SemaExprCXX.cpp revision 739d8283149d999f598a7514c6ec2b42598f51d3
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/ASTContext.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/Basic/PartialDiagnostic.h"
19#include "clang/Basic/TargetInfo.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Parse/DeclSpec.h"
22#include "llvm/ADT/STLExtras.h"
23using namespace clang;
24
25/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
26/// name (e.g., operator void const *) as an expression. This is
27/// very similar to ActOnIdentifierExpr, except that instead of
28/// providing an identifier the parser provides the type of the
29/// conversion function.
30Sema::OwningExprResult
31Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
32                                     TypeTy *Ty, bool HasTrailingLParen,
33                                     const CXXScopeSpec &SS,
34                                     bool isAddressOfOperand) {
35  //FIXME: Preserve type source info.
36  QualType ConvType = GetTypeFromParser(Ty);
37  CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
38  DeclarationName ConvName
39    = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
40  return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
41                                  &SS, isAddressOfOperand);
42}
43
44/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
45/// name (e.g., @c operator+ ) as an expression. This is very
46/// similar to ActOnIdentifierExpr, except that instead of providing
47/// an identifier the parser provides the kind of overloaded
48/// operator that was parsed.
49Sema::OwningExprResult
50Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
51                                     OverloadedOperatorKind Op,
52                                     bool HasTrailingLParen,
53                                     const CXXScopeSpec &SS,
54                                     bool isAddressOfOperand) {
55  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
56  return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
57                                  isAddressOfOperand);
58}
59
60/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
61Action::OwningExprResult
62Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
63                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
64  if (!StdNamespace)
65    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
66
67  if (isType)
68    // FIXME: Preserve type source info.
69    TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
70
71  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
72  Decl *TypeInfoDecl = LookupQualifiedName(StdNamespace, TypeInfoII,
73                                           LookupTagName);
74  RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
75  if (!TypeInfoRecordDecl)
76    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
77
78  QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
79
80  if (!isType) {
81    // C++0x [expr.typeid]p3:
82    //   When typeid is applied to an expression other than an lvalue of a
83    //   polymorphic class type [...] [the] expression is an unevaluated
84    //   operand.
85
86    // FIXME: if the type of the expression is a class type, the class
87    // shall be completely defined.
88    bool isUnevaluatedOperand = true;
89    Expr *E = static_cast<Expr *>(TyOrExpr);
90    if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
91      QualType T = E->getType();
92      if (const RecordType *RecordT = T->getAs<RecordType>()) {
93        CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
94        if (RecordD->isPolymorphic())
95          isUnevaluatedOperand = false;
96      }
97    }
98
99    // If this is an unevaluated operand, clear out the set of declaration
100    // references we have been computing.
101    if (isUnevaluatedOperand)
102      PotentiallyReferencedDeclStack.back().clear();
103  }
104
105  return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
106                                           TypeInfoType.withConst(),
107                                           SourceRange(OpLoc, RParenLoc)));
108}
109
110/// ActOnCXXBoolLiteral - Parse {true,false} literals.
111Action::OwningExprResult
112Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
113  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
114         "Unknown C++ Boolean value!");
115  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
116                                                Context.BoolTy, OpLoc));
117}
118
119/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
120Action::OwningExprResult
121Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
122  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
123}
124
125/// ActOnCXXThrow - Parse throw expressions.
126Action::OwningExprResult
127Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
128  Expr *Ex = E.takeAs<Expr>();
129  if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
130    return ExprError();
131  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
132}
133
134/// CheckCXXThrowOperand - Validate the operand of a throw.
135bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
136  // C++ [except.throw]p3:
137  //   [...] adjusting the type from "array of T" or "function returning T"
138  //   to "pointer to T" or "pointer to function returning T", [...]
139  DefaultFunctionArrayConversion(E);
140
141  //   If the type of the exception would be an incomplete type or a pointer
142  //   to an incomplete type other than (cv) void the program is ill-formed.
143  QualType Ty = E->getType();
144  int isPointer = 0;
145  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
146    Ty = Ptr->getPointeeType();
147    isPointer = 1;
148  }
149  if (!isPointer || !Ty->isVoidType()) {
150    if (RequireCompleteType(ThrowLoc, Ty,
151                            PDiag(isPointer ? diag::err_throw_incomplete_ptr
152                                            : diag::err_throw_incomplete)
153                              << E->getSourceRange()))
154      return true;
155  }
156
157  // FIXME: Construct a temporary here.
158  return false;
159}
160
161Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
162  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
163  /// is a non-lvalue expression whose value is the address of the object for
164  /// which the function is called.
165
166  if (!isa<FunctionDecl>(CurContext))
167    return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
168
169  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
170    if (MD->isInstance())
171      return Owned(new (Context) CXXThisExpr(ThisLoc,
172                                             MD->getThisType(Context)));
173
174  return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
175}
176
177/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
178/// Can be interpreted either as function-style casting ("int(x)")
179/// or class type construction ("ClassType(x,y,z)")
180/// or creation of a value-initialized type ("int()").
181Action::OwningExprResult
182Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
183                                SourceLocation LParenLoc,
184                                MultiExprArg exprs,
185                                SourceLocation *CommaLocs,
186                                SourceLocation RParenLoc) {
187  assert(TypeRep && "Missing type!");
188  // FIXME: Preserve type source info.
189  QualType Ty = GetTypeFromParser(TypeRep);
190  unsigned NumExprs = exprs.size();
191  Expr **Exprs = (Expr**)exprs.get();
192  SourceLocation TyBeginLoc = TypeRange.getBegin();
193  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
194
195  if (Ty->isDependentType() ||
196      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
197    exprs.release();
198
199    return Owned(CXXUnresolvedConstructExpr::Create(Context,
200                                                    TypeRange.getBegin(), Ty,
201                                                    LParenLoc,
202                                                    Exprs, NumExprs,
203                                                    RParenLoc));
204  }
205
206  if (Ty->isArrayType())
207    return ExprError(Diag(TyBeginLoc,
208                          diag::err_value_init_for_array_type) << FullRange);
209  if (!Ty->isVoidType() &&
210      RequireCompleteType(TyBeginLoc, Ty,
211                          PDiag(diag::err_invalid_incomplete_type_use)
212                            << FullRange))
213    return ExprError();
214
215  if (RequireNonAbstractType(TyBeginLoc, Ty,
216                             diag::err_allocation_of_abstract_type))
217    return ExprError();
218
219
220  // C++ [expr.type.conv]p1:
221  // If the expression list is a single expression, the type conversion
222  // expression is equivalent (in definedness, and if defined in meaning) to the
223  // corresponding cast expression.
224  //
225  if (NumExprs == 1) {
226    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
227    CXXMethodDecl *Method = 0;
228    if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
229                       /*FunctionalStyle=*/true))
230      return ExprError();
231
232    exprs.release();
233    if (Method) {
234      OwningExprResult CastArg
235        = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
236                               Kind, Method, Owned(Exprs[0]));
237      if (CastArg.isInvalid())
238        return ExprError();
239
240      Exprs[0] = CastArg.takeAs<Expr>();
241    }
242
243    return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
244                                                     Ty, TyBeginLoc, Kind,
245                                                     Exprs[0], RParenLoc));
246  }
247
248  if (const RecordType *RT = Ty->getAs<RecordType>()) {
249    CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
250
251    if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
252        !Record->hasTrivialDestructor()) {
253      ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
254
255      CXXConstructorDecl *Constructor
256        = PerformInitializationByConstructor(Ty, move(exprs),
257                                             TypeRange.getBegin(),
258                                             SourceRange(TypeRange.getBegin(),
259                                                         RParenLoc),
260                                             DeclarationName(),
261                                             IK_Direct,
262                                             ConstructorArgs);
263
264      if (!Constructor)
265        return ExprError();
266
267      OwningExprResult Result =
268        BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
269                                    move_arg(ConstructorArgs), RParenLoc);
270      if (Result.isInvalid())
271        return ExprError();
272
273      return MaybeBindToTemporary(Result.takeAs<Expr>());
274    }
275
276    // Fall through to value-initialize an object of class type that
277    // doesn't have a user-declared default constructor.
278  }
279
280  // C++ [expr.type.conv]p1:
281  // If the expression list specifies more than a single value, the type shall
282  // be a class with a suitably declared constructor.
283  //
284  if (NumExprs > 1)
285    return ExprError(Diag(CommaLocs[0],
286                          diag::err_builtin_func_cast_more_than_one_arg)
287      << FullRange);
288
289  assert(NumExprs == 0 && "Expected 0 expressions");
290
291  // C++ [expr.type.conv]p2:
292  // The expression T(), where T is a simple-type-specifier for a non-array
293  // complete object type or the (possibly cv-qualified) void type, creates an
294  // rvalue of the specified type, which is value-initialized.
295  //
296  exprs.release();
297  return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
298}
299
300
301/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
302/// @code new (memory) int[size][4] @endcode
303/// or
304/// @code ::new Foo(23, "hello") @endcode
305/// For the interpretation of this heap of arguments, consult the base version.
306Action::OwningExprResult
307Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
308                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
309                  SourceLocation PlacementRParen, bool ParenTypeId,
310                  Declarator &D, SourceLocation ConstructorLParen,
311                  MultiExprArg ConstructorArgs,
312                  SourceLocation ConstructorRParen) {
313  Expr *ArraySize = 0;
314  unsigned Skip = 0;
315  // If the specified type is an array, unwrap it and save the expression.
316  if (D.getNumTypeObjects() > 0 &&
317      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
318    DeclaratorChunk &Chunk = D.getTypeObject(0);
319    if (Chunk.Arr.hasStatic)
320      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
321        << D.getSourceRange());
322    if (!Chunk.Arr.NumElts)
323      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
324        << D.getSourceRange());
325    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
326    Skip = 1;
327  }
328
329  // Every dimension shall be of constant size.
330  if (D.getNumTypeObjects() > 0 &&
331      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
332    for (unsigned I = 1, N = D.getNumTypeObjects(); I < N; ++I) {
333      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
334        break;
335
336      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
337      if (Expr *NumElts = (Expr *)Array.NumElts) {
338        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
339            !NumElts->isIntegerConstantExpr(Context)) {
340          Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
341            << NumElts->getSourceRange();
342          return ExprError();
343        }
344      }
345    }
346  }
347
348  //FIXME: Store DeclaratorInfo in CXXNew expression.
349  DeclaratorInfo *DInfo = 0;
350  QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
351  if (D.isInvalidType())
352    return ExprError();
353
354  return BuildCXXNew(StartLoc, UseGlobal,
355                     PlacementLParen,
356                     move(PlacementArgs),
357                     PlacementRParen,
358                     ParenTypeId,
359                     AllocType,
360                     D.getSourceRange().getBegin(),
361                     D.getSourceRange(),
362                     Owned(ArraySize),
363                     ConstructorLParen,
364                     move(ConstructorArgs),
365                     ConstructorRParen);
366}
367
368Sema::OwningExprResult
369Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
370                  SourceLocation PlacementLParen,
371                  MultiExprArg PlacementArgs,
372                  SourceLocation PlacementRParen,
373                  bool ParenTypeId,
374                  QualType AllocType,
375                  SourceLocation TypeLoc,
376                  SourceRange TypeRange,
377                  ExprArg ArraySizeE,
378                  SourceLocation ConstructorLParen,
379                  MultiExprArg ConstructorArgs,
380                  SourceLocation ConstructorRParen) {
381  if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
382    return ExprError();
383
384  QualType ResultType = Context.getPointerType(AllocType);
385
386  // That every array dimension except the first is constant was already
387  // checked by the type check above.
388
389  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
390  //   or enumeration type with a non-negative value."
391  Expr *ArraySize = (Expr *)ArraySizeE.get();
392  if (ArraySize && !ArraySize->isTypeDependent()) {
393    QualType SizeType = ArraySize->getType();
394    if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
395      return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
396                            diag::err_array_size_not_integral)
397        << SizeType << ArraySize->getSourceRange());
398    // Let's see if this is a constant < 0. If so, we reject it out of hand.
399    // We don't care about special rules, so we tell the machinery it's not
400    // evaluated - it gives us a result in more cases.
401    if (!ArraySize->isValueDependent()) {
402      llvm::APSInt Value;
403      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
404        if (Value < llvm::APSInt(
405                        llvm::APInt::getNullValue(Value.getBitWidth()),
406                                 Value.isUnsigned()))
407          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
408                           diag::err_typecheck_negative_array_size)
409            << ArraySize->getSourceRange());
410      }
411    }
412
413    ImpCastExprToType(ArraySize, Context.getSizeType());
414  }
415
416  FunctionDecl *OperatorNew = 0;
417  FunctionDecl *OperatorDelete = 0;
418  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
419  unsigned NumPlaceArgs = PlacementArgs.size();
420  if (!AllocType->isDependentType() &&
421      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
422      FindAllocationFunctions(StartLoc,
423                              SourceRange(PlacementLParen, PlacementRParen),
424                              UseGlobal, AllocType, ArraySize, PlaceArgs,
425                              NumPlaceArgs, OperatorNew, OperatorDelete))
426    return ExprError();
427
428  bool Init = ConstructorLParen.isValid();
429  // --- Choosing a constructor ---
430  // C++ 5.3.4p15
431  // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
432  //   the object is not initialized. If the object, or any part of it, is
433  //   const-qualified, it's an error.
434  // 2) If T is a POD and there's an empty initializer, the object is value-
435  //   initialized.
436  // 3) If T is a POD and there's one initializer argument, the object is copy-
437  //   constructed.
438  // 4) If T is a POD and there's more initializer arguments, it's an error.
439  // 5) If T is not a POD, the initializer arguments are used as constructor
440  //   arguments.
441  //
442  // Or by the C++0x formulation:
443  // 1) If there's no initializer, the object is default-initialized according
444  //    to C++0x rules.
445  // 2) Otherwise, the object is direct-initialized.
446  CXXConstructorDecl *Constructor = 0;
447  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
448  const RecordType *RT;
449  unsigned NumConsArgs = ConstructorArgs.size();
450  if (AllocType->isDependentType()) {
451    // Skip all the checks.
452  } else if ((RT = AllocType->getAs<RecordType>()) &&
453             !AllocType->isAggregateType()) {
454    ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
455
456    Constructor = PerformInitializationByConstructor(
457                      AllocType, move(ConstructorArgs),
458                      TypeLoc,
459                      SourceRange(TypeLoc, ConstructorRParen),
460                      RT->getDecl()->getDeclName(),
461                      NumConsArgs != 0 ? IK_Direct : IK_Default,
462                      ConvertedConstructorArgs);
463    if (!Constructor)
464      return ExprError();
465
466    // Take the converted constructor arguments and use them for the new
467    // expression.
468    NumConsArgs = ConvertedConstructorArgs.size();
469    ConsArgs = (Expr **)ConvertedConstructorArgs.take();
470  } else {
471    if (!Init) {
472      // FIXME: Check that no subpart is const.
473      if (AllocType.isConstQualified())
474        return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
475                           << TypeRange);
476    } else if (NumConsArgs == 0) {
477      // Object is value-initialized. Do nothing.
478    } else if (NumConsArgs == 1) {
479      // Object is direct-initialized.
480      // FIXME: What DeclarationName do we pass in here?
481      if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
482                                DeclarationName() /*AllocType.getAsString()*/,
483                                /*DirectInit=*/true))
484        return ExprError();
485    } else {
486      return ExprError(Diag(StartLoc,
487                            diag::err_builtin_direct_init_more_than_one_arg)
488        << SourceRange(ConstructorLParen, ConstructorRParen));
489    }
490  }
491
492  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
493
494  PlacementArgs.release();
495  ConstructorArgs.release();
496  ArraySizeE.release();
497  return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
498                        NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
499                        ConsArgs, NumConsArgs, OperatorDelete, ResultType,
500                        StartLoc, Init ? ConstructorRParen : SourceLocation()));
501}
502
503/// CheckAllocatedType - Checks that a type is suitable as the allocated type
504/// in a new-expression.
505/// dimension off and stores the size expression in ArraySize.
506bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
507                              SourceRange R) {
508  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
509  //   abstract class type or array thereof.
510  if (AllocType->isFunctionType())
511    return Diag(Loc, diag::err_bad_new_type)
512      << AllocType << 0 << R;
513  else if (AllocType->isReferenceType())
514    return Diag(Loc, diag::err_bad_new_type)
515      << AllocType << 1 << R;
516  else if (!AllocType->isDependentType() &&
517           RequireCompleteType(Loc, AllocType,
518                               PDiag(diag::err_new_incomplete_type)
519                                 << R))
520    return true;
521  else if (RequireNonAbstractType(Loc, AllocType,
522                                  diag::err_allocation_of_abstract_type))
523    return true;
524
525  return false;
526}
527
528/// FindAllocationFunctions - Finds the overloads of operator new and delete
529/// that are appropriate for the allocation.
530bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
531                                   bool UseGlobal, QualType AllocType,
532                                   bool IsArray, Expr **PlaceArgs,
533                                   unsigned NumPlaceArgs,
534                                   FunctionDecl *&OperatorNew,
535                                   FunctionDecl *&OperatorDelete) {
536  // --- Choosing an allocation function ---
537  // C++ 5.3.4p8 - 14 & 18
538  // 1) If UseGlobal is true, only look in the global scope. Else, also look
539  //   in the scope of the allocated class.
540  // 2) If an array size is given, look for operator new[], else look for
541  //   operator new.
542  // 3) The first argument is always size_t. Append the arguments from the
543  //   placement form.
544  // FIXME: Also find the appropriate delete operator.
545
546  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
547  // We don't care about the actual value of this argument.
548  // FIXME: Should the Sema create the expression and embed it in the syntax
549  // tree? Or should the consumer just recalculate the value?
550  IntegerLiteral Size(llvm::APInt::getNullValue(
551                      Context.Target.getPointerWidth(0)),
552                      Context.getSizeType(),
553                      SourceLocation());
554  AllocArgs[0] = &Size;
555  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
556
557  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
558                                        IsArray ? OO_Array_New : OO_New);
559  if (AllocType->isRecordType() && !UseGlobal) {
560    CXXRecordDecl *Record
561      = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
562    // FIXME: We fail to find inherited overloads.
563    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
564                          AllocArgs.size(), Record, /*AllowMissing=*/true,
565                          OperatorNew))
566      return true;
567  }
568  if (!OperatorNew) {
569    // Didn't find a member overload. Look for a global one.
570    DeclareGlobalNewDelete();
571    DeclContext *TUDecl = Context.getTranslationUnitDecl();
572    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
573                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
574                          OperatorNew))
575      return true;
576  }
577
578  // FindAllocationOverload can change the passed in arguments, so we need to
579  // copy them back.
580  if (NumPlaceArgs > 0)
581    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
582
583  return false;
584}
585
586/// FindAllocationOverload - Find an fitting overload for the allocation
587/// function in the specified scope.
588bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
589                                  DeclarationName Name, Expr** Args,
590                                  unsigned NumArgs, DeclContext *Ctx,
591                                  bool AllowMissing, FunctionDecl *&Operator) {
592  DeclContext::lookup_iterator Alloc, AllocEnd;
593  llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
594  if (Alloc == AllocEnd) {
595    if (AllowMissing)
596      return false;
597    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
598      << Name << Range;
599  }
600
601  OverloadCandidateSet Candidates;
602  for (; Alloc != AllocEnd; ++Alloc) {
603    // Even member operator new/delete are implicitly treated as
604    // static, so don't use AddMemberCandidate.
605    if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
606      AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
607                           /*SuppressUserConversions=*/false);
608  }
609
610  // Do the resolution.
611  OverloadCandidateSet::iterator Best;
612  switch(BestViableFunction(Candidates, StartLoc, Best)) {
613  case OR_Success: {
614    // Got one!
615    FunctionDecl *FnDecl = Best->Function;
616    // The first argument is size_t, and the first parameter must be size_t,
617    // too. This is checked on declaration and can be assumed. (It can't be
618    // asserted on, though, since invalid decls are left in there.)
619    for (unsigned i = 1; i < NumArgs; ++i) {
620      // FIXME: Passing word to diagnostic.
621      if (PerformCopyInitialization(Args[i],
622                                    FnDecl->getParamDecl(i)->getType(),
623                                    "passing"))
624        return true;
625    }
626    Operator = FnDecl;
627    return false;
628  }
629
630  case OR_No_Viable_Function:
631    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
632      << Name << Range;
633    PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
634    return true;
635
636  case OR_Ambiguous:
637    Diag(StartLoc, diag::err_ovl_ambiguous_call)
638      << Name << Range;
639    PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
640    return true;
641
642  case OR_Deleted:
643    Diag(StartLoc, diag::err_ovl_deleted_call)
644      << Best->Function->isDeleted()
645      << Name << Range;
646    PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
647    return true;
648  }
649  assert(false && "Unreachable, bad result from BestViableFunction");
650  return true;
651}
652
653
654/// DeclareGlobalNewDelete - Declare the global forms of operator new and
655/// delete. These are:
656/// @code
657///   void* operator new(std::size_t) throw(std::bad_alloc);
658///   void* operator new[](std::size_t) throw(std::bad_alloc);
659///   void operator delete(void *) throw();
660///   void operator delete[](void *) throw();
661/// @endcode
662/// Note that the placement and nothrow forms of new are *not* implicitly
663/// declared. Their use requires including \<new\>.
664void Sema::DeclareGlobalNewDelete() {
665  if (GlobalNewDeleteDeclared)
666    return;
667
668  // C++ [basic.std.dynamic]p2:
669  //   [...] The following allocation and deallocation functions (18.4) are
670  //   implicitly declared in global scope in each translation unit of a
671  //   program
672  //
673  //     void* operator new(std::size_t) throw(std::bad_alloc);
674  //     void* operator new[](std::size_t) throw(std::bad_alloc);
675  //     void  operator delete(void*) throw();
676  //     void  operator delete[](void*) throw();
677  //
678  //   These implicit declarations introduce only the function names operator
679  //   new, operator new[], operator delete, operator delete[].
680  //
681  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
682  // "std" or "bad_alloc" as necessary to form the exception specification.
683  // However, we do not make these implicit declarations visible to name
684  // lookup.
685  if (!StdNamespace) {
686    // The "std" namespace has not yet been defined, so build one implicitly.
687    StdNamespace = NamespaceDecl::Create(Context,
688                                         Context.getTranslationUnitDecl(),
689                                         SourceLocation(),
690                                         &PP.getIdentifierTable().get("std"));
691    StdNamespace->setImplicit(true);
692  }
693
694  if (!StdBadAlloc) {
695    // The "std::bad_alloc" class has not yet been declared, so build it
696    // implicitly.
697    StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
698                                        StdNamespace,
699                                        SourceLocation(),
700                                      &PP.getIdentifierTable().get("bad_alloc"),
701                                        SourceLocation(), 0);
702    StdBadAlloc->setImplicit(true);
703  }
704
705  GlobalNewDeleteDeclared = true;
706
707  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
708  QualType SizeT = Context.getSizeType();
709
710  DeclareGlobalAllocationFunction(
711      Context.DeclarationNames.getCXXOperatorName(OO_New),
712      VoidPtr, SizeT);
713  DeclareGlobalAllocationFunction(
714      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
715      VoidPtr, SizeT);
716  DeclareGlobalAllocationFunction(
717      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
718      Context.VoidTy, VoidPtr);
719  DeclareGlobalAllocationFunction(
720      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
721      Context.VoidTy, VoidPtr);
722}
723
724/// DeclareGlobalAllocationFunction - Declares a single implicit global
725/// allocation function if it doesn't already exist.
726void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
727                                           QualType Return, QualType Argument) {
728  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
729
730  // Check if this function is already declared.
731  {
732    DeclContext::lookup_iterator Alloc, AllocEnd;
733    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
734         Alloc != AllocEnd; ++Alloc) {
735      // FIXME: Do we need to check for default arguments here?
736      FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
737      if (Func->getNumParams() == 1 &&
738          Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
739        return;
740    }
741  }
742
743  QualType BadAllocType;
744  bool HasBadAllocExceptionSpec
745    = (Name.getCXXOverloadedOperator() == OO_New ||
746       Name.getCXXOverloadedOperator() == OO_Array_New);
747  if (HasBadAllocExceptionSpec) {
748    assert(StdBadAlloc && "Must have std::bad_alloc declared");
749    BadAllocType = Context.getTypeDeclType(StdBadAlloc);
750  }
751
752  QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
753                                            true, false,
754                                            HasBadAllocExceptionSpec? 1 : 0,
755                                            &BadAllocType);
756  FunctionDecl *Alloc =
757    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
758                         FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
759  Alloc->setImplicit();
760  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
761                                           0, Argument, /*DInfo=*/0,
762                                           VarDecl::None, 0);
763  Alloc->setParams(Context, &Param, 1);
764
765  // FIXME: Also add this declaration to the IdentifierResolver, but
766  // make sure it is at the end of the chain to coincide with the
767  // global scope.
768  ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
769}
770
771/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
772/// @code ::delete ptr; @endcode
773/// or
774/// @code delete [] ptr; @endcode
775Action::OwningExprResult
776Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
777                     bool ArrayForm, ExprArg Operand) {
778  // C++ [expr.delete]p1:
779  //   The operand shall have a pointer type, or a class type having a single
780  //   conversion function to a pointer type. The result has type void.
781  //
782  // DR599 amends "pointer type" to "pointer to object type" in both cases.
783
784  FunctionDecl *OperatorDelete = 0;
785
786  Expr *Ex = (Expr *)Operand.get();
787  if (!Ex->isTypeDependent()) {
788    QualType Type = Ex->getType();
789
790    if (const RecordType *Record = Type->getAs<RecordType>()) {
791      llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
792      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
793      OverloadedFunctionDecl *Conversions =
794        RD->getVisibleConversionFunctions();
795
796      for (OverloadedFunctionDecl::function_iterator
797             Func = Conversions->function_begin(),
798             FuncEnd = Conversions->function_end();
799           Func != FuncEnd; ++Func) {
800        // Skip over templated conversion functions; they aren't considered.
801        if (isa<FunctionTemplateDecl>(*Func))
802          continue;
803
804        CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
805
806        QualType ConvType = Conv->getConversionType().getNonReferenceType();
807        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
808          if (ConvPtrType->getPointeeType()->isObjectType())
809            ObjectPtrConversions.push_back(Conv);
810      }
811      if (ObjectPtrConversions.size() == 1) {
812        // We have a single conversion to a pointer-to-object type. Perform
813        // that conversion.
814        Operand.release();
815        if (!PerformImplicitConversion(Ex,
816                            ObjectPtrConversions.front()->getConversionType(),
817                                      "converting")) {
818          Operand = Owned(Ex);
819          Type = Ex->getType();
820        }
821      }
822      else if (ObjectPtrConversions.size() > 1) {
823        Diag(StartLoc, diag::err_ambiguous_delete_operand)
824              << Type << Ex->getSourceRange();
825        for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
826          CXXConversionDecl *Conv = ObjectPtrConversions[i];
827          Diag(Conv->getLocation(), diag::err_ovl_candidate);
828        }
829        return ExprError();
830      }
831    }
832
833    if (!Type->isPointerType())
834      return ExprError(Diag(StartLoc, diag::err_delete_operand)
835        << Type << Ex->getSourceRange());
836
837    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
838    if (Pointee->isFunctionType() || Pointee->isVoidType())
839      return ExprError(Diag(StartLoc, diag::err_delete_operand)
840        << Type << Ex->getSourceRange());
841    else if (!Pointee->isDependentType() &&
842             RequireCompleteType(StartLoc, Pointee,
843                                 PDiag(diag::warn_delete_incomplete)
844                                   << Ex->getSourceRange()))
845      return ExprError();
846
847    // FIXME: This should be shared with the code for finding the delete
848    // operator in ActOnCXXNew.
849    IntegerLiteral Size(llvm::APInt::getNullValue(
850                        Context.Target.getPointerWidth(0)),
851                        Context.getSizeType(),
852                        SourceLocation());
853    ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy),
854                          CastExpr::CK_Unknown, &Size, false);
855    Expr *DeleteArg = &Cast;
856
857    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
858                                      ArrayForm ? OO_Array_Delete : OO_Delete);
859
860    if (Pointee->isRecordType() && !UseGlobal) {
861      CXXRecordDecl *Record
862        = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
863      // FIXME: We fail to find inherited overloads.
864      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
865                                 &DeleteArg, 1, Record, /*AllowMissing=*/true,
866                                 OperatorDelete))
867        return ExprError();
868      if (!Record->hasTrivialDestructor())
869        if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context))
870          MarkDeclarationReferenced(StartLoc,
871                                    const_cast<CXXDestructorDecl*>(Dtor));
872    }
873
874    if (!OperatorDelete) {
875      // Didn't find a member overload. Look for a global one.
876      DeclareGlobalNewDelete();
877      DeclContext *TUDecl = Context.getTranslationUnitDecl();
878      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
879                                 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false,
880                                 OperatorDelete))
881        return ExprError();
882    }
883
884    // FIXME: Check access and ambiguity of operator delete and destructor.
885  }
886
887  Operand.release();
888  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
889                                           OperatorDelete, Ex, StartLoc));
890}
891
892
893/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
894/// C++ if/switch/while/for statement.
895/// e.g: "if (int x = f()) {...}"
896Action::OwningExprResult
897Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
898                                       Declarator &D,
899                                       SourceLocation EqualLoc,
900                                       ExprArg AssignExprVal) {
901  assert(AssignExprVal.get() && "Null assignment expression");
902
903  // C++ 6.4p2:
904  // The declarator shall not specify a function or an array.
905  // The type-specifier-seq shall not contain typedef and shall not declare a
906  // new class or enumeration.
907
908  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
909         "Parser allowed 'typedef' as storage class of condition decl.");
910
911  // FIXME: Store DeclaratorInfo in the expression.
912  DeclaratorInfo *DInfo = 0;
913  TagDecl *OwnedTag = 0;
914  QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
915
916  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
917    // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
918    // would be created and CXXConditionDeclExpr wants a VarDecl.
919    return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
920      << SourceRange(StartLoc, EqualLoc));
921  } else if (Ty->isArrayType()) { // ...or an array.
922    Diag(StartLoc, diag::err_invalid_use_of_array_type)
923      << SourceRange(StartLoc, EqualLoc);
924  } else if (OwnedTag && OwnedTag->isDefinition()) {
925    // The type-specifier-seq shall not declare a new class or enumeration.
926    Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
927  }
928
929  DeclPtrTy Dcl = ActOnDeclarator(S, D);
930  if (!Dcl)
931    return ExprError();
932  AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
933
934  // Mark this variable as one that is declared within a conditional.
935  // We know that the decl had to be a VarDecl because that is the only type of
936  // decl that can be assigned and the grammar requires an '='.
937  VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
938  VD->setDeclaredInCondition(true);
939  return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
940}
941
942/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
943bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
944  // C++ 6.4p4:
945  // The value of a condition that is an initialized declaration in a statement
946  // other than a switch statement is the value of the declared variable
947  // implicitly converted to type bool. If that conversion is ill-formed, the
948  // program is ill-formed.
949  // The value of a condition that is an expression is the value of the
950  // expression, implicitly converted to bool.
951  //
952  return PerformContextuallyConvertToBool(CondExpr);
953}
954
955/// Helper function to determine whether this is the (deprecated) C++
956/// conversion from a string literal to a pointer to non-const char or
957/// non-const wchar_t (for narrow and wide string literals,
958/// respectively).
959bool
960Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
961  // Look inside the implicit cast, if it exists.
962  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
963    From = Cast->getSubExpr();
964
965  // A string literal (2.13.4) that is not a wide string literal can
966  // be converted to an rvalue of type "pointer to char"; a wide
967  // string literal can be converted to an rvalue of type "pointer
968  // to wchar_t" (C++ 4.2p2).
969  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
970    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
971      if (const BuiltinType *ToPointeeType
972          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
973        // This conversion is considered only when there is an
974        // explicit appropriate pointer target type (C++ 4.2p2).
975        if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
976            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
977             (!StrLit->isWide() &&
978              (ToPointeeType->getKind() == BuiltinType::Char_U ||
979               ToPointeeType->getKind() == BuiltinType::Char_S))))
980          return true;
981      }
982
983  return false;
984}
985
986/// PerformImplicitConversion - Perform an implicit conversion of the
987/// expression From to the type ToType. Returns true if there was an
988/// error, false otherwise. The expression From is replaced with the
989/// converted expression. Flavor is the kind of conversion we're
990/// performing, used in the error message. If @p AllowExplicit,
991/// explicit user-defined conversions are permitted. @p Elidable should be true
992/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
993/// resolution works differently in that case.
994bool
995Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
996                                const char *Flavor, bool AllowExplicit,
997                                bool Elidable) {
998  ImplicitConversionSequence ICS;
999  return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
1000                                   Elidable, ICS);
1001}
1002
1003bool
1004Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1005                                const char *Flavor, bool AllowExplicit,
1006                                bool Elidable,
1007                                ImplicitConversionSequence& ICS) {
1008  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1009  if (Elidable && getLangOptions().CPlusPlus0x) {
1010    ICS = TryImplicitConversion(From, ToType,
1011                                /*SuppressUserConversions=*/false,
1012                                AllowExplicit,
1013                                /*ForceRValue=*/true,
1014                                /*InOverloadResolution=*/false);
1015  }
1016  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
1017    ICS = TryImplicitConversion(From, ToType,
1018                                /*SuppressUserConversions=*/false,
1019                                AllowExplicit,
1020                                /*ForceRValue=*/false,
1021                                /*InOverloadResolution=*/false);
1022  }
1023  return PerformImplicitConversion(From, ToType, ICS, Flavor);
1024}
1025
1026/// PerformImplicitConversion - Perform an implicit conversion of the
1027/// expression From to the type ToType using the pre-computed implicit
1028/// conversion sequence ICS. Returns true if there was an error, false
1029/// otherwise. The expression From is replaced with the converted
1030/// expression. Flavor is the kind of conversion we're performing,
1031/// used in the error message.
1032bool
1033Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1034                                const ImplicitConversionSequence &ICS,
1035                                const char* Flavor) {
1036  switch (ICS.ConversionKind) {
1037  case ImplicitConversionSequence::StandardConversion:
1038    if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
1039      return true;
1040    break;
1041
1042  case ImplicitConversionSequence::UserDefinedConversion: {
1043
1044      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1045      CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
1046      QualType BeforeToType;
1047      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1048        CastKind = CastExpr::CK_UserDefinedConversion;
1049
1050        // If the user-defined conversion is specified by a conversion function,
1051        // the initial standard conversion sequence converts the source type to
1052        // the implicit object parameter of the conversion function.
1053        BeforeToType = Context.getTagDeclType(Conv->getParent());
1054      } else if (const CXXConstructorDecl *Ctor =
1055                  dyn_cast<CXXConstructorDecl>(FD)) {
1056        CastKind = CastExpr::CK_ConstructorConversion;
1057
1058        // If the user-defined conversion is specified by a constructor, the
1059        // initial standard conversion sequence converts the source type to the
1060        // type required by the argument of the constructor
1061        BeforeToType = Ctor->getParamDecl(0)->getType();
1062      }
1063      else
1064        assert(0 && "Unknown conversion function kind!");
1065
1066      if (PerformImplicitConversion(From, BeforeToType,
1067                                    ICS.UserDefined.Before, "converting"))
1068        return true;
1069
1070      OwningExprResult CastArg
1071        = BuildCXXCastArgument(From->getLocStart(),
1072                               ToType.getNonReferenceType(),
1073                               CastKind, cast<CXXMethodDecl>(FD),
1074                               Owned(From));
1075
1076      if (CastArg.isInvalid())
1077        return true;
1078
1079      From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
1080                                            CastKind, CastArg.takeAs<Expr>(),
1081                                            ToType->isLValueReferenceType());
1082      return false;
1083    }
1084
1085  case ImplicitConversionSequence::EllipsisConversion:
1086    assert(false && "Cannot perform an ellipsis conversion");
1087    return false;
1088
1089  case ImplicitConversionSequence::BadConversion:
1090    return true;
1091  }
1092
1093  // Everything went well.
1094  return false;
1095}
1096
1097/// PerformImplicitConversion - Perform an implicit conversion of the
1098/// expression From to the type ToType by following the standard
1099/// conversion sequence SCS. Returns true if there was an error, false
1100/// otherwise. The expression From is replaced with the converted
1101/// expression. Flavor is the context in which we're performing this
1102/// conversion, for use in error messages.
1103bool
1104Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1105                                const StandardConversionSequence& SCS,
1106                                const char *Flavor) {
1107  // Overall FIXME: we are recomputing too many types here and doing far too
1108  // much extra work. What this means is that we need to keep track of more
1109  // information that is computed when we try the implicit conversion initially,
1110  // so that we don't need to recompute anything here.
1111  QualType FromType = From->getType();
1112
1113  if (SCS.CopyConstructor) {
1114    // FIXME: When can ToType be a reference type?
1115    assert(!ToType->isReferenceType());
1116
1117    OwningExprResult FromResult =
1118      BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1119                            ToType, SCS.CopyConstructor,
1120                            MultiExprArg(*this, (void**)&From, 1));
1121
1122    if (FromResult.isInvalid())
1123      return true;
1124
1125    From = FromResult.takeAs<Expr>();
1126    return false;
1127  }
1128
1129  // Perform the first implicit conversion.
1130  switch (SCS.First) {
1131  case ICK_Identity:
1132  case ICK_Lvalue_To_Rvalue:
1133    // Nothing to do.
1134    break;
1135
1136  case ICK_Array_To_Pointer:
1137    FromType = Context.getArrayDecayedType(FromType);
1138    ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
1139    break;
1140
1141  case ICK_Function_To_Pointer:
1142    if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
1143      FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1144      if (!Fn)
1145        return true;
1146
1147      if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1148        return true;
1149
1150      FixOverloadedFunctionReference(From, Fn);
1151      FromType = From->getType();
1152    }
1153    FromType = Context.getPointerType(FromType);
1154    ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
1155    break;
1156
1157  default:
1158    assert(false && "Improper first standard conversion");
1159    break;
1160  }
1161
1162  // Perform the second implicit conversion
1163  switch (SCS.Second) {
1164  case ICK_Identity:
1165    // Nothing to do.
1166    break;
1167
1168  case ICK_Integral_Promotion:
1169  case ICK_Floating_Promotion:
1170  case ICK_Complex_Promotion:
1171  case ICK_Integral_Conversion:
1172  case ICK_Floating_Conversion:
1173  case ICK_Complex_Conversion:
1174  case ICK_Floating_Integral:
1175  case ICK_Complex_Real:
1176  case ICK_Compatible_Conversion:
1177      // FIXME: Go deeper to get the unqualified type!
1178    FromType = ToType.getUnqualifiedType();
1179    ImpCastExprToType(From, FromType);
1180    break;
1181
1182  case ICK_Pointer_Conversion: {
1183    if (SCS.IncompatibleObjC) {
1184      // Diagnose incompatible Objective-C conversions
1185      Diag(From->getSourceRange().getBegin(),
1186           diag::ext_typecheck_convert_incompatible_pointer)
1187        << From->getType() << ToType << Flavor
1188        << From->getSourceRange();
1189    }
1190
1191
1192    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1193    if (CheckPointerConversion(From, ToType, Kind))
1194      return true;
1195    ImpCastExprToType(From, ToType, Kind);
1196    break;
1197  }
1198
1199  case ICK_Pointer_Member: {
1200    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1201    if (CheckMemberPointerConversion(From, ToType, Kind))
1202      return true;
1203    ImpCastExprToType(From, ToType, Kind);
1204    break;
1205  }
1206  case ICK_Boolean_Conversion:
1207    FromType = Context.BoolTy;
1208    ImpCastExprToType(From, FromType);
1209    break;
1210
1211  default:
1212    assert(false && "Improper second standard conversion");
1213    break;
1214  }
1215
1216  switch (SCS.Third) {
1217  case ICK_Identity:
1218    // Nothing to do.
1219    break;
1220
1221  case ICK_Qualification:
1222    // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1223    // references.
1224    ImpCastExprToType(From, ToType.getNonReferenceType(),
1225                      CastExpr::CK_Unknown,
1226                      ToType->isLValueReferenceType());
1227    break;
1228
1229  default:
1230    assert(false && "Improper second standard conversion");
1231    break;
1232  }
1233
1234  return false;
1235}
1236
1237Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1238                                                 SourceLocation KWLoc,
1239                                                 SourceLocation LParen,
1240                                                 TypeTy *Ty,
1241                                                 SourceLocation RParen) {
1242  QualType T = GetTypeFromParser(Ty);
1243
1244  // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1245  // all traits except __is_class, __is_enum and __is_union require a the type
1246  // to be complete.
1247  if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1248    if (RequireCompleteType(KWLoc, T,
1249                            diag::err_incomplete_type_used_in_type_trait_expr))
1250      return ExprError();
1251  }
1252
1253  // There is no point in eagerly computing the value. The traits are designed
1254  // to be used from type trait templates, so Ty will be a template parameter
1255  // 99% of the time.
1256  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1257                                                RParen, Context.BoolTy));
1258}
1259
1260QualType Sema::CheckPointerToMemberOperands(
1261  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
1262  const char *OpSpelling = isIndirect ? "->*" : ".*";
1263  // C++ 5.5p2
1264  //   The binary operator .* [p3: ->*] binds its second operand, which shall
1265  //   be of type "pointer to member of T" (where T is a completely-defined
1266  //   class type) [...]
1267  QualType RType = rex->getType();
1268  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
1269  if (!MemPtr) {
1270    Diag(Loc, diag::err_bad_memptr_rhs)
1271      << OpSpelling << RType << rex->getSourceRange();
1272    return QualType();
1273  }
1274
1275  QualType Class(MemPtr->getClass(), 0);
1276
1277  // C++ 5.5p2
1278  //   [...] to its first operand, which shall be of class T or of a class of
1279  //   which T is an unambiguous and accessible base class. [p3: a pointer to
1280  //   such a class]
1281  QualType LType = lex->getType();
1282  if (isIndirect) {
1283    if (const PointerType *Ptr = LType->getAs<PointerType>())
1284      LType = Ptr->getPointeeType().getNonReferenceType();
1285    else {
1286      Diag(Loc, diag::err_bad_memptr_lhs)
1287        << OpSpelling << 1 << LType << lex->getSourceRange();
1288      return QualType();
1289    }
1290  }
1291
1292  if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1293      Context.getCanonicalType(LType).getUnqualifiedType()) {
1294    BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1295                    /*DetectVirtual=*/false);
1296    // FIXME: Would it be useful to print full ambiguity paths, or is that
1297    // overkill?
1298    if (!IsDerivedFrom(LType, Class, Paths) ||
1299        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1300      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1301        << (int)isIndirect << lex->getType() << lex->getSourceRange();
1302      return QualType();
1303    }
1304  }
1305
1306  // C++ 5.5p2
1307  //   The result is an object or a function of the type specified by the
1308  //   second operand.
1309  // The cv qualifiers are the union of those in the pointer and the left side,
1310  // in accordance with 5.5p5 and 5.2.5.
1311  // FIXME: This returns a dereferenced member function pointer as a normal
1312  // function type. However, the only operation valid on such functions is
1313  // calling them. There's also a GCC extension to get a function pointer to the
1314  // thing, which is another complication, because this type - unlike the type
1315  // that is the result of this expression - takes the class as the first
1316  // argument.
1317  // We probably need a "MemberFunctionClosureType" or something like that.
1318  QualType Result = MemPtr->getPointeeType();
1319  if (LType.isConstQualified())
1320    Result.addConst();
1321  if (LType.isVolatileQualified())
1322    Result.addVolatile();
1323  return Result;
1324}
1325
1326/// \brief Get the target type of a standard or user-defined conversion.
1327static QualType TargetType(const ImplicitConversionSequence &ICS) {
1328  assert((ICS.ConversionKind ==
1329              ImplicitConversionSequence::StandardConversion ||
1330          ICS.ConversionKind ==
1331              ImplicitConversionSequence::UserDefinedConversion) &&
1332         "function only valid for standard or user-defined conversions");
1333  if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1334    return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1335  return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1336}
1337
1338/// \brief Try to convert a type to another according to C++0x 5.16p3.
1339///
1340/// This is part of the parameter validation for the ? operator. If either
1341/// value operand is a class type, the two operands are attempted to be
1342/// converted to each other. This function does the conversion in one direction.
1343/// It emits a diagnostic and returns true only if it finds an ambiguous
1344/// conversion.
1345static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1346                                SourceLocation QuestionLoc,
1347                                ImplicitConversionSequence &ICS) {
1348  // C++0x 5.16p3
1349  //   The process for determining whether an operand expression E1 of type T1
1350  //   can be converted to match an operand expression E2 of type T2 is defined
1351  //   as follows:
1352  //   -- If E2 is an lvalue:
1353  if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1354    //   E1 can be converted to match E2 if E1 can be implicitly converted to
1355    //   type "lvalue reference to T2", subject to the constraint that in the
1356    //   conversion the reference must bind directly to E1.
1357    if (!Self.CheckReferenceInit(From,
1358                            Self.Context.getLValueReferenceType(To->getType()),
1359                                 To->getLocStart(),
1360                                 /*SuppressUserConversions=*/false,
1361                                 /*AllowExplicit=*/false,
1362                                 /*ForceRValue=*/false,
1363                                 &ICS))
1364    {
1365      assert((ICS.ConversionKind ==
1366                  ImplicitConversionSequence::StandardConversion ||
1367              ICS.ConversionKind ==
1368                  ImplicitConversionSequence::UserDefinedConversion) &&
1369             "expected a definite conversion");
1370      bool DirectBinding =
1371        ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1372        ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1373      if (DirectBinding)
1374        return false;
1375    }
1376  }
1377  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1378  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
1379  //      -- if E1 and E2 have class type, and the underlying class types are
1380  //         the same or one is a base class of the other:
1381  QualType FTy = From->getType();
1382  QualType TTy = To->getType();
1383  const RecordType *FRec = FTy->getAs<RecordType>();
1384  const RecordType *TRec = TTy->getAs<RecordType>();
1385  bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1386  if (FRec && TRec && (FRec == TRec ||
1387        FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1388    //         E1 can be converted to match E2 if the class of T2 is the
1389    //         same type as, or a base class of, the class of T1, and
1390    //         [cv2 > cv1].
1391    if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1392      // Could still fail if there's no copy constructor.
1393      // FIXME: Is this a hard error then, or just a conversion failure? The
1394      // standard doesn't say.
1395      ICS = Self.TryCopyInitialization(From, TTy,
1396                                       /*SuppressUserConversions=*/false,
1397                                       /*ForceRValue=*/false,
1398                                       /*InOverloadResolution=*/false);
1399    }
1400  } else {
1401    //     -- Otherwise: E1 can be converted to match E2 if E1 can be
1402    //        implicitly converted to the type that expression E2 would have
1403    //        if E2 were converted to an rvalue.
1404    // First find the decayed type.
1405    if (TTy->isFunctionType())
1406      TTy = Self.Context.getPointerType(TTy);
1407    else if (TTy->isArrayType())
1408      TTy = Self.Context.getArrayDecayedType(TTy);
1409
1410    // Now try the implicit conversion.
1411    // FIXME: This doesn't detect ambiguities.
1412    ICS = Self.TryImplicitConversion(From, TTy,
1413                                     /*SuppressUserConversions=*/false,
1414                                     /*AllowExplicit=*/false,
1415                                     /*ForceRValue=*/false,
1416                                     /*InOverloadResolution=*/false);
1417  }
1418  return false;
1419}
1420
1421/// \brief Try to find a common type for two according to C++0x 5.16p5.
1422///
1423/// This is part of the parameter validation for the ? operator. If either
1424/// value operand is a class type, overload resolution is used to find a
1425/// conversion to a common type.
1426static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1427                                    SourceLocation Loc) {
1428  Expr *Args[2] = { LHS, RHS };
1429  OverloadCandidateSet CandidateSet;
1430  Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1431
1432  OverloadCandidateSet::iterator Best;
1433  switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
1434    case Sema::OR_Success:
1435      // We found a match. Perform the conversions on the arguments and move on.
1436      if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1437                                         Best->Conversions[0], "converting") ||
1438          Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1439                                         Best->Conversions[1], "converting"))
1440        break;
1441      return false;
1442
1443    case Sema::OR_No_Viable_Function:
1444      Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1445        << LHS->getType() << RHS->getType()
1446        << LHS->getSourceRange() << RHS->getSourceRange();
1447      return true;
1448
1449    case Sema::OR_Ambiguous:
1450      Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1451        << LHS->getType() << RHS->getType()
1452        << LHS->getSourceRange() << RHS->getSourceRange();
1453      // FIXME: Print the possible common types by printing the return types of
1454      // the viable candidates.
1455      break;
1456
1457    case Sema::OR_Deleted:
1458      assert(false && "Conditional operator has only built-in overloads");
1459      break;
1460  }
1461  return true;
1462}
1463
1464/// \brief Perform an "extended" implicit conversion as returned by
1465/// TryClassUnification.
1466///
1467/// TryClassUnification generates ICSs that include reference bindings.
1468/// PerformImplicitConversion is not suitable for this; it chokes if the
1469/// second part of a standard conversion is ICK_DerivedToBase. This function
1470/// handles the reference binding specially.
1471static bool ConvertForConditional(Sema &Self, Expr *&E,
1472                                  const ImplicitConversionSequence &ICS) {
1473  if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1474      ICS.Standard.ReferenceBinding) {
1475    assert(ICS.Standard.DirectBinding &&
1476           "TryClassUnification should never generate indirect ref bindings");
1477    // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1478    // redoing all the work.
1479    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1480                                        TargetType(ICS)),
1481                                   /*FIXME:*/E->getLocStart(),
1482                                   /*SuppressUserConversions=*/false,
1483                                   /*AllowExplicit=*/false,
1484                                   /*ForceRValue=*/false);
1485  }
1486  if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1487      ICS.UserDefined.After.ReferenceBinding) {
1488    assert(ICS.UserDefined.After.DirectBinding &&
1489           "TryClassUnification should never generate indirect ref bindings");
1490    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1491                                        TargetType(ICS)),
1492                                   /*FIXME:*/E->getLocStart(),
1493                                   /*SuppressUserConversions=*/false,
1494                                   /*AllowExplicit=*/false,
1495                                   /*ForceRValue=*/false);
1496  }
1497  if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1498    return true;
1499  return false;
1500}
1501
1502/// \brief Check the operands of ?: under C++ semantics.
1503///
1504/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1505/// extension. In this case, LHS == Cond. (But they're not aliases.)
1506QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1507                                           SourceLocation QuestionLoc) {
1508  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1509  // interface pointers.
1510
1511  // C++0x 5.16p1
1512  //   The first expression is contextually converted to bool.
1513  if (!Cond->isTypeDependent()) {
1514    if (CheckCXXBooleanCondition(Cond))
1515      return QualType();
1516  }
1517
1518  // Either of the arguments dependent?
1519  if (LHS->isTypeDependent() || RHS->isTypeDependent())
1520    return Context.DependentTy;
1521
1522  // C++0x 5.16p2
1523  //   If either the second or the third operand has type (cv) void, ...
1524  QualType LTy = LHS->getType();
1525  QualType RTy = RHS->getType();
1526  bool LVoid = LTy->isVoidType();
1527  bool RVoid = RTy->isVoidType();
1528  if (LVoid || RVoid) {
1529    //   ... then the [l2r] conversions are performed on the second and third
1530    //   operands ...
1531    DefaultFunctionArrayConversion(LHS);
1532    DefaultFunctionArrayConversion(RHS);
1533    LTy = LHS->getType();
1534    RTy = RHS->getType();
1535
1536    //   ... and one of the following shall hold:
1537    //   -- The second or the third operand (but not both) is a throw-
1538    //      expression; the result is of the type of the other and is an rvalue.
1539    bool LThrow = isa<CXXThrowExpr>(LHS);
1540    bool RThrow = isa<CXXThrowExpr>(RHS);
1541    if (LThrow && !RThrow)
1542      return RTy;
1543    if (RThrow && !LThrow)
1544      return LTy;
1545
1546    //   -- Both the second and third operands have type void; the result is of
1547    //      type void and is an rvalue.
1548    if (LVoid && RVoid)
1549      return Context.VoidTy;
1550
1551    // Neither holds, error.
1552    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1553      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1554      << LHS->getSourceRange() << RHS->getSourceRange();
1555    return QualType();
1556  }
1557
1558  // Neither is void.
1559
1560  // C++0x 5.16p3
1561  //   Otherwise, if the second and third operand have different types, and
1562  //   either has (cv) class type, and attempt is made to convert each of those
1563  //   operands to the other.
1564  if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1565      (LTy->isRecordType() || RTy->isRecordType())) {
1566    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1567    // These return true if a single direction is already ambiguous.
1568    if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1569      return QualType();
1570    if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1571      return QualType();
1572
1573    bool HaveL2R = ICSLeftToRight.ConversionKind !=
1574      ImplicitConversionSequence::BadConversion;
1575    bool HaveR2L = ICSRightToLeft.ConversionKind !=
1576      ImplicitConversionSequence::BadConversion;
1577    //   If both can be converted, [...] the program is ill-formed.
1578    if (HaveL2R && HaveR2L) {
1579      Diag(QuestionLoc, diag::err_conditional_ambiguous)
1580        << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1581      return QualType();
1582    }
1583
1584    //   If exactly one conversion is possible, that conversion is applied to
1585    //   the chosen operand and the converted operands are used in place of the
1586    //   original operands for the remainder of this section.
1587    if (HaveL2R) {
1588      if (ConvertForConditional(*this, LHS, ICSLeftToRight))
1589        return QualType();
1590      LTy = LHS->getType();
1591    } else if (HaveR2L) {
1592      if (ConvertForConditional(*this, RHS, ICSRightToLeft))
1593        return QualType();
1594      RTy = RHS->getType();
1595    }
1596  }
1597
1598  // C++0x 5.16p4
1599  //   If the second and third operands are lvalues and have the same type,
1600  //   the result is of that type [...]
1601  bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1602  if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1603      RHS->isLvalue(Context) == Expr::LV_Valid)
1604    return LTy;
1605
1606  // C++0x 5.16p5
1607  //   Otherwise, the result is an rvalue. If the second and third operands
1608  //   do not have the same type, and either has (cv) class type, ...
1609  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1610    //   ... overload resolution is used to determine the conversions (if any)
1611    //   to be applied to the operands. If the overload resolution fails, the
1612    //   program is ill-formed.
1613    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1614      return QualType();
1615  }
1616
1617  // C++0x 5.16p6
1618  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1619  //   conversions are performed on the second and third operands.
1620  DefaultFunctionArrayConversion(LHS);
1621  DefaultFunctionArrayConversion(RHS);
1622  LTy = LHS->getType();
1623  RTy = RHS->getType();
1624
1625  //   After those conversions, one of the following shall hold:
1626  //   -- The second and third operands have the same type; the result
1627  //      is of that type.
1628  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1629    return LTy;
1630
1631  //   -- The second and third operands have arithmetic or enumeration type;
1632  //      the usual arithmetic conversions are performed to bring them to a
1633  //      common type, and the result is of that type.
1634  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1635    UsualArithmeticConversions(LHS, RHS);
1636    return LHS->getType();
1637  }
1638
1639  //   -- The second and third operands have pointer type, or one has pointer
1640  //      type and the other is a null pointer constant; pointer conversions
1641  //      and qualification conversions are performed to bring them to their
1642  //      composite pointer type. The result is of the composite pointer type.
1643  QualType Composite = FindCompositePointerType(LHS, RHS);
1644  if (!Composite.isNull())
1645    return Composite;
1646
1647  // Fourth bullet is same for pointers-to-member. However, the possible
1648  // conversions are far more limited: we have null-to-pointer, upcast of
1649  // containing class, and second-level cv-ness.
1650  // cv-ness is not a union, but must match one of the two operands. (Which,
1651  // frankly, is stupid.)
1652  const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1653  const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
1654  if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1655    ImpCastExprToType(RHS, LTy);
1656    return LTy;
1657  }
1658  if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1659    ImpCastExprToType(LHS, RTy);
1660    return RTy;
1661  }
1662  if (LMemPtr && RMemPtr) {
1663    QualType LPointee = LMemPtr->getPointeeType();
1664    QualType RPointee = RMemPtr->getPointeeType();
1665    // First, we check that the unqualified pointee type is the same. If it's
1666    // not, there's no conversion that will unify the two pointers.
1667    if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1668        Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1669      // Second, we take the greater of the two cv qualifications. If neither
1670      // is greater than the other, the conversion is not possible.
1671      unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1672      if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1673        // Third, we check if either of the container classes is derived from
1674        // the other.
1675        QualType LContainer(LMemPtr->getClass(), 0);
1676        QualType RContainer(RMemPtr->getClass(), 0);
1677        QualType MoreDerived;
1678        if (Context.getCanonicalType(LContainer) ==
1679            Context.getCanonicalType(RContainer))
1680          MoreDerived = LContainer;
1681        else if (IsDerivedFrom(LContainer, RContainer))
1682          MoreDerived = LContainer;
1683        else if (IsDerivedFrom(RContainer, LContainer))
1684          MoreDerived = RContainer;
1685
1686        if (!MoreDerived.isNull()) {
1687          // The type 'Q Pointee (MoreDerived::*)' is the common type.
1688          // We don't use ImpCastExprToType here because this could still fail
1689          // for ambiguous or inaccessible conversions.
1690          QualType Common = Context.getMemberPointerType(
1691            LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1692          if (PerformImplicitConversion(LHS, Common, "converting"))
1693            return QualType();
1694          if (PerformImplicitConversion(RHS, Common, "converting"))
1695            return QualType();
1696          return Common;
1697        }
1698      }
1699    }
1700  }
1701
1702  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1703    << LHS->getType() << RHS->getType()
1704    << LHS->getSourceRange() << RHS->getSourceRange();
1705  return QualType();
1706}
1707
1708/// \brief Find a merged pointer type and convert the two expressions to it.
1709///
1710/// This finds the composite pointer type (or member pointer type) for @p E1
1711/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1712/// type and returns it.
1713/// It does not emit diagnostics.
1714QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1715  assert(getLangOptions().CPlusPlus && "This function assumes C++");
1716  QualType T1 = E1->getType(), T2 = E2->getType();
1717
1718  if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1719      !T2->isPointerType() && !T2->isMemberPointerType())
1720   return QualType();
1721
1722  // FIXME: Do we need to work on the canonical types?
1723
1724  // C++0x 5.9p2
1725  //   Pointer conversions and qualification conversions are performed on
1726  //   pointer operands to bring them to their composite pointer type. If
1727  //   one operand is a null pointer constant, the composite pointer type is
1728  //   the type of the other operand.
1729  if (E1->isNullPointerConstant(Context)) {
1730    ImpCastExprToType(E1, T2);
1731    return T2;
1732  }
1733  if (E2->isNullPointerConstant(Context)) {
1734    ImpCastExprToType(E2, T1);
1735    return T1;
1736  }
1737
1738  // Now both have to be pointers or member pointers.
1739  if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1740      !T2->isPointerType() && !T2->isMemberPointerType())
1741    return QualType();
1742
1743  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
1744  //   the other has type "pointer to cv2 T" and the composite pointer type is
1745  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1746  //   Otherwise, the composite pointer type is a pointer type similar to the
1747  //   type of one of the operands, with a cv-qualification signature that is
1748  //   the union of the cv-qualification signatures of the operand types.
1749  // In practice, the first part here is redundant; it's subsumed by the second.
1750  // What we do here is, we build the two possible composite types, and try the
1751  // conversions in both directions. If only one works, or if the two composite
1752  // types are the same, we have succeeded.
1753  llvm::SmallVector<unsigned, 4> QualifierUnion;
1754  llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
1755  QualType Composite1 = T1, Composite2 = T2;
1756  do {
1757    const PointerType *Ptr1, *Ptr2;
1758    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1759        (Ptr2 = Composite2->getAs<PointerType>())) {
1760      Composite1 = Ptr1->getPointeeType();
1761      Composite2 = Ptr2->getPointeeType();
1762      QualifierUnion.push_back(
1763                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1764      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1765      continue;
1766    }
1767
1768    const MemberPointerType *MemPtr1, *MemPtr2;
1769    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1770        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1771      Composite1 = MemPtr1->getPointeeType();
1772      Composite2 = MemPtr2->getPointeeType();
1773      QualifierUnion.push_back(
1774                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1775      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1776                                             MemPtr2->getClass()));
1777      continue;
1778    }
1779
1780    // FIXME: block pointer types?
1781
1782    // Cannot unwrap any more types.
1783    break;
1784  } while (true);
1785
1786  // Rewrap the composites as pointers or member pointers with the union CVRs.
1787  llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1788    = MemberOfClass.begin();
1789  for (llvm::SmallVector<unsigned, 4>::iterator
1790         I = QualifierUnion.begin(),
1791         E = QualifierUnion.end();
1792       I != E; (void)++I, ++MOC) {
1793    if (MOC->first && MOC->second) {
1794      // Rebuild member pointer type
1795      Composite1 = Context.getMemberPointerType(Composite1.getQualifiedType(*I),
1796                                                MOC->first);
1797      Composite2 = Context.getMemberPointerType(Composite2.getQualifiedType(*I),
1798                                                MOC->second);
1799    } else {
1800      // Rebuild pointer type
1801      Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1802      Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1803    }
1804  }
1805
1806  ImplicitConversionSequence E1ToC1 =
1807    TryImplicitConversion(E1, Composite1,
1808                          /*SuppressUserConversions=*/false,
1809                          /*AllowExplicit=*/false,
1810                          /*ForceRValue=*/false,
1811                          /*InOverloadResolution=*/false);
1812  ImplicitConversionSequence E2ToC1 =
1813    TryImplicitConversion(E2, Composite1,
1814                          /*SuppressUserConversions=*/false,
1815                          /*AllowExplicit=*/false,
1816                          /*ForceRValue=*/false,
1817                          /*InOverloadResolution=*/false);
1818
1819  ImplicitConversionSequence E1ToC2, E2ToC2;
1820  E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1821  E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1822  if (Context.getCanonicalType(Composite1) !=
1823      Context.getCanonicalType(Composite2)) {
1824    E1ToC2 = TryImplicitConversion(E1, Composite2,
1825                                   /*SuppressUserConversions=*/false,
1826                                   /*AllowExplicit=*/false,
1827                                   /*ForceRValue=*/false,
1828                                   /*InOverloadResolution=*/false);
1829    E2ToC2 = TryImplicitConversion(E2, Composite2,
1830                                   /*SuppressUserConversions=*/false,
1831                                   /*AllowExplicit=*/false,
1832                                   /*ForceRValue=*/false,
1833                                   /*InOverloadResolution=*/false);
1834  }
1835
1836  bool ToC1Viable = E1ToC1.ConversionKind !=
1837                      ImplicitConversionSequence::BadConversion
1838                 && E2ToC1.ConversionKind !=
1839                      ImplicitConversionSequence::BadConversion;
1840  bool ToC2Viable = E1ToC2.ConversionKind !=
1841                      ImplicitConversionSequence::BadConversion
1842                 && E2ToC2.ConversionKind !=
1843                      ImplicitConversionSequence::BadConversion;
1844  if (ToC1Viable && !ToC2Viable) {
1845    if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1846        !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1847      return Composite1;
1848  }
1849  if (ToC2Viable && !ToC1Viable) {
1850    if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1851        !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1852      return Composite2;
1853  }
1854  return QualType();
1855}
1856
1857Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
1858  if (!Context.getLangOptions().CPlusPlus)
1859    return Owned(E);
1860
1861  const RecordType *RT = E->getType()->getAs<RecordType>();
1862  if (!RT)
1863    return Owned(E);
1864
1865  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1866  if (RD->hasTrivialDestructor())
1867    return Owned(E);
1868
1869  if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
1870    QualType Ty = CE->getCallee()->getType();
1871    if (const PointerType *PT = Ty->getAs<PointerType>())
1872      Ty = PT->getPointeeType();
1873
1874    const FunctionType *FTy = Ty->getAs<FunctionType>();
1875    if (FTy->getResultType()->isReferenceType())
1876      return Owned(E);
1877  }
1878  CXXTemporary *Temp = CXXTemporary::Create(Context,
1879                                            RD->getDestructor(Context));
1880  ExprTemporaries.push_back(Temp);
1881  if (CXXDestructorDecl *Destructor =
1882        const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1883    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
1884  // FIXME: Add the temporary to the temporaries vector.
1885  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1886}
1887
1888Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
1889                                              bool ShouldDestroyTemps) {
1890  assert(SubExpr && "sub expression can't be null!");
1891
1892  if (ExprTemporaries.empty())
1893    return SubExpr;
1894
1895  Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
1896                                           &ExprTemporaries[0],
1897                                           ExprTemporaries.size(),
1898                                           ShouldDestroyTemps);
1899  ExprTemporaries.clear();
1900
1901  return E;
1902}
1903
1904Sema::OwningExprResult
1905Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
1906                                   tok::TokenKind OpKind, TypeTy *&ObjectType) {
1907  // Since this might be a postfix expression, get rid of ParenListExprs.
1908  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1909
1910  Expr *BaseExpr = (Expr*)Base.get();
1911  assert(BaseExpr && "no record expansion");
1912
1913  QualType BaseType = BaseExpr->getType();
1914  if (BaseType->isDependentType()) {
1915    // FIXME: member of the current instantiation
1916    ObjectType = BaseType.getAsOpaquePtr();
1917    return move(Base);
1918  }
1919
1920  // C++ [over.match.oper]p8:
1921  //   [...] When operator->returns, the operator-> is applied  to the value
1922  //   returned, with the original second operand.
1923  if (OpKind == tok::arrow) {
1924    while (BaseType->isRecordType()) {
1925      Base = BuildOverloadedArrowExpr(S, move(Base), BaseExpr->getExprLoc());
1926      BaseExpr = (Expr*)Base.get();
1927      if (BaseExpr == NULL)
1928        return ExprError();
1929      BaseType = BaseExpr->getType();
1930    }
1931  }
1932
1933  if (BaseType->isPointerType())
1934    BaseType = BaseType->getPointeeType();
1935
1936  // We could end up with various non-record types here, such as extended
1937  // vector types or Objective-C interfaces. Just return early and let
1938  // ActOnMemberReferenceExpr do the work.
1939  if (!BaseType->isRecordType()) {
1940    // C++ [basic.lookup.classref]p2:
1941    //   [...] If the type of the object expression is of pointer to scalar
1942    //   type, the unqualified-id is looked up in the context of the complete
1943    //   postfix-expression.
1944    ObjectType = 0;
1945    return move(Base);
1946  }
1947
1948  // C++ [basic.lookup.classref]p2:
1949  //   If the id-expression in a class member access (5.2.5) is an
1950  //   unqualified-id, and the type of the object expres- sion is of a class
1951  //   type C (or of pointer to a class type C), the unqualified-id is looked
1952  //   up in the scope of class C. [...]
1953  ObjectType = BaseType.getAsOpaquePtr();
1954  return move(Base);
1955}
1956
1957Sema::OwningExprResult
1958Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
1959                                   SourceLocation OpLoc,
1960                                   tok::TokenKind OpKind,
1961                                   SourceLocation ClassNameLoc,
1962                                   IdentifierInfo *ClassName,
1963                                   const CXXScopeSpec &SS,
1964                                   bool HasTrailingLParen) {
1965  if (SS.isInvalid())
1966    return ExprError();
1967
1968  QualType BaseType;
1969  if (isUnknownSpecialization(SS))
1970    BaseType = Context.getTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1971                                       ClassName);
1972  else {
1973    TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, &SS);
1974    if (!BaseTy) {
1975      Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
1976        << ClassName;
1977      return ExprError();
1978    }
1979
1980    BaseType = GetTypeFromParser(BaseTy);
1981  }
1982
1983  CanQualType CanBaseType = Context.getCanonicalType(BaseType);
1984  DeclarationName DtorName =
1985    Context.DeclarationNames.getCXXDestructorName(CanBaseType);
1986
1987  OwningExprResult Result
1988    = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1989                               DtorName, DeclPtrTy(), &SS);
1990  if (Result.isInvalid() || HasTrailingLParen)
1991    return move(Result);
1992
1993  // The only way a reference to a destructor can be used is to
1994  // immediately call them. Since the next token is not a '(', produce a
1995  // diagnostic and build the call now.
1996  Expr *E = (Expr *)Result.get();
1997  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(E->getLocEnd());
1998  Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
1999    << isa<CXXPseudoDestructorExpr>(E)
2000    << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2001
2002  return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
2003                       MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
2004}
2005
2006Sema::OwningExprResult
2007Sema::ActOnOverloadedOperatorReferenceExpr(Scope *S, ExprArg Base,
2008                                           SourceLocation OpLoc,
2009                                           tok::TokenKind OpKind,
2010                                           SourceLocation ClassNameLoc,
2011                                           OverloadedOperatorKind OverOpKind,
2012                                           const CXXScopeSpec *SS) {
2013  if (SS && SS->isInvalid())
2014    return ExprError();
2015
2016  DeclarationName Name =
2017    Context.DeclarationNames.getCXXOperatorName(OverOpKind);
2018
2019  return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2020                                  Name, DeclPtrTy(), SS);
2021}
2022
2023Sema::OwningExprResult
2024Sema::ActOnConversionOperatorReferenceExpr(Scope *S, ExprArg Base,
2025                                           SourceLocation OpLoc,
2026                                           tok::TokenKind OpKind,
2027                                           SourceLocation ClassNameLoc,
2028                                           TypeTy *Ty,
2029                                           const CXXScopeSpec *SS) {
2030  if (SS && SS->isInvalid())
2031    return ExprError();
2032
2033  //FIXME: Preserve type source info.
2034  QualType ConvType = GetTypeFromParser(Ty);
2035  CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
2036  DeclarationName ConvName =
2037    Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
2038
2039  return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2040                                  ConvName, DeclPtrTy(), SS);
2041}
2042
2043Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2044                                                  QualType Ty,
2045                                                  CastExpr::CastKind Kind,
2046                                                  CXXMethodDecl *Method,
2047                                                  ExprArg Arg) {
2048  Expr *From = Arg.takeAs<Expr>();
2049
2050  switch (Kind) {
2051  default: assert(0 && "Unhandled cast kind!");
2052  case CastExpr::CK_ConstructorConversion: {
2053    ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2054
2055    if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2056                                MultiExprArg(*this, (void **)&From, 1),
2057                                CastLoc, ConstructorArgs))
2058      return ExprError();
2059
2060    return BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2061                                 move_arg(ConstructorArgs));
2062  }
2063
2064  case CastExpr::CK_UserDefinedConversion: {
2065    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2066
2067    // Cast to base if needed.
2068    if (PerformObjectArgumentInitialization(From, Method))
2069      return ExprError();
2070
2071    // Create an implicit member expr to refer to the conversion operator.
2072    MemberExpr *ME =
2073      new (Context) MemberExpr(From, /*IsArrow=*/false, Method,
2074                               SourceLocation(), Method->getType());
2075
2076
2077    // And an implicit call expr that calls it.
2078    QualType ResultType = Method->getResultType().getNonReferenceType();
2079    CXXMemberCallExpr *CE =
2080      new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
2081                                      ResultType,
2082                                      SourceLocation());
2083
2084    return Owned(CE);
2085  }
2086
2087  }
2088}
2089
2090Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2091  Expr *FullExpr = Arg.takeAs<Expr>();
2092  if (FullExpr)
2093    FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
2094                                                 /*ShouldDestroyTemps=*/true);
2095
2096
2097  return Owned(FullExpr);
2098}
2099