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