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