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