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