SemaExprCXX.cpp revision 8db75a2b9c963a3bc0bf928e711353552f4fef79
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 "clang/Sema/SemaInternal.h"
15#include "clang/Sema/DeclSpec.h"
16#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
18#include "clang/Sema/ParsedTemplate.h"
19#include "clang/Sema/ScopeInfo.h"
20#include "clang/Sema/TemplateDeduction.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/CXXInheritance.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Lex/Preprocessor.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/Support/ErrorHandling.h"
32using namespace clang;
33using namespace sema;
34
35ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
36                                   IdentifierInfo &II,
37                                   SourceLocation NameLoc,
38                                   Scope *S, CXXScopeSpec &SS,
39                                   ParsedType ObjectTypePtr,
40                                   bool EnteringContext) {
41  // Determine where to perform name lookup.
42
43  // FIXME: This area of the standard is very messy, and the current
44  // wording is rather unclear about which scopes we search for the
45  // destructor name; see core issues 399 and 555. Issue 399 in
46  // particular shows where the current description of destructor name
47  // lookup is completely out of line with existing practice, e.g.,
48  // this appears to be ill-formed:
49  //
50  //   namespace N {
51  //     template <typename T> struct S {
52  //       ~S();
53  //     };
54  //   }
55  //
56  //   void f(N::S<int>* s) {
57  //     s->N::S<int>::~S();
58  //   }
59  //
60  // See also PR6358 and PR6359.
61  // For this reason, we're currently only doing the C++03 version of this
62  // code; the C++0x version has to wait until we get a proper spec.
63  QualType SearchType;
64  DeclContext *LookupCtx = 0;
65  bool isDependent = false;
66  bool LookInScope = false;
67
68  // If we have an object type, it's because we are in a
69  // pseudo-destructor-expression or a member access expression, and
70  // we know what type we're looking for.
71  if (ObjectTypePtr)
72    SearchType = GetTypeFromParser(ObjectTypePtr);
73
74  if (SS.isSet()) {
75    NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
76
77    bool AlreadySearched = false;
78    bool LookAtPrefix = true;
79    // C++ [basic.lookup.qual]p6:
80    //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
81    //   the type-names are looked up as types in the scope designated by the
82    //   nested-name-specifier. In a qualified-id of the form:
83    //
84    //     ::[opt] nested-name-specifier  ~ class-name
85    //
86    //   where the nested-name-specifier designates a namespace scope, and in
87    //   a qualified-id of the form:
88    //
89    //     ::opt nested-name-specifier class-name ::  ~ class-name
90    //
91    //   the class-names are looked up as types in the scope designated by
92    //   the nested-name-specifier.
93    //
94    // Here, we check the first case (completely) and determine whether the
95    // code below is permitted to look at the prefix of the
96    // nested-name-specifier.
97    DeclContext *DC = computeDeclContext(SS, EnteringContext);
98    if (DC && DC->isFileContext()) {
99      AlreadySearched = true;
100      LookupCtx = DC;
101      isDependent = false;
102    } else if (DC && isa<CXXRecordDecl>(DC))
103      LookAtPrefix = false;
104
105    // The second case from the C++03 rules quoted further above.
106    NestedNameSpecifier *Prefix = 0;
107    if (AlreadySearched) {
108      // Nothing left to do.
109    } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
110      CXXScopeSpec PrefixSS;
111      PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
112      LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
113      isDependent = isDependentScopeSpecifier(PrefixSS);
114    } else if (ObjectTypePtr) {
115      LookupCtx = computeDeclContext(SearchType);
116      isDependent = SearchType->isDependentType();
117    } else {
118      LookupCtx = computeDeclContext(SS, EnteringContext);
119      isDependent = LookupCtx && LookupCtx->isDependentContext();
120    }
121
122    LookInScope = false;
123  } else if (ObjectTypePtr) {
124    // C++ [basic.lookup.classref]p3:
125    //   If the unqualified-id is ~type-name, the type-name is looked up
126    //   in the context of the entire postfix-expression. If the type T
127    //   of the object expression is of a class type C, the type-name is
128    //   also looked up in the scope of class C. At least one of the
129    //   lookups shall find a name that refers to (possibly
130    //   cv-qualified) T.
131    LookupCtx = computeDeclContext(SearchType);
132    isDependent = SearchType->isDependentType();
133    assert((isDependent || !SearchType->isIncompleteType()) &&
134           "Caller should have completed object type");
135
136    LookInScope = true;
137  } else {
138    // Perform lookup into the current scope (only).
139    LookInScope = true;
140  }
141
142  TypeDecl *NonMatchingTypeDecl = 0;
143  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
144  for (unsigned Step = 0; Step != 2; ++Step) {
145    // Look for the name first in the computed lookup context (if we
146    // have one) and, if that fails to find a match, in the scope (if
147    // we're allowed to look there).
148    Found.clear();
149    if (Step == 0 && LookupCtx)
150      LookupQualifiedName(Found, LookupCtx);
151    else if (Step == 1 && LookInScope && S)
152      LookupName(Found, S);
153    else
154      continue;
155
156    // FIXME: Should we be suppressing ambiguities here?
157    if (Found.isAmbiguous())
158      return ParsedType();
159
160    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
161      QualType T = Context.getTypeDeclType(Type);
162
163      if (SearchType.isNull() || SearchType->isDependentType() ||
164          Context.hasSameUnqualifiedType(T, SearchType)) {
165        // We found our type!
166
167        return ParsedType::make(T);
168      }
169
170      if (!SearchType.isNull())
171        NonMatchingTypeDecl = Type;
172    }
173
174    // If the name that we found is a class template name, and it is
175    // the same name as the template name in the last part of the
176    // nested-name-specifier (if present) or the object type, then
177    // this is the destructor for that class.
178    // FIXME: This is a workaround until we get real drafting for core
179    // issue 399, for which there isn't even an obvious direction.
180    if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
181      QualType MemberOfType;
182      if (SS.isSet()) {
183        if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
184          // Figure out the type of the context, if it has one.
185          if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
186            MemberOfType = Context.getTypeDeclType(Record);
187        }
188      }
189      if (MemberOfType.isNull())
190        MemberOfType = SearchType;
191
192      if (MemberOfType.isNull())
193        continue;
194
195      // We're referring into a class template specialization. If the
196      // class template we found is the same as the template being
197      // specialized, we found what we are looking for.
198      if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
199        if (ClassTemplateSpecializationDecl *Spec
200              = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
201          if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
202                Template->getCanonicalDecl())
203            return ParsedType::make(MemberOfType);
204        }
205
206        continue;
207      }
208
209      // We're referring to an unresolved class template
210      // specialization. Determine whether we class template we found
211      // is the same as the template being specialized or, if we don't
212      // know which template is being specialized, that it at least
213      // has the same name.
214      if (const TemplateSpecializationType *SpecType
215            = MemberOfType->getAs<TemplateSpecializationType>()) {
216        TemplateName SpecName = SpecType->getTemplateName();
217
218        // The class template we found is the same template being
219        // specialized.
220        if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
221          if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
222            return ParsedType::make(MemberOfType);
223
224          continue;
225        }
226
227        // The class template we found has the same name as the
228        // (dependent) template name being specialized.
229        if (DependentTemplateName *DepTemplate
230                                    = SpecName.getAsDependentTemplateName()) {
231          if (DepTemplate->isIdentifier() &&
232              DepTemplate->getIdentifier() == Template->getIdentifier())
233            return ParsedType::make(MemberOfType);
234
235          continue;
236        }
237      }
238    }
239  }
240
241  if (isDependent) {
242    // We didn't find our type, but that's okay: it's dependent
243    // anyway.
244
245    // FIXME: What if we have no nested-name-specifier?
246    QualType T = CheckTypenameType(ETK_None, SourceLocation(),
247                                   SS.getWithLocInContext(Context),
248                                   II, NameLoc);
249    return ParsedType::make(T);
250  }
251
252  if (NonMatchingTypeDecl) {
253    QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
254    Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
255      << T << SearchType;
256    Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
257      << T;
258  } else if (ObjectTypePtr)
259    Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
260      << &II;
261  else
262    Diag(NameLoc, diag::err_destructor_class_name);
263
264  return ParsedType();
265}
266
267/// \brief Build a C++ typeid expression with a type operand.
268ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
269                                SourceLocation TypeidLoc,
270                                TypeSourceInfo *Operand,
271                                SourceLocation RParenLoc) {
272  // C++ [expr.typeid]p4:
273  //   The top-level cv-qualifiers of the lvalue expression or the type-id
274  //   that is the operand of typeid are always ignored.
275  //   If the type of the type-id is a class type or a reference to a class
276  //   type, the class shall be completely-defined.
277  Qualifiers Quals;
278  QualType T
279    = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
280                                      Quals);
281  if (T->getAs<RecordType>() &&
282      RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
283    return ExprError();
284
285  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
286                                           Operand,
287                                           SourceRange(TypeidLoc, RParenLoc)));
288}
289
290/// \brief Build a C++ typeid expression with an expression operand.
291ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
292                                SourceLocation TypeidLoc,
293                                Expr *E,
294                                SourceLocation RParenLoc) {
295  bool isUnevaluatedOperand = true;
296  if (E && !E->isTypeDependent()) {
297    QualType T = E->getType();
298    if (const RecordType *RecordT = T->getAs<RecordType>()) {
299      CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
300      // C++ [expr.typeid]p3:
301      //   [...] If the type of the expression is a class type, the class
302      //   shall be completely-defined.
303      if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
304        return ExprError();
305
306      // C++ [expr.typeid]p3:
307      //   When typeid is applied to an expression other than an glvalue of a
308      //   polymorphic class type [...] [the] expression is an unevaluated
309      //   operand. [...]
310      if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
311        isUnevaluatedOperand = false;
312
313        // We require a vtable to query the type at run time.
314        MarkVTableUsed(TypeidLoc, RecordD);
315      }
316    }
317
318    // C++ [expr.typeid]p4:
319    //   [...] If the type of the type-id is a reference to a possibly
320    //   cv-qualified type, the result of the typeid expression refers to a
321    //   std::type_info object representing the cv-unqualified referenced
322    //   type.
323    Qualifiers Quals;
324    QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
325    if (!Context.hasSameType(T, UnqualT)) {
326      T = UnqualT;
327      E = ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E)).take();
328    }
329  }
330
331  // If this is an unevaluated operand, clear out the set of
332  // declaration references we have been computing and eliminate any
333  // temporaries introduced in its computation.
334  if (isUnevaluatedOperand)
335    ExprEvalContexts.back().Context = Unevaluated;
336
337  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
338                                           E,
339                                           SourceRange(TypeidLoc, RParenLoc)));
340}
341
342/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
343ExprResult
344Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
345                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
346  // Find the std::type_info type.
347  if (!getStdNamespace())
348    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
349
350  if (!CXXTypeInfoDecl) {
351    IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
352    LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
353    LookupQualifiedName(R, getStdNamespace());
354    CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
355    if (!CXXTypeInfoDecl)
356      return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
357  }
358
359  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
360
361  if (isType) {
362    // The operand is a type; handle it as such.
363    TypeSourceInfo *TInfo = 0;
364    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
365                                   &TInfo);
366    if (T.isNull())
367      return ExprError();
368
369    if (!TInfo)
370      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
371
372    return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
373  }
374
375  // The operand is an expression.
376  return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
377}
378
379/// Retrieve the UuidAttr associated with QT.
380static UuidAttr *GetUuidAttrOfType(QualType QT) {
381  // Optionally remove one level of pointer, reference or array indirection.
382  const Type *Ty = QT.getTypePtr();;
383  if (QT->isPointerType() || QT->isReferenceType())
384    Ty = QT->getPointeeType().getTypePtr();
385  else if (QT->isArrayType())
386    Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
387
388  // Loop all record redeclaration looking for an uuid attribute.
389  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
390  for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
391       E = RD->redecls_end(); I != E; ++I) {
392    if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
393      return Uuid;
394  }
395
396  return 0;
397}
398
399/// \brief Build a Microsoft __uuidof expression with a type operand.
400ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
401                                SourceLocation TypeidLoc,
402                                TypeSourceInfo *Operand,
403                                SourceLocation RParenLoc) {
404  if (!Operand->getType()->isDependentType()) {
405    if (!GetUuidAttrOfType(Operand->getType()))
406      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
407  }
408
409  // FIXME: add __uuidof semantic analysis for type operand.
410  return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
411                                           Operand,
412                                           SourceRange(TypeidLoc, RParenLoc)));
413}
414
415/// \brief Build a Microsoft __uuidof expression with an expression operand.
416ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
417                                SourceLocation TypeidLoc,
418                                Expr *E,
419                                SourceLocation RParenLoc) {
420  if (!E->getType()->isDependentType()) {
421    if (!GetUuidAttrOfType(E->getType()) &&
422        !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
423      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
424  }
425  // FIXME: add __uuidof semantic analysis for type operand.
426  return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
427                                           E,
428                                           SourceRange(TypeidLoc, RParenLoc)));
429}
430
431/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
432ExprResult
433Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
434                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
435  // If MSVCGuidDecl has not been cached, do the lookup.
436  if (!MSVCGuidDecl) {
437    IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
438    LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
439    LookupQualifiedName(R, Context.getTranslationUnitDecl());
440    MSVCGuidDecl = R.getAsSingle<RecordDecl>();
441    if (!MSVCGuidDecl)
442      return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
443  }
444
445  QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
446
447  if (isType) {
448    // The operand is a type; handle it as such.
449    TypeSourceInfo *TInfo = 0;
450    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
451                                   &TInfo);
452    if (T.isNull())
453      return ExprError();
454
455    if (!TInfo)
456      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
457
458    return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
459  }
460
461  // The operand is an expression.
462  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
463}
464
465/// ActOnCXXBoolLiteral - Parse {true,false} literals.
466ExprResult
467Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
468  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
469         "Unknown C++ Boolean value!");
470  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
471                                                Context.BoolTy, OpLoc));
472}
473
474/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
475ExprResult
476Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
477  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
478}
479
480/// ActOnCXXThrow - Parse throw expressions.
481ExprResult
482Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
483  // Don't report an error if 'throw' is used in system headers.
484  if (!getLangOptions().CXXExceptions &&
485      !getSourceManager().isInSystemHeader(OpLoc))
486    Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
487
488  if (Ex && !Ex->isTypeDependent()) {
489    ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex);
490    if (ExRes.isInvalid())
491      return ExprError();
492    Ex = ExRes.take();
493  }
494  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
495}
496
497/// CheckCXXThrowOperand - Validate the operand of a throw.
498ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E) {
499  // C++ [except.throw]p3:
500  //   A throw-expression initializes a temporary object, called the exception
501  //   object, the type of which is determined by removing any top-level
502  //   cv-qualifiers from the static type of the operand of throw and adjusting
503  //   the type from "array of T" or "function returning T" to "pointer to T"
504  //   or "pointer to function returning T", [...]
505  if (E->getType().hasQualifiers())
506    E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
507                      CastCategory(E)).take();
508
509  ExprResult Res = DefaultFunctionArrayConversion(E);
510  if (Res.isInvalid())
511    return ExprError();
512  E = Res.take();
513
514  //   If the type of the exception would be an incomplete type or a pointer
515  //   to an incomplete type other than (cv) void the program is ill-formed.
516  QualType Ty = E->getType();
517  bool isPointer = false;
518  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
519    Ty = Ptr->getPointeeType();
520    isPointer = true;
521  }
522  if (!isPointer || !Ty->isVoidType()) {
523    if (RequireCompleteType(ThrowLoc, Ty,
524                            PDiag(isPointer ? diag::err_throw_incomplete_ptr
525                                            : diag::err_throw_incomplete)
526                              << E->getSourceRange()))
527      return ExprError();
528
529    if (RequireNonAbstractType(ThrowLoc, E->getType(),
530                               PDiag(diag::err_throw_abstract_type)
531                                 << E->getSourceRange()))
532      return ExprError();
533  }
534
535  // Initialize the exception result.  This implicitly weeds out
536  // abstract types or types with inaccessible copy constructors.
537  const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
538
539  // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
540  InitializedEntity Entity =
541      InitializedEntity::InitializeException(ThrowLoc, E->getType(),
542                                             /*NRVO=*/false);
543  Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
544                                        QualType(), E);
545  if (Res.isInvalid())
546    return ExprError();
547  E = Res.take();
548
549  // If the exception has class type, we need additional handling.
550  const RecordType *RecordTy = Ty->getAs<RecordType>();
551  if (!RecordTy)
552    return Owned(E);
553  CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
554
555  // If we are throwing a polymorphic class type or pointer thereof,
556  // exception handling will make use of the vtable.
557  MarkVTableUsed(ThrowLoc, RD);
558
559  // If a pointer is thrown, the referenced object will not be destroyed.
560  if (isPointer)
561    return Owned(E);
562
563  // If the class has a non-trivial destructor, we must be able to call it.
564  if (RD->hasTrivialDestructor())
565    return Owned(E);
566
567  CXXDestructorDecl *Destructor
568    = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
569  if (!Destructor)
570    return Owned(E);
571
572  MarkDeclarationReferenced(E->getExprLoc(), Destructor);
573  CheckDestructorAccess(E->getExprLoc(), Destructor,
574                        PDiag(diag::err_access_dtor_exception) << Ty);
575  return Owned(E);
576}
577
578CXXMethodDecl *Sema::tryCaptureCXXThis() {
579  // Ignore block scopes: we can capture through them.
580  // Ignore nested enum scopes: we'll diagnose non-constant expressions
581  // where they're invalid, and other uses are legitimate.
582  // Don't ignore nested class scopes: you can't use 'this' in a local class.
583  DeclContext *DC = CurContext;
584  while (true) {
585    if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
586    else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
587    else break;
588  }
589
590  // If we're not in an instance method, error out.
591  CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC);
592  if (!method || !method->isInstance())
593    return 0;
594
595  // Mark that we're closing on 'this' in all the block scopes, if applicable.
596  for (unsigned idx = FunctionScopes.size() - 1;
597       isa<BlockScopeInfo>(FunctionScopes[idx]);
598       --idx)
599    cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
600
601  return method;
602}
603
604ExprResult Sema::ActOnCXXThis(SourceLocation loc) {
605  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
606  /// is a non-lvalue expression whose value is the address of the object for
607  /// which the function is called.
608
609  CXXMethodDecl *method = tryCaptureCXXThis();
610  if (!method) return Diag(loc, diag::err_invalid_this_use);
611
612  return Owned(new (Context) CXXThisExpr(loc, method->getThisType(Context),
613                                         /*isImplicit=*/false));
614}
615
616ExprResult
617Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
618                                SourceLocation LParenLoc,
619                                MultiExprArg exprs,
620                                SourceLocation RParenLoc) {
621  if (!TypeRep)
622    return ExprError();
623
624  TypeSourceInfo *TInfo;
625  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
626  if (!TInfo)
627    TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
628
629  return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
630}
631
632/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
633/// Can be interpreted either as function-style casting ("int(x)")
634/// or class type construction ("ClassType(x,y,z)")
635/// or creation of a value-initialized type ("int()").
636ExprResult
637Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
638                                SourceLocation LParenLoc,
639                                MultiExprArg exprs,
640                                SourceLocation RParenLoc) {
641  QualType Ty = TInfo->getType();
642  unsigned NumExprs = exprs.size();
643  Expr **Exprs = (Expr**)exprs.get();
644  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
645  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
646
647  if (Ty->isDependentType() ||
648      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
649    exprs.release();
650
651    return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
652                                                    LParenLoc,
653                                                    Exprs, NumExprs,
654                                                    RParenLoc));
655  }
656
657  if (Ty->isArrayType())
658    return ExprError(Diag(TyBeginLoc,
659                          diag::err_value_init_for_array_type) << FullRange);
660  if (!Ty->isVoidType() &&
661      RequireCompleteType(TyBeginLoc, Ty,
662                          PDiag(diag::err_invalid_incomplete_type_use)
663                            << FullRange))
664    return ExprError();
665
666  if (RequireNonAbstractType(TyBeginLoc, Ty,
667                             diag::err_allocation_of_abstract_type))
668    return ExprError();
669
670
671  // C++ [expr.type.conv]p1:
672  // If the expression list is a single expression, the type conversion
673  // expression is equivalent (in definedness, and if defined in meaning) to the
674  // corresponding cast expression.
675  //
676  if (NumExprs == 1) {
677    CastKind Kind = CK_Invalid;
678    ExprValueKind VK = VK_RValue;
679    CXXCastPath BasePath;
680    ExprResult CastExpr =
681      CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
682                     Kind, VK, BasePath,
683                     /*FunctionalStyle=*/true);
684    if (CastExpr.isInvalid())
685      return ExprError();
686    Exprs[0] = CastExpr.take();
687
688    exprs.release();
689
690    return Owned(CXXFunctionalCastExpr::Create(Context,
691                                               Ty.getNonLValueExprType(Context),
692                                               VK, TInfo, TyBeginLoc, Kind,
693                                               Exprs[0], &BasePath,
694                                               RParenLoc));
695  }
696
697  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
698  InitializationKind Kind
699    = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
700                                                  LParenLoc, RParenLoc)
701               : InitializationKind::CreateValue(TyBeginLoc,
702                                                 LParenLoc, RParenLoc);
703  InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
704  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
705
706  // FIXME: Improve AST representation?
707  return move(Result);
708}
709
710/// doesUsualArrayDeleteWantSize - Answers whether the usual
711/// operator delete[] for the given type has a size_t parameter.
712static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
713                                         QualType allocType) {
714  const RecordType *record =
715    allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
716  if (!record) return false;
717
718  // Try to find an operator delete[] in class scope.
719
720  DeclarationName deleteName =
721    S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
722  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
723  S.LookupQualifiedName(ops, record->getDecl());
724
725  // We're just doing this for information.
726  ops.suppressDiagnostics();
727
728  // Very likely: there's no operator delete[].
729  if (ops.empty()) return false;
730
731  // If it's ambiguous, it should be illegal to call operator delete[]
732  // on this thing, so it doesn't matter if we allocate extra space or not.
733  if (ops.isAmbiguous()) return false;
734
735  LookupResult::Filter filter = ops.makeFilter();
736  while (filter.hasNext()) {
737    NamedDecl *del = filter.next()->getUnderlyingDecl();
738
739    // C++0x [basic.stc.dynamic.deallocation]p2:
740    //   A template instance is never a usual deallocation function,
741    //   regardless of its signature.
742    if (isa<FunctionTemplateDecl>(del)) {
743      filter.erase();
744      continue;
745    }
746
747    // C++0x [basic.stc.dynamic.deallocation]p2:
748    //   If class T does not declare [an operator delete[] with one
749    //   parameter] but does declare a member deallocation function
750    //   named operator delete[] with exactly two parameters, the
751    //   second of which has type std::size_t, then this function
752    //   is a usual deallocation function.
753    if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
754      filter.erase();
755      continue;
756    }
757  }
758  filter.done();
759
760  if (!ops.isSingleResult()) return false;
761
762  const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
763  return (del->getNumParams() == 2);
764}
765
766/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
767/// @code new (memory) int[size][4] @endcode
768/// or
769/// @code ::new Foo(23, "hello") @endcode
770/// For the interpretation of this heap of arguments, consult the base version.
771ExprResult
772Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
773                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
774                  SourceLocation PlacementRParen, SourceRange TypeIdParens,
775                  Declarator &D, SourceLocation ConstructorLParen,
776                  MultiExprArg ConstructorArgs,
777                  SourceLocation ConstructorRParen) {
778  bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
779
780  Expr *ArraySize = 0;
781  // If the specified type is an array, unwrap it and save the expression.
782  if (D.getNumTypeObjects() > 0 &&
783      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
784    DeclaratorChunk &Chunk = D.getTypeObject(0);
785    if (TypeContainsAuto)
786      return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
787        << D.getSourceRange());
788    if (Chunk.Arr.hasStatic)
789      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
790        << D.getSourceRange());
791    if (!Chunk.Arr.NumElts)
792      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
793        << D.getSourceRange());
794
795    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
796    D.DropFirstTypeObject();
797  }
798
799  // Every dimension shall be of constant size.
800  if (ArraySize) {
801    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
802      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
803        break;
804
805      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
806      if (Expr *NumElts = (Expr *)Array.NumElts) {
807        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
808            !NumElts->isIntegerConstantExpr(Context)) {
809          Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
810            << NumElts->getSourceRange();
811          return ExprError();
812        }
813      }
814    }
815  }
816
817  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0, /*OwnedDecl=*/0,
818                                               /*AllowAuto=*/true);
819  QualType AllocType = TInfo->getType();
820  if (D.isInvalidType())
821    return ExprError();
822
823  return BuildCXXNew(StartLoc, UseGlobal,
824                     PlacementLParen,
825                     move(PlacementArgs),
826                     PlacementRParen,
827                     TypeIdParens,
828                     AllocType,
829                     TInfo,
830                     ArraySize,
831                     ConstructorLParen,
832                     move(ConstructorArgs),
833                     ConstructorRParen,
834                     TypeContainsAuto);
835}
836
837ExprResult
838Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
839                  SourceLocation PlacementLParen,
840                  MultiExprArg PlacementArgs,
841                  SourceLocation PlacementRParen,
842                  SourceRange TypeIdParens,
843                  QualType AllocType,
844                  TypeSourceInfo *AllocTypeInfo,
845                  Expr *ArraySize,
846                  SourceLocation ConstructorLParen,
847                  MultiExprArg ConstructorArgs,
848                  SourceLocation ConstructorRParen,
849                  bool TypeMayContainAuto) {
850  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
851
852  // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
853  if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
854    if (ConstructorArgs.size() == 0)
855      return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
856                       << AllocType << TypeRange);
857    if (ConstructorArgs.size() != 1) {
858      Expr *FirstBad = ConstructorArgs.get()[1];
859      return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
860                            diag::err_auto_new_ctor_multiple_expressions)
861                       << AllocType << TypeRange);
862    }
863    TypeSourceInfo *DeducedType = 0;
864    if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
865      return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
866                       << AllocType
867                       << ConstructorArgs.get()[0]->getType()
868                       << TypeRange
869                       << ConstructorArgs.get()[0]->getSourceRange());
870    if (!DeducedType)
871      return ExprError();
872
873    AllocTypeInfo = DeducedType;
874    AllocType = AllocTypeInfo->getType();
875  }
876
877  // Per C++0x [expr.new]p5, the type being constructed may be a
878  // typedef of an array type.
879  if (!ArraySize) {
880    if (const ConstantArrayType *Array
881                              = Context.getAsConstantArrayType(AllocType)) {
882      ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
883                                         Context.getSizeType(),
884                                         TypeRange.getEnd());
885      AllocType = Array->getElementType();
886    }
887  }
888
889  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
890    return ExprError();
891
892  QualType ResultType = Context.getPointerType(AllocType);
893
894  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
895  //   or enumeration type with a non-negative value."
896  if (ArraySize && !ArraySize->isTypeDependent()) {
897
898    QualType SizeType = ArraySize->getType();
899
900    ExprResult ConvertedSize
901      = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
902                                       PDiag(diag::err_array_size_not_integral),
903                                     PDiag(diag::err_array_size_incomplete_type)
904                                       << ArraySize->getSourceRange(),
905                               PDiag(diag::err_array_size_explicit_conversion),
906                                       PDiag(diag::note_array_size_conversion),
907                               PDiag(diag::err_array_size_ambiguous_conversion),
908                                       PDiag(diag::note_array_size_conversion),
909                          PDiag(getLangOptions().CPlusPlus0x? 0
910                                            : diag::ext_array_size_conversion));
911    if (ConvertedSize.isInvalid())
912      return ExprError();
913
914    ArraySize = ConvertedSize.take();
915    SizeType = ArraySize->getType();
916    if (!SizeType->isIntegralOrUnscopedEnumerationType())
917      return ExprError();
918
919    // Let's see if this is a constant < 0. If so, we reject it out of hand.
920    // We don't care about special rules, so we tell the machinery it's not
921    // evaluated - it gives us a result in more cases.
922    if (!ArraySize->isValueDependent()) {
923      llvm::APSInt Value;
924      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
925        if (Value < llvm::APSInt(
926                        llvm::APInt::getNullValue(Value.getBitWidth()),
927                                 Value.isUnsigned()))
928          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
929                                diag::err_typecheck_negative_array_size)
930            << ArraySize->getSourceRange());
931
932        if (!AllocType->isDependentType()) {
933          unsigned ActiveSizeBits
934            = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
935          if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
936            Diag(ArraySize->getSourceRange().getBegin(),
937                 diag::err_array_too_large)
938              << Value.toString(10)
939              << ArraySize->getSourceRange();
940            return ExprError();
941          }
942        }
943      } else if (TypeIdParens.isValid()) {
944        // Can't have dynamic array size when the type-id is in parentheses.
945        Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
946          << ArraySize->getSourceRange()
947          << FixItHint::CreateRemoval(TypeIdParens.getBegin())
948          << FixItHint::CreateRemoval(TypeIdParens.getEnd());
949
950        TypeIdParens = SourceRange();
951      }
952    }
953
954    ArraySize = ImpCastExprToType(ArraySize, Context.getSizeType(),
955                      CK_IntegralCast).take();
956  }
957
958  FunctionDecl *OperatorNew = 0;
959  FunctionDecl *OperatorDelete = 0;
960  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
961  unsigned NumPlaceArgs = PlacementArgs.size();
962
963  if (!AllocType->isDependentType() &&
964      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
965      FindAllocationFunctions(StartLoc,
966                              SourceRange(PlacementLParen, PlacementRParen),
967                              UseGlobal, AllocType, ArraySize, PlaceArgs,
968                              NumPlaceArgs, OperatorNew, OperatorDelete))
969    return ExprError();
970
971  // If this is an array allocation, compute whether the usual array
972  // deallocation function for the type has a size_t parameter.
973  bool UsualArrayDeleteWantsSize = false;
974  if (ArraySize && !AllocType->isDependentType())
975    UsualArrayDeleteWantsSize
976      = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
977
978  llvm::SmallVector<Expr *, 8> AllPlaceArgs;
979  if (OperatorNew) {
980    // Add default arguments, if any.
981    const FunctionProtoType *Proto =
982      OperatorNew->getType()->getAs<FunctionProtoType>();
983    VariadicCallType CallType =
984      Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
985
986    if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
987                               Proto, 1, PlaceArgs, NumPlaceArgs,
988                               AllPlaceArgs, CallType))
989      return ExprError();
990
991    NumPlaceArgs = AllPlaceArgs.size();
992    if (NumPlaceArgs > 0)
993      PlaceArgs = &AllPlaceArgs[0];
994  }
995
996  bool Init = ConstructorLParen.isValid();
997  // --- Choosing a constructor ---
998  CXXConstructorDecl *Constructor = 0;
999  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
1000  unsigned NumConsArgs = ConstructorArgs.size();
1001  ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
1002
1003  // Array 'new' can't have any initializers.
1004  if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
1005    SourceRange InitRange(ConsArgs[0]->getLocStart(),
1006                          ConsArgs[NumConsArgs - 1]->getLocEnd());
1007
1008    Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1009    return ExprError();
1010  }
1011
1012  if (!AllocType->isDependentType() &&
1013      !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1014    // C++0x [expr.new]p15:
1015    //   A new-expression that creates an object of type T initializes that
1016    //   object as follows:
1017    InitializationKind Kind
1018    //     - If the new-initializer is omitted, the object is default-
1019    //       initialized (8.5); if no initialization is performed,
1020    //       the object has indeterminate value
1021      = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
1022    //     - Otherwise, the new-initializer is interpreted according to the
1023    //       initialization rules of 8.5 for direct-initialization.
1024             : InitializationKind::CreateDirect(TypeRange.getBegin(),
1025                                                ConstructorLParen,
1026                                                ConstructorRParen);
1027
1028    InitializedEntity Entity
1029      = InitializedEntity::InitializeNew(StartLoc, AllocType);
1030    InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
1031    ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1032                                                move(ConstructorArgs));
1033    if (FullInit.isInvalid())
1034      return ExprError();
1035
1036    // FullInit is our initializer; walk through it to determine if it's a
1037    // constructor call, which CXXNewExpr handles directly.
1038    if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1039      if (CXXBindTemporaryExpr *Binder
1040            = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1041        FullInitExpr = Binder->getSubExpr();
1042      if (CXXConstructExpr *Construct
1043                    = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1044        Constructor = Construct->getConstructor();
1045        for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1046                                         AEnd = Construct->arg_end();
1047             A != AEnd; ++A)
1048          ConvertedConstructorArgs.push_back(*A);
1049      } else {
1050        // Take the converted initializer.
1051        ConvertedConstructorArgs.push_back(FullInit.release());
1052      }
1053    } else {
1054      // No initialization required.
1055    }
1056
1057    // Take the converted arguments and use them for the new expression.
1058    NumConsArgs = ConvertedConstructorArgs.size();
1059    ConsArgs = (Expr **)ConvertedConstructorArgs.take();
1060  }
1061
1062  // Mark the new and delete operators as referenced.
1063  if (OperatorNew)
1064    MarkDeclarationReferenced(StartLoc, OperatorNew);
1065  if (OperatorDelete)
1066    MarkDeclarationReferenced(StartLoc, OperatorDelete);
1067
1068  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
1069
1070  PlacementArgs.release();
1071  ConstructorArgs.release();
1072
1073  return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
1074                                        PlaceArgs, NumPlaceArgs, TypeIdParens,
1075                                        ArraySize, Constructor, Init,
1076                                        ConsArgs, NumConsArgs, OperatorDelete,
1077                                        UsualArrayDeleteWantsSize,
1078                                        ResultType, AllocTypeInfo,
1079                                        StartLoc,
1080                                        Init ? ConstructorRParen :
1081                                               TypeRange.getEnd(),
1082                                        ConstructorLParen, ConstructorRParen));
1083}
1084
1085/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1086/// in a new-expression.
1087/// dimension off and stores the size expression in ArraySize.
1088bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1089                              SourceRange R) {
1090  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1091  //   abstract class type or array thereof.
1092  if (AllocType->isFunctionType())
1093    return Diag(Loc, diag::err_bad_new_type)
1094      << AllocType << 0 << R;
1095  else if (AllocType->isReferenceType())
1096    return Diag(Loc, diag::err_bad_new_type)
1097      << AllocType << 1 << R;
1098  else if (!AllocType->isDependentType() &&
1099           RequireCompleteType(Loc, AllocType,
1100                               PDiag(diag::err_new_incomplete_type)
1101                                 << R))
1102    return true;
1103  else if (RequireNonAbstractType(Loc, AllocType,
1104                                  diag::err_allocation_of_abstract_type))
1105    return true;
1106  else if (AllocType->isVariablyModifiedType())
1107    return Diag(Loc, diag::err_variably_modified_new_type)
1108             << AllocType;
1109  else if (unsigned AddressSpace = AllocType.getAddressSpace())
1110    return Diag(Loc, diag::err_address_space_qualified_new)
1111      << AllocType.getUnqualifiedType() << AddressSpace;
1112
1113  return false;
1114}
1115
1116/// \brief Determine whether the given function is a non-placement
1117/// deallocation function.
1118static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1119  if (FD->isInvalidDecl())
1120    return false;
1121
1122  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1123    return Method->isUsualDeallocationFunction();
1124
1125  return ((FD->getOverloadedOperator() == OO_Delete ||
1126           FD->getOverloadedOperator() == OO_Array_Delete) &&
1127          FD->getNumParams() == 1);
1128}
1129
1130/// FindAllocationFunctions - Finds the overloads of operator new and delete
1131/// that are appropriate for the allocation.
1132bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1133                                   bool UseGlobal, QualType AllocType,
1134                                   bool IsArray, Expr **PlaceArgs,
1135                                   unsigned NumPlaceArgs,
1136                                   FunctionDecl *&OperatorNew,
1137                                   FunctionDecl *&OperatorDelete) {
1138  // --- Choosing an allocation function ---
1139  // C++ 5.3.4p8 - 14 & 18
1140  // 1) If UseGlobal is true, only look in the global scope. Else, also look
1141  //   in the scope of the allocated class.
1142  // 2) If an array size is given, look for operator new[], else look for
1143  //   operator new.
1144  // 3) The first argument is always size_t. Append the arguments from the
1145  //   placement form.
1146
1147  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1148  // We don't care about the actual value of this argument.
1149  // FIXME: Should the Sema create the expression and embed it in the syntax
1150  // tree? Or should the consumer just recalculate the value?
1151  IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1152                      Context.Target.getPointerWidth(0)),
1153                      Context.getSizeType(),
1154                      SourceLocation());
1155  AllocArgs[0] = &Size;
1156  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1157
1158  // C++ [expr.new]p8:
1159  //   If the allocated type is a non-array type, the allocation
1160  //   function's name is operator new and the deallocation function's
1161  //   name is operator delete. If the allocated type is an array
1162  //   type, the allocation function's name is operator new[] and the
1163  //   deallocation function's name is operator delete[].
1164  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1165                                        IsArray ? OO_Array_New : OO_New);
1166  DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1167                                        IsArray ? OO_Array_Delete : OO_Delete);
1168
1169  QualType AllocElemType = Context.getBaseElementType(AllocType);
1170
1171  if (AllocElemType->isRecordType() && !UseGlobal) {
1172    CXXRecordDecl *Record
1173      = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1174    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1175                          AllocArgs.size(), Record, /*AllowMissing=*/true,
1176                          OperatorNew))
1177      return true;
1178  }
1179  if (!OperatorNew) {
1180    // Didn't find a member overload. Look for a global one.
1181    DeclareGlobalNewDelete();
1182    DeclContext *TUDecl = Context.getTranslationUnitDecl();
1183    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1184                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1185                          OperatorNew))
1186      return true;
1187  }
1188
1189  // We don't need an operator delete if we're running under
1190  // -fno-exceptions.
1191  if (!getLangOptions().Exceptions) {
1192    OperatorDelete = 0;
1193    return false;
1194  }
1195
1196  // FindAllocationOverload can change the passed in arguments, so we need to
1197  // copy them back.
1198  if (NumPlaceArgs > 0)
1199    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
1200
1201  // C++ [expr.new]p19:
1202  //
1203  //   If the new-expression begins with a unary :: operator, the
1204  //   deallocation function's name is looked up in the global
1205  //   scope. Otherwise, if the allocated type is a class type T or an
1206  //   array thereof, the deallocation function's name is looked up in
1207  //   the scope of T. If this lookup fails to find the name, or if
1208  //   the allocated type is not a class type or array thereof, the
1209  //   deallocation function's name is looked up in the global scope.
1210  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1211  if (AllocElemType->isRecordType() && !UseGlobal) {
1212    CXXRecordDecl *RD
1213      = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1214    LookupQualifiedName(FoundDelete, RD);
1215  }
1216  if (FoundDelete.isAmbiguous())
1217    return true; // FIXME: clean up expressions?
1218
1219  if (FoundDelete.empty()) {
1220    DeclareGlobalNewDelete();
1221    LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1222  }
1223
1224  FoundDelete.suppressDiagnostics();
1225
1226  llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1227
1228  // Whether we're looking for a placement operator delete is dictated
1229  // by whether we selected a placement operator new, not by whether
1230  // we had explicit placement arguments.  This matters for things like
1231  //   struct A { void *operator new(size_t, int = 0); ... };
1232  //   A *a = new A()
1233  bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1234
1235  if (isPlacementNew) {
1236    // C++ [expr.new]p20:
1237    //   A declaration of a placement deallocation function matches the
1238    //   declaration of a placement allocation function if it has the
1239    //   same number of parameters and, after parameter transformations
1240    //   (8.3.5), all parameter types except the first are
1241    //   identical. [...]
1242    //
1243    // To perform this comparison, we compute the function type that
1244    // the deallocation function should have, and use that type both
1245    // for template argument deduction and for comparison purposes.
1246    //
1247    // FIXME: this comparison should ignore CC and the like.
1248    QualType ExpectedFunctionType;
1249    {
1250      const FunctionProtoType *Proto
1251        = OperatorNew->getType()->getAs<FunctionProtoType>();
1252
1253      llvm::SmallVector<QualType, 4> ArgTypes;
1254      ArgTypes.push_back(Context.VoidPtrTy);
1255      for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1256        ArgTypes.push_back(Proto->getArgType(I));
1257
1258      FunctionProtoType::ExtProtoInfo EPI;
1259      EPI.Variadic = Proto->isVariadic();
1260
1261      ExpectedFunctionType
1262        = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1263                                  ArgTypes.size(), EPI);
1264    }
1265
1266    for (LookupResult::iterator D = FoundDelete.begin(),
1267                             DEnd = FoundDelete.end();
1268         D != DEnd; ++D) {
1269      FunctionDecl *Fn = 0;
1270      if (FunctionTemplateDecl *FnTmpl
1271            = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1272        // Perform template argument deduction to try to match the
1273        // expected function type.
1274        TemplateDeductionInfo Info(Context, StartLoc);
1275        if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1276          continue;
1277      } else
1278        Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1279
1280      if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1281        Matches.push_back(std::make_pair(D.getPair(), Fn));
1282    }
1283  } else {
1284    // C++ [expr.new]p20:
1285    //   [...] Any non-placement deallocation function matches a
1286    //   non-placement allocation function. [...]
1287    for (LookupResult::iterator D = FoundDelete.begin(),
1288                             DEnd = FoundDelete.end();
1289         D != DEnd; ++D) {
1290      if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1291        if (isNonPlacementDeallocationFunction(Fn))
1292          Matches.push_back(std::make_pair(D.getPair(), Fn));
1293    }
1294  }
1295
1296  // C++ [expr.new]p20:
1297  //   [...] If the lookup finds a single matching deallocation
1298  //   function, that function will be called; otherwise, no
1299  //   deallocation function will be called.
1300  if (Matches.size() == 1) {
1301    OperatorDelete = Matches[0].second;
1302
1303    // C++0x [expr.new]p20:
1304    //   If the lookup finds the two-parameter form of a usual
1305    //   deallocation function (3.7.4.2) and that function, considered
1306    //   as a placement deallocation function, would have been
1307    //   selected as a match for the allocation function, the program
1308    //   is ill-formed.
1309    if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1310        isNonPlacementDeallocationFunction(OperatorDelete)) {
1311      Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1312        << SourceRange(PlaceArgs[0]->getLocStart(),
1313                       PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1314      Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1315        << DeleteName;
1316    } else {
1317      CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1318                            Matches[0].first);
1319    }
1320  }
1321
1322  return false;
1323}
1324
1325/// FindAllocationOverload - Find an fitting overload for the allocation
1326/// function in the specified scope.
1327bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1328                                  DeclarationName Name, Expr** Args,
1329                                  unsigned NumArgs, DeclContext *Ctx,
1330                                  bool AllowMissing, FunctionDecl *&Operator) {
1331  LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1332  LookupQualifiedName(R, Ctx);
1333  if (R.empty()) {
1334    if (AllowMissing)
1335      return false;
1336    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1337      << Name << Range;
1338  }
1339
1340  if (R.isAmbiguous())
1341    return true;
1342
1343  R.suppressDiagnostics();
1344
1345  OverloadCandidateSet Candidates(StartLoc);
1346  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1347       Alloc != AllocEnd; ++Alloc) {
1348    // Even member operator new/delete are implicitly treated as
1349    // static, so don't use AddMemberCandidate.
1350    NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1351
1352    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1353      AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1354                                   /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1355                                   Candidates,
1356                                   /*SuppressUserConversions=*/false);
1357      continue;
1358    }
1359
1360    FunctionDecl *Fn = cast<FunctionDecl>(D);
1361    AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
1362                         /*SuppressUserConversions=*/false);
1363  }
1364
1365  // Do the resolution.
1366  OverloadCandidateSet::iterator Best;
1367  switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1368  case OR_Success: {
1369    // Got one!
1370    FunctionDecl *FnDecl = Best->Function;
1371    MarkDeclarationReferenced(StartLoc, FnDecl);
1372    // The first argument is size_t, and the first parameter must be size_t,
1373    // too. This is checked on declaration and can be assumed. (It can't be
1374    // asserted on, though, since invalid decls are left in there.)
1375    // Watch out for variadic allocator function.
1376    unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1377    for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1378      ExprResult Result
1379        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1380                                                       Context,
1381                                                       FnDecl->getParamDecl(i)),
1382                                    SourceLocation(),
1383                                    Owned(Args[i]));
1384      if (Result.isInvalid())
1385        return true;
1386
1387      Args[i] = Result.takeAs<Expr>();
1388    }
1389    Operator = FnDecl;
1390    CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
1391    return false;
1392  }
1393
1394  case OR_No_Viable_Function:
1395    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1396      << Name << Range;
1397    Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1398    return true;
1399
1400  case OR_Ambiguous:
1401    Diag(StartLoc, diag::err_ovl_ambiguous_call)
1402      << Name << Range;
1403    Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1404    return true;
1405
1406  case OR_Deleted: {
1407    Diag(StartLoc, diag::err_ovl_deleted_call)
1408      << Best->Function->isDeleted()
1409      << Name
1410      << getDeletedOrUnavailableSuffix(Best->Function)
1411      << Range;
1412    Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1413    return true;
1414  }
1415  }
1416  assert(false && "Unreachable, bad result from BestViableFunction");
1417  return true;
1418}
1419
1420
1421/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1422/// delete. These are:
1423/// @code
1424///   // C++03:
1425///   void* operator new(std::size_t) throw(std::bad_alloc);
1426///   void* operator new[](std::size_t) throw(std::bad_alloc);
1427///   void operator delete(void *) throw();
1428///   void operator delete[](void *) throw();
1429///   // C++0x:
1430///   void* operator new(std::size_t);
1431///   void* operator new[](std::size_t);
1432///   void operator delete(void *);
1433///   void operator delete[](void *);
1434/// @endcode
1435/// C++0x operator delete is implicitly noexcept.
1436/// Note that the placement and nothrow forms of new are *not* implicitly
1437/// declared. Their use requires including \<new\>.
1438void Sema::DeclareGlobalNewDelete() {
1439  if (GlobalNewDeleteDeclared)
1440    return;
1441
1442  // C++ [basic.std.dynamic]p2:
1443  //   [...] The following allocation and deallocation functions (18.4) are
1444  //   implicitly declared in global scope in each translation unit of a
1445  //   program
1446  //
1447  //     C++03:
1448  //     void* operator new(std::size_t) throw(std::bad_alloc);
1449  //     void* operator new[](std::size_t) throw(std::bad_alloc);
1450  //     void  operator delete(void*) throw();
1451  //     void  operator delete[](void*) throw();
1452  //     C++0x:
1453  //     void* operator new(std::size_t);
1454  //     void* operator new[](std::size_t);
1455  //     void  operator delete(void*);
1456  //     void  operator delete[](void*);
1457  //
1458  //   These implicit declarations introduce only the function names operator
1459  //   new, operator new[], operator delete, operator delete[].
1460  //
1461  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1462  // "std" or "bad_alloc" as necessary to form the exception specification.
1463  // However, we do not make these implicit declarations visible to name
1464  // lookup.
1465  // Note that the C++0x versions of operator delete are deallocation functions,
1466  // and thus are implicitly noexcept.
1467  if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
1468    // The "std::bad_alloc" class has not yet been declared, so build it
1469    // implicitly.
1470    StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1471                                        getOrCreateStdNamespace(),
1472                                        SourceLocation(), SourceLocation(),
1473                                      &PP.getIdentifierTable().get("bad_alloc"),
1474                                        0);
1475    getStdBadAlloc()->setImplicit(true);
1476  }
1477
1478  GlobalNewDeleteDeclared = true;
1479
1480  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1481  QualType SizeT = Context.getSizeType();
1482  bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
1483
1484  DeclareGlobalAllocationFunction(
1485      Context.DeclarationNames.getCXXOperatorName(OO_New),
1486      VoidPtr, SizeT, AssumeSaneOperatorNew);
1487  DeclareGlobalAllocationFunction(
1488      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1489      VoidPtr, SizeT, AssumeSaneOperatorNew);
1490  DeclareGlobalAllocationFunction(
1491      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1492      Context.VoidTy, VoidPtr);
1493  DeclareGlobalAllocationFunction(
1494      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1495      Context.VoidTy, VoidPtr);
1496}
1497
1498/// DeclareGlobalAllocationFunction - Declares a single implicit global
1499/// allocation function if it doesn't already exist.
1500void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1501                                           QualType Return, QualType Argument,
1502                                           bool AddMallocAttr) {
1503  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1504
1505  // Check if this function is already declared.
1506  {
1507    DeclContext::lookup_iterator Alloc, AllocEnd;
1508    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1509         Alloc != AllocEnd; ++Alloc) {
1510      // Only look at non-template functions, as it is the predefined,
1511      // non-templated allocation function we are trying to declare here.
1512      if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1513        QualType InitialParamType =
1514          Context.getCanonicalType(
1515            Func->getParamDecl(0)->getType().getUnqualifiedType());
1516        // FIXME: Do we need to check for default arguments here?
1517        if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1518          if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
1519            Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1520          return;
1521        }
1522      }
1523    }
1524  }
1525
1526  QualType BadAllocType;
1527  bool HasBadAllocExceptionSpec
1528    = (Name.getCXXOverloadedOperator() == OO_New ||
1529       Name.getCXXOverloadedOperator() == OO_Array_New);
1530  if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
1531    assert(StdBadAlloc && "Must have std::bad_alloc declared");
1532    BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
1533  }
1534
1535  FunctionProtoType::ExtProtoInfo EPI;
1536  if (HasBadAllocExceptionSpec) {
1537    if (!getLangOptions().CPlusPlus0x) {
1538      EPI.ExceptionSpecType = EST_Dynamic;
1539      EPI.NumExceptions = 1;
1540      EPI.Exceptions = &BadAllocType;
1541    }
1542  } else {
1543    EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1544                                EST_BasicNoexcept : EST_DynamicNone;
1545  }
1546
1547  QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
1548  FunctionDecl *Alloc =
1549    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1550                         SourceLocation(), Name,
1551                         FnType, /*TInfo=*/0, SC_None,
1552                         SC_None, false, true);
1553  Alloc->setImplicit();
1554
1555  if (AddMallocAttr)
1556    Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1557
1558  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1559                                           SourceLocation(), 0,
1560                                           Argument, /*TInfo=*/0,
1561                                           SC_None, SC_None, 0);
1562  Alloc->setParams(&Param, 1);
1563
1564  // FIXME: Also add this declaration to the IdentifierResolver, but
1565  // make sure it is at the end of the chain to coincide with the
1566  // global scope.
1567  Context.getTranslationUnitDecl()->addDecl(Alloc);
1568}
1569
1570bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1571                                    DeclarationName Name,
1572                                    FunctionDecl* &Operator) {
1573  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1574  // Try to find operator delete/operator delete[] in class scope.
1575  LookupQualifiedName(Found, RD);
1576
1577  if (Found.isAmbiguous())
1578    return true;
1579
1580  Found.suppressDiagnostics();
1581
1582  llvm::SmallVector<DeclAccessPair,4> Matches;
1583  for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1584       F != FEnd; ++F) {
1585    NamedDecl *ND = (*F)->getUnderlyingDecl();
1586
1587    // Ignore template operator delete members from the check for a usual
1588    // deallocation function.
1589    if (isa<FunctionTemplateDecl>(ND))
1590      continue;
1591
1592    if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
1593      Matches.push_back(F.getPair());
1594  }
1595
1596  // There's exactly one suitable operator;  pick it.
1597  if (Matches.size() == 1) {
1598    Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1599    CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1600                          Matches[0]);
1601    return false;
1602
1603  // We found multiple suitable operators;  complain about the ambiguity.
1604  } else if (!Matches.empty()) {
1605    Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1606      << Name << RD;
1607
1608    for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1609           F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1610      Diag((*F)->getUnderlyingDecl()->getLocation(),
1611           diag::note_member_declared_here) << Name;
1612    return true;
1613  }
1614
1615  // We did find operator delete/operator delete[] declarations, but
1616  // none of them were suitable.
1617  if (!Found.empty()) {
1618    Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1619      << Name << RD;
1620
1621    for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1622         F != FEnd; ++F)
1623      Diag((*F)->getUnderlyingDecl()->getLocation(),
1624           diag::note_member_declared_here) << Name;
1625
1626    return true;
1627  }
1628
1629  // Look for a global declaration.
1630  DeclareGlobalNewDelete();
1631  DeclContext *TUDecl = Context.getTranslationUnitDecl();
1632
1633  CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1634  Expr* DeallocArgs[1];
1635  DeallocArgs[0] = &Null;
1636  if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1637                             DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1638                             Operator))
1639    return true;
1640
1641  assert(Operator && "Did not find a deallocation function!");
1642  return false;
1643}
1644
1645/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1646/// @code ::delete ptr; @endcode
1647/// or
1648/// @code delete [] ptr; @endcode
1649ExprResult
1650Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
1651                     bool ArrayForm, Expr *ExE) {
1652  // C++ [expr.delete]p1:
1653  //   The operand shall have a pointer type, or a class type having a single
1654  //   conversion function to a pointer type. The result has type void.
1655  //
1656  // DR599 amends "pointer type" to "pointer to object type" in both cases.
1657
1658  ExprResult Ex = Owned(ExE);
1659  FunctionDecl *OperatorDelete = 0;
1660  bool ArrayFormAsWritten = ArrayForm;
1661  bool UsualArrayDeleteWantsSize = false;
1662
1663  if (!Ex.get()->isTypeDependent()) {
1664    QualType Type = Ex.get()->getType();
1665
1666    if (const RecordType *Record = Type->getAs<RecordType>()) {
1667      if (RequireCompleteType(StartLoc, Type,
1668                              PDiag(diag::err_delete_incomplete_class_type)))
1669        return ExprError();
1670
1671      llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1672
1673      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1674      const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
1675      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1676             E = Conversions->end(); I != E; ++I) {
1677        NamedDecl *D = I.getDecl();
1678        if (isa<UsingShadowDecl>(D))
1679          D = cast<UsingShadowDecl>(D)->getTargetDecl();
1680
1681        // Skip over templated conversion functions; they aren't considered.
1682        if (isa<FunctionTemplateDecl>(D))
1683          continue;
1684
1685        CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
1686
1687        QualType ConvType = Conv->getConversionType().getNonReferenceType();
1688        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1689          if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
1690            ObjectPtrConversions.push_back(Conv);
1691      }
1692      if (ObjectPtrConversions.size() == 1) {
1693        // We have a single conversion to a pointer-to-object type. Perform
1694        // that conversion.
1695        // TODO: don't redo the conversion calculation.
1696        ExprResult Res =
1697          PerformImplicitConversion(Ex.get(),
1698                            ObjectPtrConversions.front()->getConversionType(),
1699                                    AA_Converting);
1700        if (Res.isUsable()) {
1701          Ex = move(Res);
1702          Type = Ex.get()->getType();
1703        }
1704      }
1705      else if (ObjectPtrConversions.size() > 1) {
1706        Diag(StartLoc, diag::err_ambiguous_delete_operand)
1707              << Type << Ex.get()->getSourceRange();
1708        for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1709          NoteOverloadCandidate(ObjectPtrConversions[i]);
1710        return ExprError();
1711      }
1712    }
1713
1714    if (!Type->isPointerType())
1715      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1716        << Type << Ex.get()->getSourceRange());
1717
1718    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
1719    if (Pointee->isVoidType() && !isSFINAEContext()) {
1720      // The C++ standard bans deleting a pointer to a non-object type, which
1721      // effectively bans deletion of "void*". However, most compilers support
1722      // this, so we treat it as a warning unless we're in a SFINAE context.
1723      Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1724        << Type << Ex.get()->getSourceRange();
1725    } else if (Pointee->isFunctionType() || Pointee->isVoidType())
1726      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1727        << Type << Ex.get()->getSourceRange());
1728    else if (!Pointee->isDependentType() &&
1729             RequireCompleteType(StartLoc, Pointee,
1730                                 PDiag(diag::warn_delete_incomplete)
1731                                   << Ex.get()->getSourceRange()))
1732      return ExprError();
1733    else if (unsigned AddressSpace = Pointee.getAddressSpace())
1734      return Diag(Ex.get()->getLocStart(),
1735                  diag::err_address_space_qualified_delete)
1736               << Pointee.getUnqualifiedType() << AddressSpace;
1737    // C++ [expr.delete]p2:
1738    //   [Note: a pointer to a const type can be the operand of a
1739    //   delete-expression; it is not necessary to cast away the constness
1740    //   (5.2.11) of the pointer expression before it is used as the operand
1741    //   of the delete-expression. ]
1742    Ex = ImpCastExprToType(Ex.take(), Context.getPointerType(Context.VoidTy),
1743                      CK_NoOp);
1744
1745    if (Pointee->isArrayType() && !ArrayForm) {
1746      Diag(StartLoc, diag::warn_delete_array_type)
1747          << Type << Ex.get()->getSourceRange()
1748          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1749      ArrayForm = true;
1750    }
1751
1752    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1753                                      ArrayForm ? OO_Array_Delete : OO_Delete);
1754
1755    QualType PointeeElem = Context.getBaseElementType(Pointee);
1756    if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1757      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1758
1759      if (!UseGlobal &&
1760          FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
1761        return ExprError();
1762
1763      // If we're allocating an array of records, check whether the
1764      // usual operator delete[] has a size_t parameter.
1765      if (ArrayForm) {
1766        // If the user specifically asked to use the global allocator,
1767        // we'll need to do the lookup into the class.
1768        if (UseGlobal)
1769          UsualArrayDeleteWantsSize =
1770            doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1771
1772        // Otherwise, the usual operator delete[] should be the
1773        // function we just found.
1774        else if (isa<CXXMethodDecl>(OperatorDelete))
1775          UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1776      }
1777
1778      if (!RD->hasTrivialDestructor())
1779        if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1780          MarkDeclarationReferenced(StartLoc,
1781                                    const_cast<CXXDestructorDecl*>(Dtor));
1782          DiagnoseUseOfDecl(Dtor, StartLoc);
1783        }
1784    }
1785
1786    if (!OperatorDelete) {
1787      // Look for a global declaration.
1788      DeclareGlobalNewDelete();
1789      DeclContext *TUDecl = Context.getTranslationUnitDecl();
1790      Expr *Arg = Ex.get();
1791      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
1792                                 &Arg, 1, TUDecl, /*AllowMissing=*/false,
1793                                 OperatorDelete))
1794        return ExprError();
1795    }
1796
1797    MarkDeclarationReferenced(StartLoc, OperatorDelete);
1798
1799    // Check access and ambiguity of operator delete and destructor.
1800    if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1801      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1802      if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1803          CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
1804                      PDiag(diag::err_access_dtor) << PointeeElem);
1805      }
1806    }
1807
1808  }
1809
1810  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
1811                                           ArrayFormAsWritten,
1812                                           UsualArrayDeleteWantsSize,
1813                                           OperatorDelete, Ex.take(), StartLoc));
1814}
1815
1816/// \brief Check the use of the given variable as a C++ condition in an if,
1817/// while, do-while, or switch statement.
1818ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1819                                        SourceLocation StmtLoc,
1820                                        bool ConvertToBoolean) {
1821  QualType T = ConditionVar->getType();
1822
1823  // C++ [stmt.select]p2:
1824  //   The declarator shall not specify a function or an array.
1825  if (T->isFunctionType())
1826    return ExprError(Diag(ConditionVar->getLocation(),
1827                          diag::err_invalid_use_of_function_type)
1828                       << ConditionVar->getSourceRange());
1829  else if (T->isArrayType())
1830    return ExprError(Diag(ConditionVar->getLocation(),
1831                          diag::err_invalid_use_of_array_type)
1832                     << ConditionVar->getSourceRange());
1833
1834  ExprResult Condition =
1835    Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1836                                        ConditionVar,
1837                                        ConditionVar->getLocation(),
1838                            ConditionVar->getType().getNonReferenceType(),
1839                              VK_LValue));
1840  if (ConvertToBoolean) {
1841    Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
1842    if (Condition.isInvalid())
1843      return ExprError();
1844  }
1845
1846  return move(Condition);
1847}
1848
1849/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1850ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
1851  // C++ 6.4p4:
1852  // The value of a condition that is an initialized declaration in a statement
1853  // other than a switch statement is the value of the declared variable
1854  // implicitly converted to type bool. If that conversion is ill-formed, the
1855  // program is ill-formed.
1856  // The value of a condition that is an expression is the value of the
1857  // expression, implicitly converted to bool.
1858  //
1859  return PerformContextuallyConvertToBool(CondExpr);
1860}
1861
1862/// Helper function to determine whether this is the (deprecated) C++
1863/// conversion from a string literal to a pointer to non-const char or
1864/// non-const wchar_t (for narrow and wide string literals,
1865/// respectively).
1866bool
1867Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1868  // Look inside the implicit cast, if it exists.
1869  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1870    From = Cast->getSubExpr();
1871
1872  // A string literal (2.13.4) that is not a wide string literal can
1873  // be converted to an rvalue of type "pointer to char"; a wide
1874  // string literal can be converted to an rvalue of type "pointer
1875  // to wchar_t" (C++ 4.2p2).
1876  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
1877    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
1878      if (const BuiltinType *ToPointeeType
1879          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
1880        // This conversion is considered only when there is an
1881        // explicit appropriate pointer target type (C++ 4.2p2).
1882        if (!ToPtrType->getPointeeType().hasQualifiers() &&
1883            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1884             (!StrLit->isWide() &&
1885              (ToPointeeType->getKind() == BuiltinType::Char_U ||
1886               ToPointeeType->getKind() == BuiltinType::Char_S))))
1887          return true;
1888      }
1889
1890  return false;
1891}
1892
1893static ExprResult BuildCXXCastArgument(Sema &S,
1894                                       SourceLocation CastLoc,
1895                                       QualType Ty,
1896                                       CastKind Kind,
1897                                       CXXMethodDecl *Method,
1898                                       NamedDecl *FoundDecl,
1899                                       Expr *From) {
1900  switch (Kind) {
1901  default: assert(0 && "Unhandled cast kind!");
1902  case CK_ConstructorConversion: {
1903    ASTOwningVector<Expr*> ConstructorArgs(S);
1904
1905    if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1906                                  MultiExprArg(&From, 1),
1907                                  CastLoc, ConstructorArgs))
1908      return ExprError();
1909
1910    ExprResult Result =
1911    S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1912                            move_arg(ConstructorArgs),
1913                            /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1914                            SourceRange());
1915    if (Result.isInvalid())
1916      return ExprError();
1917
1918    return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1919  }
1920
1921  case CK_UserDefinedConversion: {
1922    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1923
1924    // Create an implicit call expr that calls it.
1925    ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
1926    if (Result.isInvalid())
1927      return ExprError();
1928
1929    return S.MaybeBindToTemporary(Result.get());
1930  }
1931  }
1932}
1933
1934/// PerformImplicitConversion - Perform an implicit conversion of the
1935/// expression From to the type ToType using the pre-computed implicit
1936/// conversion sequence ICS. Returns the converted
1937/// expression. Action is the kind of conversion we're performing,
1938/// used in the error message.
1939ExprResult
1940Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1941                                const ImplicitConversionSequence &ICS,
1942                                AssignmentAction Action, bool CStyle) {
1943  switch (ICS.getKind()) {
1944  case ImplicitConversionSequence::StandardConversion: {
1945    ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
1946                                               Action, CStyle);
1947    if (Res.isInvalid())
1948      return ExprError();
1949    From = Res.take();
1950    break;
1951  }
1952
1953  case ImplicitConversionSequence::UserDefinedConversion: {
1954
1955      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1956      CastKind CastKind;
1957      QualType BeforeToType;
1958      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1959        CastKind = CK_UserDefinedConversion;
1960
1961        // If the user-defined conversion is specified by a conversion function,
1962        // the initial standard conversion sequence converts the source type to
1963        // the implicit object parameter of the conversion function.
1964        BeforeToType = Context.getTagDeclType(Conv->getParent());
1965      } else {
1966        const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
1967        CastKind = CK_ConstructorConversion;
1968        // Do no conversion if dealing with ... for the first conversion.
1969        if (!ICS.UserDefined.EllipsisConversion) {
1970          // If the user-defined conversion is specified by a constructor, the
1971          // initial standard conversion sequence converts the source type to the
1972          // type required by the argument of the constructor
1973          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1974        }
1975      }
1976      // Watch out for elipsis conversion.
1977      if (!ICS.UserDefined.EllipsisConversion) {
1978        ExprResult Res =
1979          PerformImplicitConversion(From, BeforeToType,
1980                                    ICS.UserDefined.Before, AA_Converting,
1981                                    CStyle);
1982        if (Res.isInvalid())
1983          return ExprError();
1984        From = Res.take();
1985      }
1986
1987      ExprResult CastArg
1988        = BuildCXXCastArgument(*this,
1989                               From->getLocStart(),
1990                               ToType.getNonReferenceType(),
1991                               CastKind, cast<CXXMethodDecl>(FD),
1992                               ICS.UserDefined.FoundConversionFunction,
1993                               From);
1994
1995      if (CastArg.isInvalid())
1996        return ExprError();
1997
1998      From = CastArg.take();
1999
2000      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2001                                       AA_Converting, CStyle);
2002  }
2003
2004  case ImplicitConversionSequence::AmbiguousConversion:
2005    ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
2006                          PDiag(diag::err_typecheck_ambiguous_condition)
2007                            << From->getSourceRange());
2008     return ExprError();
2009
2010  case ImplicitConversionSequence::EllipsisConversion:
2011    assert(false && "Cannot perform an ellipsis conversion");
2012    return Owned(From);
2013
2014  case ImplicitConversionSequence::BadConversion:
2015    return ExprError();
2016  }
2017
2018  // Everything went well.
2019  return Owned(From);
2020}
2021
2022/// PerformImplicitConversion - Perform an implicit conversion of the
2023/// expression From to the type ToType by following the standard
2024/// conversion sequence SCS. Returns the converted
2025/// expression. Flavor is the context in which we're performing this
2026/// conversion, for use in error messages.
2027ExprResult
2028Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2029                                const StandardConversionSequence& SCS,
2030                                AssignmentAction Action, bool CStyle) {
2031  // Overall FIXME: we are recomputing too many types here and doing far too
2032  // much extra work. What this means is that we need to keep track of more
2033  // information that is computed when we try the implicit conversion initially,
2034  // so that we don't need to recompute anything here.
2035  QualType FromType = From->getType();
2036
2037  if (SCS.CopyConstructor) {
2038    // FIXME: When can ToType be a reference type?
2039    assert(!ToType->isReferenceType());
2040    if (SCS.Second == ICK_Derived_To_Base) {
2041      ASTOwningVector<Expr*> ConstructorArgs(*this);
2042      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
2043                                  MultiExprArg(*this, &From, 1),
2044                                  /*FIXME:ConstructLoc*/SourceLocation(),
2045                                  ConstructorArgs))
2046        return ExprError();
2047      return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2048                                   ToType, SCS.CopyConstructor,
2049                                   move_arg(ConstructorArgs),
2050                                   /*ZeroInit*/ false,
2051                                   CXXConstructExpr::CK_Complete,
2052                                   SourceRange());
2053    }
2054    return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2055                                 ToType, SCS.CopyConstructor,
2056                                 MultiExprArg(*this, &From, 1),
2057                                 /*ZeroInit*/ false,
2058                                 CXXConstructExpr::CK_Complete,
2059                                 SourceRange());
2060  }
2061
2062  // Resolve overloaded function references.
2063  if (Context.hasSameType(FromType, Context.OverloadTy)) {
2064    DeclAccessPair Found;
2065    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2066                                                          true, Found);
2067    if (!Fn)
2068      return ExprError();
2069
2070    if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
2071      return ExprError();
2072
2073    From = FixOverloadedFunctionReference(From, Found, Fn);
2074    FromType = From->getType();
2075  }
2076
2077  // Perform the first implicit conversion.
2078  switch (SCS.First) {
2079  case ICK_Identity:
2080    // Nothing to do.
2081    break;
2082
2083  case ICK_Lvalue_To_Rvalue:
2084    // Should this get its own ICK?
2085    if (From->getObjectKind() == OK_ObjCProperty) {
2086      ExprResult FromRes = ConvertPropertyForRValue(From);
2087      if (FromRes.isInvalid())
2088        return ExprError();
2089      From = FromRes.take();
2090      if (!From->isGLValue()) break;
2091    }
2092
2093    // Check for trivial buffer overflows.
2094    CheckArrayAccess(From);
2095
2096    FromType = FromType.getUnqualifiedType();
2097    From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2098                                    From, 0, VK_RValue);
2099    break;
2100
2101  case ICK_Array_To_Pointer:
2102    FromType = Context.getArrayDecayedType(FromType);
2103    From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay).take();
2104    break;
2105
2106  case ICK_Function_To_Pointer:
2107    FromType = Context.getPointerType(FromType);
2108    From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay).take();
2109    break;
2110
2111  default:
2112    assert(false && "Improper first standard conversion");
2113    break;
2114  }
2115
2116  // Perform the second implicit conversion
2117  switch (SCS.Second) {
2118  case ICK_Identity:
2119    // If both sides are functions (or pointers/references to them), there could
2120    // be incompatible exception declarations.
2121    if (CheckExceptionSpecCompatibility(From, ToType))
2122      return ExprError();
2123    // Nothing else to do.
2124    break;
2125
2126  case ICK_NoReturn_Adjustment:
2127    // If both sides are functions (or pointers/references to them), there could
2128    // be incompatible exception declarations.
2129    if (CheckExceptionSpecCompatibility(From, ToType))
2130      return ExprError();
2131
2132    From = ImpCastExprToType(From, ToType, CK_NoOp).take();
2133    break;
2134
2135  case ICK_Integral_Promotion:
2136  case ICK_Integral_Conversion:
2137    From = ImpCastExprToType(From, ToType, CK_IntegralCast).take();
2138    break;
2139
2140  case ICK_Floating_Promotion:
2141  case ICK_Floating_Conversion:
2142    From = ImpCastExprToType(From, ToType, CK_FloatingCast).take();
2143    break;
2144
2145  case ICK_Complex_Promotion:
2146  case ICK_Complex_Conversion: {
2147    QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2148    QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2149    CastKind CK;
2150    if (FromEl->isRealFloatingType()) {
2151      if (ToEl->isRealFloatingType())
2152        CK = CK_FloatingComplexCast;
2153      else
2154        CK = CK_FloatingComplexToIntegralComplex;
2155    } else if (ToEl->isRealFloatingType()) {
2156      CK = CK_IntegralComplexToFloatingComplex;
2157    } else {
2158      CK = CK_IntegralComplexCast;
2159    }
2160    From = ImpCastExprToType(From, ToType, CK).take();
2161    break;
2162  }
2163
2164  case ICK_Floating_Integral:
2165    if (ToType->isRealFloatingType())
2166      From = ImpCastExprToType(From, ToType, CK_IntegralToFloating).take();
2167    else
2168      From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral).take();
2169    break;
2170
2171  case ICK_Compatible_Conversion:
2172    From = ImpCastExprToType(From, ToType, CK_NoOp).take();
2173    break;
2174
2175  case ICK_Pointer_Conversion: {
2176    if (SCS.IncompatibleObjC && Action != AA_Casting) {
2177      // Diagnose incompatible Objective-C conversions
2178      if (Action == AA_Initializing)
2179        Diag(From->getSourceRange().getBegin(),
2180             diag::ext_typecheck_convert_incompatible_pointer)
2181          << ToType << From->getType() << Action
2182          << From->getSourceRange();
2183      else
2184        Diag(From->getSourceRange().getBegin(),
2185             diag::ext_typecheck_convert_incompatible_pointer)
2186          << From->getType() << ToType << Action
2187          << From->getSourceRange();
2188    }
2189
2190    CastKind Kind = CK_Invalid;
2191    CXXCastPath BasePath;
2192    if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
2193      return ExprError();
2194    From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath).take();
2195    break;
2196  }
2197
2198  case ICK_Pointer_Member: {
2199    CastKind Kind = CK_Invalid;
2200    CXXCastPath BasePath;
2201    if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
2202      return ExprError();
2203    if (CheckExceptionSpecCompatibility(From, ToType))
2204      return ExprError();
2205    From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath).take();
2206    break;
2207  }
2208
2209  case ICK_Boolean_Conversion:
2210    From = ImpCastExprToType(From, Context.BoolTy,
2211                             ScalarTypeToBooleanCastKind(FromType)).take();
2212    break;
2213
2214  case ICK_Derived_To_Base: {
2215    CXXCastPath BasePath;
2216    if (CheckDerivedToBaseConversion(From->getType(),
2217                                     ToType.getNonReferenceType(),
2218                                     From->getLocStart(),
2219                                     From->getSourceRange(),
2220                                     &BasePath,
2221                                     CStyle))
2222      return ExprError();
2223
2224    From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2225                      CK_DerivedToBase, CastCategory(From),
2226                      &BasePath).take();
2227    break;
2228  }
2229
2230  case ICK_Vector_Conversion:
2231    From = ImpCastExprToType(From, ToType, CK_BitCast).take();
2232    break;
2233
2234  case ICK_Vector_Splat:
2235    From = ImpCastExprToType(From, ToType, CK_VectorSplat).take();
2236    break;
2237
2238  case ICK_Complex_Real:
2239    // Case 1.  x -> _Complex y
2240    if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2241      QualType ElType = ToComplex->getElementType();
2242      bool isFloatingComplex = ElType->isRealFloatingType();
2243
2244      // x -> y
2245      if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2246        // do nothing
2247      } else if (From->getType()->isRealFloatingType()) {
2248        From = ImpCastExprToType(From, ElType,
2249                isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
2250      } else {
2251        assert(From->getType()->isIntegerType());
2252        From = ImpCastExprToType(From, ElType,
2253                isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
2254      }
2255      // y -> _Complex y
2256      From = ImpCastExprToType(From, ToType,
2257                   isFloatingComplex ? CK_FloatingRealToComplex
2258                                     : CK_IntegralRealToComplex).take();
2259
2260    // Case 2.  _Complex x -> y
2261    } else {
2262      const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2263      assert(FromComplex);
2264
2265      QualType ElType = FromComplex->getElementType();
2266      bool isFloatingComplex = ElType->isRealFloatingType();
2267
2268      // _Complex x -> x
2269      From = ImpCastExprToType(From, ElType,
2270                   isFloatingComplex ? CK_FloatingComplexToReal
2271                                     : CK_IntegralComplexToReal).take();
2272
2273      // x -> y
2274      if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2275        // do nothing
2276      } else if (ToType->isRealFloatingType()) {
2277        From = ImpCastExprToType(From, ToType,
2278                isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating).take();
2279      } else {
2280        assert(ToType->isIntegerType());
2281        From = ImpCastExprToType(From, ToType,
2282                isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast).take();
2283      }
2284    }
2285    break;
2286
2287  case ICK_Block_Pointer_Conversion: {
2288      From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2289                               VK_RValue).take();
2290      break;
2291    }
2292
2293  case ICK_TransparentUnionConversion: {
2294    ExprResult FromRes = Owned(From);
2295    Sema::AssignConvertType ConvTy =
2296      CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2297    if (FromRes.isInvalid())
2298      return ExprError();
2299    From = FromRes.take();
2300    assert ((ConvTy == Sema::Compatible) &&
2301            "Improper transparent union conversion");
2302    (void)ConvTy;
2303    break;
2304  }
2305
2306  case ICK_Lvalue_To_Rvalue:
2307  case ICK_Array_To_Pointer:
2308  case ICK_Function_To_Pointer:
2309  case ICK_Qualification:
2310  case ICK_Num_Conversion_Kinds:
2311    assert(false && "Improper second standard conversion");
2312    break;
2313  }
2314
2315  switch (SCS.Third) {
2316  case ICK_Identity:
2317    // Nothing to do.
2318    break;
2319
2320  case ICK_Qualification: {
2321    // The qualification keeps the category of the inner expression, unless the
2322    // target type isn't a reference.
2323    ExprValueKind VK = ToType->isReferenceType() ?
2324                                  CastCategory(From) : VK_RValue;
2325    From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2326                             CK_NoOp, VK).take();
2327
2328    if (SCS.DeprecatedStringLiteralToCharPtr &&
2329        !getLangOptions().WritableStrings)
2330      Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2331        << ToType.getNonReferenceType();
2332
2333    break;
2334    }
2335
2336  default:
2337    assert(false && "Improper third standard conversion");
2338    break;
2339  }
2340
2341  return Owned(From);
2342}
2343
2344ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
2345                                     SourceLocation KWLoc,
2346                                     ParsedType Ty,
2347                                     SourceLocation RParen) {
2348  TypeSourceInfo *TSInfo;
2349  QualType T = GetTypeFromParser(Ty, &TSInfo);
2350
2351  if (!TSInfo)
2352    TSInfo = Context.getTrivialTypeSourceInfo(T);
2353  return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
2354}
2355
2356/// \brief Check the completeness of a type in a unary type trait.
2357///
2358/// If the particular type trait requires a complete type, tries to complete
2359/// it. If completing the type fails, a diagnostic is emitted and false
2360/// returned. If completing the type succeeds or no completion was required,
2361/// returns true.
2362static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2363                                                UnaryTypeTrait UTT,
2364                                                SourceLocation Loc,
2365                                                QualType ArgTy) {
2366  // C++0x [meta.unary.prop]p3:
2367  //   For all of the class templates X declared in this Clause, instantiating
2368  //   that template with a template argument that is a class template
2369  //   specialization may result in the implicit instantiation of the template
2370  //   argument if and only if the semantics of X require that the argument
2371  //   must be a complete type.
2372  // We apply this rule to all the type trait expressions used to implement
2373  // these class templates. We also try to follow any GCC documented behavior
2374  // in these expressions to ensure portability of standard libraries.
2375  switch (UTT) {
2376    // is_complete_type somewhat obviously cannot require a complete type.
2377  case UTT_IsCompleteType:
2378    // Fall-through
2379
2380    // These traits are modeled on the type predicates in C++0x
2381    // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2382    // requiring a complete type, as whether or not they return true cannot be
2383    // impacted by the completeness of the type.
2384  case UTT_IsVoid:
2385  case UTT_IsIntegral:
2386  case UTT_IsFloatingPoint:
2387  case UTT_IsArray:
2388  case UTT_IsPointer:
2389  case UTT_IsLvalueReference:
2390  case UTT_IsRvalueReference:
2391  case UTT_IsMemberFunctionPointer:
2392  case UTT_IsMemberObjectPointer:
2393  case UTT_IsEnum:
2394  case UTT_IsUnion:
2395  case UTT_IsClass:
2396  case UTT_IsFunction:
2397  case UTT_IsReference:
2398  case UTT_IsArithmetic:
2399  case UTT_IsFundamental:
2400  case UTT_IsObject:
2401  case UTT_IsScalar:
2402  case UTT_IsCompound:
2403  case UTT_IsMemberPointer:
2404    // Fall-through
2405
2406    // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2407    // which requires some of its traits to have the complete type. However,
2408    // the completeness of the type cannot impact these traits' semantics, and
2409    // so they don't require it. This matches the comments on these traits in
2410    // Table 49.
2411  case UTT_IsConst:
2412  case UTT_IsVolatile:
2413  case UTT_IsSigned:
2414  case UTT_IsUnsigned:
2415    return true;
2416
2417    // C++0x [meta.unary.prop] Table 49 requires the following traits to be
2418    // applied to a complete type.
2419  case UTT_IsTrivial:
2420  case UTT_IsStandardLayout:
2421  case UTT_IsPOD:
2422  case UTT_IsLiteral:
2423  case UTT_IsEmpty:
2424  case UTT_IsPolymorphic:
2425  case UTT_IsAbstract:
2426    // Fall-through
2427
2428    // These trait expressions are designed to help implement predicates in
2429    // [meta.unary.prop] despite not being named the same. They are specified
2430    // by both GCC and the Embarcadero C++ compiler, and require the complete
2431    // type due to the overarching C++0x type predicates being implemented
2432    // requiring the complete type.
2433  case UTT_HasNothrowAssign:
2434  case UTT_HasNothrowConstructor:
2435  case UTT_HasNothrowCopy:
2436  case UTT_HasTrivialAssign:
2437  case UTT_HasTrivialConstructor:
2438  case UTT_HasTrivialCopy:
2439  case UTT_HasTrivialDestructor:
2440  case UTT_HasVirtualDestructor:
2441    // Arrays of unknown bound are expressly allowed.
2442    QualType ElTy = ArgTy;
2443    if (ArgTy->isIncompleteArrayType())
2444      ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2445
2446    // The void type is expressly allowed.
2447    if (ElTy->isVoidType())
2448      return true;
2449
2450    return !S.RequireCompleteType(
2451      Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
2452  }
2453  llvm_unreachable("Type trait not handled by switch");
2454}
2455
2456static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2457                                   SourceLocation KeyLoc, QualType T) {
2458  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
2459
2460  ASTContext &C = Self.Context;
2461  switch(UTT) {
2462    // Type trait expressions corresponding to the primary type category
2463    // predicates in C++0x [meta.unary.cat].
2464  case UTT_IsVoid:
2465    return T->isVoidType();
2466  case UTT_IsIntegral:
2467    return T->isIntegralType(C);
2468  case UTT_IsFloatingPoint:
2469    return T->isFloatingType();
2470  case UTT_IsArray:
2471    return T->isArrayType();
2472  case UTT_IsPointer:
2473    return T->isPointerType();
2474  case UTT_IsLvalueReference:
2475    return T->isLValueReferenceType();
2476  case UTT_IsRvalueReference:
2477    return T->isRValueReferenceType();
2478  case UTT_IsMemberFunctionPointer:
2479    return T->isMemberFunctionPointerType();
2480  case UTT_IsMemberObjectPointer:
2481    return T->isMemberDataPointerType();
2482  case UTT_IsEnum:
2483    return T->isEnumeralType();
2484  case UTT_IsUnion:
2485    return T->isUnionType();
2486  case UTT_IsClass:
2487    return T->isClassType() || T->isStructureType();
2488  case UTT_IsFunction:
2489    return T->isFunctionType();
2490
2491    // Type trait expressions which correspond to the convenient composition
2492    // predicates in C++0x [meta.unary.comp].
2493  case UTT_IsReference:
2494    return T->isReferenceType();
2495  case UTT_IsArithmetic:
2496    return T->isArithmeticType() && !T->isEnumeralType();
2497  case UTT_IsFundamental:
2498    return T->isFundamentalType();
2499  case UTT_IsObject:
2500    return T->isObjectType();
2501  case UTT_IsScalar:
2502    return T->isScalarType();
2503  case UTT_IsCompound:
2504    return T->isCompoundType();
2505  case UTT_IsMemberPointer:
2506    return T->isMemberPointerType();
2507
2508    // Type trait expressions which correspond to the type property predicates
2509    // in C++0x [meta.unary.prop].
2510  case UTT_IsConst:
2511    return T.isConstQualified();
2512  case UTT_IsVolatile:
2513    return T.isVolatileQualified();
2514  case UTT_IsTrivial:
2515    return T->isTrivialType();
2516  case UTT_IsStandardLayout:
2517    return T->isStandardLayoutType();
2518  case UTT_IsPOD:
2519    return T->isPODType();
2520  case UTT_IsLiteral:
2521    return T->isLiteralType();
2522  case UTT_IsEmpty:
2523    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2524      return !RD->isUnion() && RD->isEmpty();
2525    return false;
2526  case UTT_IsPolymorphic:
2527    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2528      return RD->isPolymorphic();
2529    return false;
2530  case UTT_IsAbstract:
2531    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2532      return RD->isAbstract();
2533    return false;
2534  case UTT_IsSigned:
2535    return T->isSignedIntegerType();
2536  case UTT_IsUnsigned:
2537    return T->isUnsignedIntegerType();
2538
2539    // Type trait expressions which query classes regarding their construction,
2540    // destruction, and copying. Rather than being based directly on the
2541    // related type predicates in the standard, they are specified by both
2542    // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2543    // specifications.
2544    //
2545    //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2546    //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2547  case UTT_HasTrivialConstructor:
2548    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2549    //   If __is_pod (type) is true then the trait is true, else if type is
2550    //   a cv class or union type (or array thereof) with a trivial default
2551    //   constructor ([class.ctor]) then the trait is true, else it is false.
2552    if (T->isPODType())
2553      return true;
2554    if (const RecordType *RT =
2555          C.getBaseElementType(T)->getAs<RecordType>())
2556      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2557    return false;
2558  case UTT_HasTrivialCopy:
2559    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2560    //   If __is_pod (type) is true or type is a reference type then
2561    //   the trait is true, else if type is a cv class or union type
2562    //   with a trivial copy constructor ([class.copy]) then the trait
2563    //   is true, else it is false.
2564    if (T->isPODType() || T->isReferenceType())
2565      return true;
2566    if (const RecordType *RT = T->getAs<RecordType>())
2567      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2568    return false;
2569  case UTT_HasTrivialAssign:
2570    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2571    //   If type is const qualified or is a reference type then the
2572    //   trait is false. Otherwise if __is_pod (type) is true then the
2573    //   trait is true, else if type is a cv class or union type with
2574    //   a trivial copy assignment ([class.copy]) then the trait is
2575    //   true, else it is false.
2576    // Note: the const and reference restrictions are interesting,
2577    // given that const and reference members don't prevent a class
2578    // from having a trivial copy assignment operator (but do cause
2579    // errors if the copy assignment operator is actually used, q.v.
2580    // [class.copy]p12).
2581
2582    if (C.getBaseElementType(T).isConstQualified())
2583      return false;
2584    if (T->isPODType())
2585      return true;
2586    if (const RecordType *RT = T->getAs<RecordType>())
2587      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2588    return false;
2589  case UTT_HasTrivialDestructor:
2590    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2591    //   If __is_pod (type) is true or type is a reference type
2592    //   then the trait is true, else if type is a cv class or union
2593    //   type (or array thereof) with a trivial destructor
2594    //   ([class.dtor]) then the trait is true, else it is
2595    //   false.
2596    if (T->isPODType() || T->isReferenceType())
2597      return true;
2598    if (const RecordType *RT =
2599          C.getBaseElementType(T)->getAs<RecordType>())
2600      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2601    return false;
2602  // TODO: Propagate nothrowness for implicitly declared special members.
2603  case UTT_HasNothrowAssign:
2604    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2605    //   If type is const qualified or is a reference type then the
2606    //   trait is false. Otherwise if __has_trivial_assign (type)
2607    //   is true then the trait is true, else if type is a cv class
2608    //   or union type with copy assignment operators that are known
2609    //   not to throw an exception then the trait is true, else it is
2610    //   false.
2611    if (C.getBaseElementType(T).isConstQualified())
2612      return false;
2613    if (T->isReferenceType())
2614      return false;
2615    if (T->isPODType())
2616      return true;
2617    if (const RecordType *RT = T->getAs<RecordType>()) {
2618      CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2619      if (RD->hasTrivialCopyAssignment())
2620        return true;
2621
2622      bool FoundAssign = false;
2623      bool AllNoThrow = true;
2624      DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
2625      LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2626                       Sema::LookupOrdinaryName);
2627      if (Self.LookupQualifiedName(Res, RD)) {
2628        for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2629             Op != OpEnd; ++Op) {
2630          CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2631          if (Operator->isCopyAssignmentOperator()) {
2632            FoundAssign = true;
2633            const FunctionProtoType *CPT
2634                = Operator->getType()->getAs<FunctionProtoType>();
2635            if (!CPT->isNothrow(Self.Context)) {
2636              AllNoThrow = false;
2637              break;
2638            }
2639          }
2640        }
2641      }
2642
2643      return FoundAssign && AllNoThrow;
2644    }
2645    return false;
2646  case UTT_HasNothrowCopy:
2647    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2648    //   If __has_trivial_copy (type) is true then the trait is true, else
2649    //   if type is a cv class or union type with copy constructors that are
2650    //   known not to throw an exception then the trait is true, else it is
2651    //   false.
2652    if (T->isPODType() || T->isReferenceType())
2653      return true;
2654    if (const RecordType *RT = T->getAs<RecordType>()) {
2655      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2656      if (RD->hasTrivialCopyConstructor())
2657        return true;
2658
2659      bool FoundConstructor = false;
2660      bool AllNoThrow = true;
2661      unsigned FoundTQs;
2662      DeclContext::lookup_const_iterator Con, ConEnd;
2663      for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2664           Con != ConEnd; ++Con) {
2665        // A template constructor is never a copy constructor.
2666        // FIXME: However, it may actually be selected at the actual overload
2667        // resolution point.
2668        if (isa<FunctionTemplateDecl>(*Con))
2669          continue;
2670        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2671        if (Constructor->isCopyConstructor(FoundTQs)) {
2672          FoundConstructor = true;
2673          const FunctionProtoType *CPT
2674              = Constructor->getType()->getAs<FunctionProtoType>();
2675          // FIXME: check whether evaluating default arguments can throw.
2676          // For now, we'll be conservative and assume that they can throw.
2677          if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1) {
2678            AllNoThrow = false;
2679            break;
2680          }
2681        }
2682      }
2683
2684      return FoundConstructor && AllNoThrow;
2685    }
2686    return false;
2687  case UTT_HasNothrowConstructor:
2688    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2689    //   If __has_trivial_constructor (type) is true then the trait is
2690    //   true, else if type is a cv class or union type (or array
2691    //   thereof) with a default constructor that is known not to
2692    //   throw an exception then the trait is true, else it is false.
2693    if (T->isPODType())
2694      return true;
2695    if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2696      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2697      if (RD->hasTrivialConstructor())
2698        return true;
2699
2700      DeclContext::lookup_const_iterator Con, ConEnd;
2701      for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2702           Con != ConEnd; ++Con) {
2703        // FIXME: In C++0x, a constructor template can be a default constructor.
2704        if (isa<FunctionTemplateDecl>(*Con))
2705          continue;
2706        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2707        if (Constructor->isDefaultConstructor()) {
2708          const FunctionProtoType *CPT
2709              = Constructor->getType()->getAs<FunctionProtoType>();
2710          // TODO: check whether evaluating default arguments can throw.
2711          // For now, we'll be conservative and assume that they can throw.
2712          return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
2713        }
2714      }
2715    }
2716    return false;
2717  case UTT_HasVirtualDestructor:
2718    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2719    //   If type is a class type with a virtual destructor ([class.dtor])
2720    //   then the trait is true, else it is false.
2721    if (const RecordType *Record = T->getAs<RecordType>()) {
2722      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2723      if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
2724        return Destructor->isVirtual();
2725    }
2726    return false;
2727
2728    // These type trait expressions are modeled on the specifications for the
2729    // Embarcadero C++0x type trait functions:
2730    //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2731  case UTT_IsCompleteType:
2732    // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
2733    //   Returns True if and only if T is a complete type at the point of the
2734    //   function call.
2735    return !T->isIncompleteType();
2736  }
2737  llvm_unreachable("Type trait not covered by switch");
2738}
2739
2740ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
2741                                     SourceLocation KWLoc,
2742                                     TypeSourceInfo *TSInfo,
2743                                     SourceLocation RParen) {
2744  QualType T = TSInfo->getType();
2745  if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
2746    return ExprError();
2747
2748  bool Value = false;
2749  if (!T->isDependentType())
2750    Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
2751
2752  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
2753                                                RParen, Context.BoolTy));
2754}
2755
2756ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2757                                      SourceLocation KWLoc,
2758                                      ParsedType LhsTy,
2759                                      ParsedType RhsTy,
2760                                      SourceLocation RParen) {
2761  TypeSourceInfo *LhsTSInfo;
2762  QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2763  if (!LhsTSInfo)
2764    LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2765
2766  TypeSourceInfo *RhsTSInfo;
2767  QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2768  if (!RhsTSInfo)
2769    RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2770
2771  return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2772}
2773
2774static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2775                                    QualType LhsT, QualType RhsT,
2776                                    SourceLocation KeyLoc) {
2777  assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
2778         "Cannot evaluate traits of dependent types");
2779
2780  switch(BTT) {
2781  case BTT_IsBaseOf: {
2782    // C++0x [meta.rel]p2
2783    // Base is a base class of Derived without regard to cv-qualifiers or
2784    // Base and Derived are not unions and name the same class type without
2785    // regard to cv-qualifiers.
2786
2787    const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2788    if (!lhsRecord) return false;
2789
2790    const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2791    if (!rhsRecord) return false;
2792
2793    assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2794             == (lhsRecord == rhsRecord));
2795
2796    if (lhsRecord == rhsRecord)
2797      return !lhsRecord->getDecl()->isUnion();
2798
2799    // C++0x [meta.rel]p2:
2800    //   If Base and Derived are class types and are different types
2801    //   (ignoring possible cv-qualifiers) then Derived shall be a
2802    //   complete type.
2803    if (Self.RequireCompleteType(KeyLoc, RhsT,
2804                          diag::err_incomplete_type_used_in_type_trait_expr))
2805      return false;
2806
2807    return cast<CXXRecordDecl>(rhsRecord->getDecl())
2808      ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2809  }
2810  case BTT_IsSame:
2811    return Self.Context.hasSameType(LhsT, RhsT);
2812  case BTT_TypeCompatible:
2813    return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2814                                           RhsT.getUnqualifiedType());
2815  case BTT_IsConvertible:
2816  case BTT_IsConvertibleTo: {
2817    // C++0x [meta.rel]p4:
2818    //   Given the following function prototype:
2819    //
2820    //     template <class T>
2821    //       typename add_rvalue_reference<T>::type create();
2822    //
2823    //   the predicate condition for a template specialization
2824    //   is_convertible<From, To> shall be satisfied if and only if
2825    //   the return expression in the following code would be
2826    //   well-formed, including any implicit conversions to the return
2827    //   type of the function:
2828    //
2829    //     To test() {
2830    //       return create<From>();
2831    //     }
2832    //
2833    //   Access checking is performed as if in a context unrelated to To and
2834    //   From. Only the validity of the immediate context of the expression
2835    //   of the return-statement (including conversions to the return type)
2836    //   is considered.
2837    //
2838    // We model the initialization as a copy-initialization of a temporary
2839    // of the appropriate type, which for this expression is identical to the
2840    // return statement (since NRVO doesn't apply).
2841    if (LhsT->isObjectType() || LhsT->isFunctionType())
2842      LhsT = Self.Context.getRValueReferenceType(LhsT);
2843
2844    InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
2845    OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
2846                         Expr::getValueKindForType(LhsT));
2847    Expr *FromPtr = &From;
2848    InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2849                                                           SourceLocation()));
2850
2851    // Perform the initialization within a SFINAE trap at translation unit
2852    // scope.
2853    Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2854    Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
2855    InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2856    if (Init.getKind() == InitializationSequence::FailedSequence)
2857      return false;
2858
2859    ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2860    return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2861  }
2862  }
2863  llvm_unreachable("Unknown type trait or not implemented");
2864}
2865
2866ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2867                                      SourceLocation KWLoc,
2868                                      TypeSourceInfo *LhsTSInfo,
2869                                      TypeSourceInfo *RhsTSInfo,
2870                                      SourceLocation RParen) {
2871  QualType LhsT = LhsTSInfo->getType();
2872  QualType RhsT = RhsTSInfo->getType();
2873
2874  if (BTT == BTT_TypeCompatible) {
2875    if (getLangOptions().CPlusPlus) {
2876      Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2877        << SourceRange(KWLoc, RParen);
2878      return ExprError();
2879    }
2880  }
2881
2882  bool Value = false;
2883  if (!LhsT->isDependentType() && !RhsT->isDependentType())
2884    Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2885
2886  // Select trait result type.
2887  QualType ResultType;
2888  switch (BTT) {
2889  case BTT_IsBaseOf:       ResultType = Context.BoolTy; break;
2890  case BTT_IsConvertible:  ResultType = Context.BoolTy; break;
2891  case BTT_IsSame:         ResultType = Context.BoolTy; break;
2892  case BTT_TypeCompatible: ResultType = Context.IntTy; break;
2893  case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
2894  }
2895
2896  return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2897                                                 RhsTSInfo, Value, RParen,
2898                                                 ResultType));
2899}
2900
2901ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
2902                                     SourceLocation KWLoc,
2903                                     ParsedType Ty,
2904                                     Expr* DimExpr,
2905                                     SourceLocation RParen) {
2906  TypeSourceInfo *TSInfo;
2907  QualType T = GetTypeFromParser(Ty, &TSInfo);
2908  if (!TSInfo)
2909    TSInfo = Context.getTrivialTypeSourceInfo(T);
2910
2911  return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
2912}
2913
2914static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
2915                                           QualType T, Expr *DimExpr,
2916                                           SourceLocation KeyLoc) {
2917  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
2918
2919  switch(ATT) {
2920  case ATT_ArrayRank:
2921    if (T->isArrayType()) {
2922      unsigned Dim = 0;
2923      while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
2924        ++Dim;
2925        T = AT->getElementType();
2926      }
2927      return Dim;
2928    }
2929    return 0;
2930
2931  case ATT_ArrayExtent: {
2932    llvm::APSInt Value;
2933    uint64_t Dim;
2934    if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
2935      if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
2936        Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
2937          DimExpr->getSourceRange();
2938        return false;
2939      }
2940      Dim = Value.getLimitedValue();
2941    } else {
2942      Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
2943        DimExpr->getSourceRange();
2944      return false;
2945    }
2946
2947    if (T->isArrayType()) {
2948      unsigned D = 0;
2949      bool Matched = false;
2950      while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
2951        if (Dim == D) {
2952          Matched = true;
2953          break;
2954        }
2955        ++D;
2956        T = AT->getElementType();
2957      }
2958
2959      if (Matched && T->isArrayType()) {
2960        if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
2961          return CAT->getSize().getLimitedValue();
2962      }
2963    }
2964    return 0;
2965  }
2966  }
2967  llvm_unreachable("Unknown type trait or not implemented");
2968}
2969
2970ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
2971                                     SourceLocation KWLoc,
2972                                     TypeSourceInfo *TSInfo,
2973                                     Expr* DimExpr,
2974                                     SourceLocation RParen) {
2975  QualType T = TSInfo->getType();
2976
2977  // FIXME: This should likely be tracked as an APInt to remove any host
2978  // assumptions about the width of size_t on the target.
2979  uint64_t Value = 0;
2980  if (!T->isDependentType())
2981    Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
2982
2983  // While the specification for these traits from the Embarcadero C++
2984  // compiler's documentation says the return type is 'unsigned int', Clang
2985  // returns 'size_t'. On Windows, the primary platform for the Embarcadero
2986  // compiler, there is no difference. On several other platforms this is an
2987  // important distinction.
2988  return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
2989                                                DimExpr, RParen,
2990                                                Context.getSizeType()));
2991}
2992
2993ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
2994                                      SourceLocation KWLoc,
2995                                      Expr *Queried,
2996                                      SourceLocation RParen) {
2997  // If error parsing the expression, ignore.
2998  if (!Queried)
2999    return ExprError();
3000
3001  ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
3002
3003  return move(Result);
3004}
3005
3006static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3007  switch (ET) {
3008  case ET_IsLValueExpr: return E->isLValue();
3009  case ET_IsRValueExpr: return E->isRValue();
3010  }
3011  llvm_unreachable("Expression trait not covered by switch");
3012}
3013
3014ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
3015                                      SourceLocation KWLoc,
3016                                      Expr *Queried,
3017                                      SourceLocation RParen) {
3018  if (Queried->isTypeDependent()) {
3019    // Delay type-checking for type-dependent expressions.
3020  } else if (Queried->getType()->isPlaceholderType()) {
3021    ExprResult PE = CheckPlaceholderExpr(Queried);
3022    if (PE.isInvalid()) return ExprError();
3023    return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3024  }
3025
3026  bool Value = EvaluateExpressionTrait(ET, Queried);
3027
3028  return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3029                                                 RParen, Context.BoolTy));
3030}
3031
3032QualType Sema::CheckPointerToMemberOperands(ExprResult &lex, ExprResult &rex,
3033                                            ExprValueKind &VK,
3034                                            SourceLocation Loc,
3035                                            bool isIndirect) {
3036  const char *OpSpelling = isIndirect ? "->*" : ".*";
3037  // C++ 5.5p2
3038  //   The binary operator .* [p3: ->*] binds its second operand, which shall
3039  //   be of type "pointer to member of T" (where T is a completely-defined
3040  //   class type) [...]
3041  QualType RType = rex.get()->getType();
3042  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
3043  if (!MemPtr) {
3044    Diag(Loc, diag::err_bad_memptr_rhs)
3045      << OpSpelling << RType << rex.get()->getSourceRange();
3046    return QualType();
3047  }
3048
3049  QualType Class(MemPtr->getClass(), 0);
3050
3051  // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3052  // member pointer points must be completely-defined. However, there is no
3053  // reason for this semantic distinction, and the rule is not enforced by
3054  // other compilers. Therefore, we do not check this property, as it is
3055  // likely to be considered a defect.
3056
3057  // C++ 5.5p2
3058  //   [...] to its first operand, which shall be of class T or of a class of
3059  //   which T is an unambiguous and accessible base class. [p3: a pointer to
3060  //   such a class]
3061  QualType LType = lex.get()->getType();
3062  if (isIndirect) {
3063    if (const PointerType *Ptr = LType->getAs<PointerType>())
3064      LType = Ptr->getPointeeType();
3065    else {
3066      Diag(Loc, diag::err_bad_memptr_lhs)
3067        << OpSpelling << 1 << LType
3068        << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
3069      return QualType();
3070    }
3071  }
3072
3073  if (!Context.hasSameUnqualifiedType(Class, LType)) {
3074    // If we want to check the hierarchy, we need a complete type.
3075    if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
3076        << OpSpelling << (int)isIndirect)) {
3077      return QualType();
3078    }
3079    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3080                       /*DetectVirtual=*/false);
3081    // FIXME: Would it be useful to print full ambiguity paths, or is that
3082    // overkill?
3083    if (!IsDerivedFrom(LType, Class, Paths) ||
3084        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3085      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
3086        << (int)isIndirect << lex.get()->getType();
3087      return QualType();
3088    }
3089    // Cast LHS to type of use.
3090    QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
3091    ExprValueKind VK =
3092        isIndirect ? VK_RValue : CastCategory(lex.get());
3093
3094    CXXCastPath BasePath;
3095    BuildBasePathArray(Paths, BasePath);
3096    lex = ImpCastExprToType(lex.take(), UseType, CK_DerivedToBase, VK, &BasePath);
3097  }
3098
3099  if (isa<CXXScalarValueInitExpr>(rex.get()->IgnoreParens())) {
3100    // Diagnose use of pointer-to-member type which when used as
3101    // the functional cast in a pointer-to-member expression.
3102    Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3103     return QualType();
3104  }
3105
3106  // C++ 5.5p2
3107  //   The result is an object or a function of the type specified by the
3108  //   second operand.
3109  // The cv qualifiers are the union of those in the pointer and the left side,
3110  // in accordance with 5.5p5 and 5.2.5.
3111  QualType Result = MemPtr->getPointeeType();
3112  Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
3113
3114  // C++0x [expr.mptr.oper]p6:
3115  //   In a .* expression whose object expression is an rvalue, the program is
3116  //   ill-formed if the second operand is a pointer to member function with
3117  //   ref-qualifier &. In a ->* expression or in a .* expression whose object
3118  //   expression is an lvalue, the program is ill-formed if the second operand
3119  //   is a pointer to member function with ref-qualifier &&.
3120  if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3121    switch (Proto->getRefQualifier()) {
3122    case RQ_None:
3123      // Do nothing
3124      break;
3125
3126    case RQ_LValue:
3127      if (!isIndirect && !lex.get()->Classify(Context).isLValue())
3128        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
3129          << RType << 1 << lex.get()->getSourceRange();
3130      break;
3131
3132    case RQ_RValue:
3133      if (isIndirect || !lex.get()->Classify(Context).isRValue())
3134        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
3135          << RType << 0 << lex.get()->getSourceRange();
3136      break;
3137    }
3138  }
3139
3140  // C++ [expr.mptr.oper]p6:
3141  //   The result of a .* expression whose second operand is a pointer
3142  //   to a data member is of the same value category as its
3143  //   first operand. The result of a .* expression whose second
3144  //   operand is a pointer to a member function is a prvalue. The
3145  //   result of an ->* expression is an lvalue if its second operand
3146  //   is a pointer to data member and a prvalue otherwise.
3147  if (Result->isFunctionType()) {
3148    VK = VK_RValue;
3149    return Context.BoundMemberTy;
3150  } else if (isIndirect) {
3151    VK = VK_LValue;
3152  } else {
3153    VK = lex.get()->getValueKind();
3154  }
3155
3156  return Result;
3157}
3158
3159/// \brief Try to convert a type to another according to C++0x 5.16p3.
3160///
3161/// This is part of the parameter validation for the ? operator. If either
3162/// value operand is a class type, the two operands are attempted to be
3163/// converted to each other. This function does the conversion in one direction.
3164/// It returns true if the program is ill-formed and has already been diagnosed
3165/// as such.
3166static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3167                                SourceLocation QuestionLoc,
3168                                bool &HaveConversion,
3169                                QualType &ToType) {
3170  HaveConversion = false;
3171  ToType = To->getType();
3172
3173  InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
3174                                                           SourceLocation());
3175  // C++0x 5.16p3
3176  //   The process for determining whether an operand expression E1 of type T1
3177  //   can be converted to match an operand expression E2 of type T2 is defined
3178  //   as follows:
3179  //   -- If E2 is an lvalue:
3180  bool ToIsLvalue = To->isLValue();
3181  if (ToIsLvalue) {
3182    //   E1 can be converted to match E2 if E1 can be implicitly converted to
3183    //   type "lvalue reference to T2", subject to the constraint that in the
3184    //   conversion the reference must bind directly to E1.
3185    QualType T = Self.Context.getLValueReferenceType(ToType);
3186    InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
3187
3188    InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3189    if (InitSeq.isDirectReferenceBinding()) {
3190      ToType = T;
3191      HaveConversion = true;
3192      return false;
3193    }
3194
3195    if (InitSeq.isAmbiguous())
3196      return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3197  }
3198
3199  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
3200  //      -- if E1 and E2 have class type, and the underlying class types are
3201  //         the same or one is a base class of the other:
3202  QualType FTy = From->getType();
3203  QualType TTy = To->getType();
3204  const RecordType *FRec = FTy->getAs<RecordType>();
3205  const RecordType *TRec = TTy->getAs<RecordType>();
3206  bool FDerivedFromT = FRec && TRec && FRec != TRec &&
3207                       Self.IsDerivedFrom(FTy, TTy);
3208  if (FRec && TRec &&
3209      (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
3210    //         E1 can be converted to match E2 if the class of T2 is the
3211    //         same type as, or a base class of, the class of T1, and
3212    //         [cv2 > cv1].
3213    if (FRec == TRec || FDerivedFromT) {
3214      if (TTy.isAtLeastAsQualifiedAs(FTy)) {
3215        InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3216        InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3217        if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
3218          HaveConversion = true;
3219          return false;
3220        }
3221
3222        if (InitSeq.isAmbiguous())
3223          return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3224      }
3225    }
3226
3227    return false;
3228  }
3229
3230  //     -- Otherwise: E1 can be converted to match E2 if E1 can be
3231  //        implicitly converted to the type that expression E2 would have
3232  //        if E2 were converted to an rvalue (or the type it has, if E2 is
3233  //        an rvalue).
3234  //
3235  // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3236  // to the array-to-pointer or function-to-pointer conversions.
3237  if (!TTy->getAs<TagType>())
3238    TTy = TTy.getUnqualifiedType();
3239
3240  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3241  InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3242  HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
3243  ToType = TTy;
3244  if (InitSeq.isAmbiguous())
3245    return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3246
3247  return false;
3248}
3249
3250/// \brief Try to find a common type for two according to C++0x 5.16p5.
3251///
3252/// This is part of the parameter validation for the ? operator. If either
3253/// value operand is a class type, overload resolution is used to find a
3254/// conversion to a common type.
3255static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
3256                                    SourceLocation QuestionLoc) {
3257  Expr *Args[2] = { LHS.get(), RHS.get() };
3258  OverloadCandidateSet CandidateSet(QuestionLoc);
3259  Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3260                                    CandidateSet);
3261
3262  OverloadCandidateSet::iterator Best;
3263  switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
3264    case OR_Success: {
3265      // We found a match. Perform the conversions on the arguments and move on.
3266      ExprResult LHSRes =
3267        Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3268                                       Best->Conversions[0], Sema::AA_Converting);
3269      if (LHSRes.isInvalid())
3270        break;
3271      LHS = move(LHSRes);
3272
3273      ExprResult RHSRes =
3274        Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3275                                       Best->Conversions[1], Sema::AA_Converting);
3276      if (RHSRes.isInvalid())
3277        break;
3278      RHS = move(RHSRes);
3279      if (Best->Function)
3280        Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
3281      return false;
3282    }
3283
3284    case OR_No_Viable_Function:
3285
3286      // Emit a better diagnostic if one of the expressions is a null pointer
3287      // constant and the other is a pointer type. In this case, the user most
3288      // likely forgot to take the address of the other expression.
3289      if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
3290        return true;
3291
3292      Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3293        << LHS.get()->getType() << RHS.get()->getType()
3294        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3295      return true;
3296
3297    case OR_Ambiguous:
3298      Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
3299        << LHS.get()->getType() << RHS.get()->getType()
3300        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3301      // FIXME: Print the possible common types by printing the return types of
3302      // the viable candidates.
3303      break;
3304
3305    case OR_Deleted:
3306      assert(false && "Conditional operator has only built-in overloads");
3307      break;
3308  }
3309  return true;
3310}
3311
3312/// \brief Perform an "extended" implicit conversion as returned by
3313/// TryClassUnification.
3314static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
3315  InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
3316  InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
3317                                                           SourceLocation());
3318  Expr *Arg = E.take();
3319  InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3320  ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
3321  if (Result.isInvalid())
3322    return true;
3323
3324  E = Result;
3325  return false;
3326}
3327
3328/// \brief Check the operands of ?: under C++ semantics.
3329///
3330/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3331/// extension. In this case, LHS == Cond. (But they're not aliases.)
3332QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
3333                                           ExprValueKind &VK, ExprObjectKind &OK,
3334                                           SourceLocation QuestionLoc) {
3335  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3336  // interface pointers.
3337
3338  // C++0x 5.16p1
3339  //   The first expression is contextually converted to bool.
3340  if (!Cond.get()->isTypeDependent()) {
3341    ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3342    if (CondRes.isInvalid())
3343      return QualType();
3344    Cond = move(CondRes);
3345  }
3346
3347  // Assume r-value.
3348  VK = VK_RValue;
3349  OK = OK_Ordinary;
3350
3351  // Either of the arguments dependent?
3352  if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
3353    return Context.DependentTy;
3354
3355  // C++0x 5.16p2
3356  //   If either the second or the third operand has type (cv) void, ...
3357  QualType LTy = LHS.get()->getType();
3358  QualType RTy = RHS.get()->getType();
3359  bool LVoid = LTy->isVoidType();
3360  bool RVoid = RTy->isVoidType();
3361  if (LVoid || RVoid) {
3362    //   ... then the [l2r] conversions are performed on the second and third
3363    //   operands ...
3364    LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3365    RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3366    if (LHS.isInvalid() || RHS.isInvalid())
3367      return QualType();
3368    LTy = LHS.get()->getType();
3369    RTy = RHS.get()->getType();
3370
3371    //   ... and one of the following shall hold:
3372    //   -- The second or the third operand (but not both) is a throw-
3373    //      expression; the result is of the type of the other and is an rvalue.
3374    bool LThrow = isa<CXXThrowExpr>(LHS.get());
3375    bool RThrow = isa<CXXThrowExpr>(RHS.get());
3376    if (LThrow && !RThrow)
3377      return RTy;
3378    if (RThrow && !LThrow)
3379      return LTy;
3380
3381    //   -- Both the second and third operands have type void; the result is of
3382    //      type void and is an rvalue.
3383    if (LVoid && RVoid)
3384      return Context.VoidTy;
3385
3386    // Neither holds, error.
3387    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3388      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
3389      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3390    return QualType();
3391  }
3392
3393  // Neither is void.
3394
3395  // C++0x 5.16p3
3396  //   Otherwise, if the second and third operand have different types, and
3397  //   either has (cv) class type, and attempt is made to convert each of those
3398  //   operands to the other.
3399  if (!Context.hasSameType(LTy, RTy) &&
3400      (LTy->isRecordType() || RTy->isRecordType())) {
3401    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3402    // These return true if a single direction is already ambiguous.
3403    QualType L2RType, R2LType;
3404    bool HaveL2R, HaveR2L;
3405    if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
3406      return QualType();
3407    if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
3408      return QualType();
3409
3410    //   If both can be converted, [...] the program is ill-formed.
3411    if (HaveL2R && HaveR2L) {
3412      Diag(QuestionLoc, diag::err_conditional_ambiguous)
3413        << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3414      return QualType();
3415    }
3416
3417    //   If exactly one conversion is possible, that conversion is applied to
3418    //   the chosen operand and the converted operands are used in place of the
3419    //   original operands for the remainder of this section.
3420    if (HaveL2R) {
3421      if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
3422        return QualType();
3423      LTy = LHS.get()->getType();
3424    } else if (HaveR2L) {
3425      if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
3426        return QualType();
3427      RTy = RHS.get()->getType();
3428    }
3429  }
3430
3431  // C++0x 5.16p4
3432  //   If the second and third operands are glvalues of the same value
3433  //   category and have the same type, the result is of that type and
3434  //   value category and it is a bit-field if the second or the third
3435  //   operand is a bit-field, or if both are bit-fields.
3436  // We only extend this to bitfields, not to the crazy other kinds of
3437  // l-values.
3438  bool Same = Context.hasSameType(LTy, RTy);
3439  if (Same &&
3440      LHS.get()->isGLValue() &&
3441      LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3442      LHS.get()->isOrdinaryOrBitFieldObject() &&
3443      RHS.get()->isOrdinaryOrBitFieldObject()) {
3444    VK = LHS.get()->getValueKind();
3445    if (LHS.get()->getObjectKind() == OK_BitField ||
3446        RHS.get()->getObjectKind() == OK_BitField)
3447      OK = OK_BitField;
3448    return LTy;
3449  }
3450
3451  // C++0x 5.16p5
3452  //   Otherwise, the result is an rvalue. If the second and third operands
3453  //   do not have the same type, and either has (cv) class type, ...
3454  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3455    //   ... overload resolution is used to determine the conversions (if any)
3456    //   to be applied to the operands. If the overload resolution fails, the
3457    //   program is ill-formed.
3458    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3459      return QualType();
3460  }
3461
3462  // C++0x 5.16p6
3463  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3464  //   conversions are performed on the second and third operands.
3465  LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3466  RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3467  if (LHS.isInvalid() || RHS.isInvalid())
3468    return QualType();
3469  LTy = LHS.get()->getType();
3470  RTy = RHS.get()->getType();
3471
3472  //   After those conversions, one of the following shall hold:
3473  //   -- The second and third operands have the same type; the result
3474  //      is of that type. If the operands have class type, the result
3475  //      is a prvalue temporary of the result type, which is
3476  //      copy-initialized from either the second operand or the third
3477  //      operand depending on the value of the first operand.
3478  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3479    if (LTy->isRecordType()) {
3480      // The operands have class type. Make a temporary copy.
3481      InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
3482      ExprResult LHSCopy = PerformCopyInitialization(Entity,
3483                                                     SourceLocation(),
3484                                                     LHS);
3485      if (LHSCopy.isInvalid())
3486        return QualType();
3487
3488      ExprResult RHSCopy = PerformCopyInitialization(Entity,
3489                                                     SourceLocation(),
3490                                                     RHS);
3491      if (RHSCopy.isInvalid())
3492        return QualType();
3493
3494      LHS = LHSCopy;
3495      RHS = RHSCopy;
3496    }
3497
3498    return LTy;
3499  }
3500
3501  // Extension: conditional operator involving vector types.
3502  if (LTy->isVectorType() || RTy->isVectorType())
3503    return CheckVectorOperands(QuestionLoc, LHS, RHS);
3504
3505  //   -- The second and third operands have arithmetic or enumeration type;
3506  //      the usual arithmetic conversions are performed to bring them to a
3507  //      common type, and the result is of that type.
3508  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3509    UsualArithmeticConversions(LHS, RHS);
3510    if (LHS.isInvalid() || RHS.isInvalid())
3511      return QualType();
3512    return LHS.get()->getType();
3513  }
3514
3515  //   -- The second and third operands have pointer type, or one has pointer
3516  //      type and the other is a null pointer constant; pointer conversions
3517  //      and qualification conversions are performed to bring them to their
3518  //      composite pointer type. The result is of the composite pointer type.
3519  //   -- The second and third operands have pointer to member type, or one has
3520  //      pointer to member type and the other is a null pointer constant;
3521  //      pointer to member conversions and qualification conversions are
3522  //      performed to bring them to a common type, whose cv-qualification
3523  //      shall match the cv-qualification of either the second or the third
3524  //      operand. The result is of the common type.
3525  bool NonStandardCompositeType = false;
3526  QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
3527                              isSFINAEContext()? 0 : &NonStandardCompositeType);
3528  if (!Composite.isNull()) {
3529    if (NonStandardCompositeType)
3530      Diag(QuestionLoc,
3531           diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3532        << LTy << RTy << Composite
3533        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3534
3535    return Composite;
3536  }
3537
3538  // Similarly, attempt to find composite type of two objective-c pointers.
3539  Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3540  if (!Composite.isNull())
3541    return Composite;
3542
3543  // Check if we are using a null with a non-pointer type.
3544  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
3545    return QualType();
3546
3547  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3548    << LHS.get()->getType() << RHS.get()->getType()
3549    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3550  return QualType();
3551}
3552
3553/// \brief Find a merged pointer type and convert the two expressions to it.
3554///
3555/// This finds the composite pointer type (or member pointer type) for @p E1
3556/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3557/// type and returns it.
3558/// It does not emit diagnostics.
3559///
3560/// \param Loc The location of the operator requiring these two expressions to
3561/// be converted to the composite pointer type.
3562///
3563/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3564/// a non-standard (but still sane) composite type to which both expressions
3565/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3566/// will be set true.
3567QualType Sema::FindCompositePointerType(SourceLocation Loc,
3568                                        Expr *&E1, Expr *&E2,
3569                                        bool *NonStandardCompositeType) {
3570  if (NonStandardCompositeType)
3571    *NonStandardCompositeType = false;
3572
3573  assert(getLangOptions().CPlusPlus && "This function assumes C++");
3574  QualType T1 = E1->getType(), T2 = E2->getType();
3575
3576  if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3577      !T2->isAnyPointerType() && !T2->isMemberPointerType())
3578   return QualType();
3579
3580  // C++0x 5.9p2
3581  //   Pointer conversions and qualification conversions are performed on
3582  //   pointer operands to bring them to their composite pointer type. If
3583  //   one operand is a null pointer constant, the composite pointer type is
3584  //   the type of the other operand.
3585  if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3586    if (T2->isMemberPointerType())
3587      E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
3588    else
3589      E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
3590    return T2;
3591  }
3592  if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3593    if (T1->isMemberPointerType())
3594      E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
3595    else
3596      E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
3597    return T1;
3598  }
3599
3600  // Now both have to be pointers or member pointers.
3601  if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3602      (!T2->isPointerType() && !T2->isMemberPointerType()))
3603    return QualType();
3604
3605  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
3606  //   the other has type "pointer to cv2 T" and the composite pointer type is
3607  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3608  //   Otherwise, the composite pointer type is a pointer type similar to the
3609  //   type of one of the operands, with a cv-qualification signature that is
3610  //   the union of the cv-qualification signatures of the operand types.
3611  // In practice, the first part here is redundant; it's subsumed by the second.
3612  // What we do here is, we build the two possible composite types, and try the
3613  // conversions in both directions. If only one works, or if the two composite
3614  // types are the same, we have succeeded.
3615  // FIXME: extended qualifiers?
3616  typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3617  QualifierVector QualifierUnion;
3618  typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3619      ContainingClassVector;
3620  ContainingClassVector MemberOfClass;
3621  QualType Composite1 = Context.getCanonicalType(T1),
3622           Composite2 = Context.getCanonicalType(T2);
3623  unsigned NeedConstBefore = 0;
3624  do {
3625    const PointerType *Ptr1, *Ptr2;
3626    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3627        (Ptr2 = Composite2->getAs<PointerType>())) {
3628      Composite1 = Ptr1->getPointeeType();
3629      Composite2 = Ptr2->getPointeeType();
3630
3631      // If we're allowed to create a non-standard composite type, keep track
3632      // of where we need to fill in additional 'const' qualifiers.
3633      if (NonStandardCompositeType &&
3634          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3635        NeedConstBefore = QualifierUnion.size();
3636
3637      QualifierUnion.push_back(
3638                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3639      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3640      continue;
3641    }
3642
3643    const MemberPointerType *MemPtr1, *MemPtr2;
3644    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3645        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3646      Composite1 = MemPtr1->getPointeeType();
3647      Composite2 = MemPtr2->getPointeeType();
3648
3649      // If we're allowed to create a non-standard composite type, keep track
3650      // of where we need to fill in additional 'const' qualifiers.
3651      if (NonStandardCompositeType &&
3652          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3653        NeedConstBefore = QualifierUnion.size();
3654
3655      QualifierUnion.push_back(
3656                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3657      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3658                                             MemPtr2->getClass()));
3659      continue;
3660    }
3661
3662    // FIXME: block pointer types?
3663
3664    // Cannot unwrap any more types.
3665    break;
3666  } while (true);
3667
3668  if (NeedConstBefore && NonStandardCompositeType) {
3669    // Extension: Add 'const' to qualifiers that come before the first qualifier
3670    // mismatch, so that our (non-standard!) composite type meets the
3671    // requirements of C++ [conv.qual]p4 bullet 3.
3672    for (unsigned I = 0; I != NeedConstBefore; ++I) {
3673      if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3674        QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3675        *NonStandardCompositeType = true;
3676      }
3677    }
3678  }
3679
3680  // Rewrap the composites as pointers or member pointers with the union CVRs.
3681  ContainingClassVector::reverse_iterator MOC
3682    = MemberOfClass.rbegin();
3683  for (QualifierVector::reverse_iterator
3684         I = QualifierUnion.rbegin(),
3685         E = QualifierUnion.rend();
3686       I != E; (void)++I, ++MOC) {
3687    Qualifiers Quals = Qualifiers::fromCVRMask(*I);
3688    if (MOC->first && MOC->second) {
3689      // Rebuild member pointer type
3690      Composite1 = Context.getMemberPointerType(
3691                                    Context.getQualifiedType(Composite1, Quals),
3692                                    MOC->first);
3693      Composite2 = Context.getMemberPointerType(
3694                                    Context.getQualifiedType(Composite2, Quals),
3695                                    MOC->second);
3696    } else {
3697      // Rebuild pointer type
3698      Composite1
3699        = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3700      Composite2
3701        = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
3702    }
3703  }
3704
3705  // Try to convert to the first composite pointer type.
3706  InitializedEntity Entity1
3707    = InitializedEntity::InitializeTemporary(Composite1);
3708  InitializationKind Kind
3709    = InitializationKind::CreateCopy(Loc, SourceLocation());
3710  InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3711  InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
3712
3713  if (E1ToC1 && E2ToC1) {
3714    // Conversion to Composite1 is viable.
3715    if (!Context.hasSameType(Composite1, Composite2)) {
3716      // Composite2 is a different type from Composite1. Check whether
3717      // Composite2 is also viable.
3718      InitializedEntity Entity2
3719        = InitializedEntity::InitializeTemporary(Composite2);
3720      InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3721      InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3722      if (E1ToC2 && E2ToC2) {
3723        // Both Composite1 and Composite2 are viable and are different;
3724        // this is an ambiguity.
3725        return QualType();
3726      }
3727    }
3728
3729    // Convert E1 to Composite1
3730    ExprResult E1Result
3731      = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
3732    if (E1Result.isInvalid())
3733      return QualType();
3734    E1 = E1Result.takeAs<Expr>();
3735
3736    // Convert E2 to Composite1
3737    ExprResult E2Result
3738      = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
3739    if (E2Result.isInvalid())
3740      return QualType();
3741    E2 = E2Result.takeAs<Expr>();
3742
3743    return Composite1;
3744  }
3745
3746  // Check whether Composite2 is viable.
3747  InitializedEntity Entity2
3748    = InitializedEntity::InitializeTemporary(Composite2);
3749  InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3750  InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3751  if (!E1ToC2 || !E2ToC2)
3752    return QualType();
3753
3754  // Convert E1 to Composite2
3755  ExprResult E1Result
3756    = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
3757  if (E1Result.isInvalid())
3758    return QualType();
3759  E1 = E1Result.takeAs<Expr>();
3760
3761  // Convert E2 to Composite2
3762  ExprResult E2Result
3763    = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
3764  if (E2Result.isInvalid())
3765    return QualType();
3766  E2 = E2Result.takeAs<Expr>();
3767
3768  return Composite2;
3769}
3770
3771ExprResult Sema::MaybeBindToTemporary(Expr *E) {
3772  if (!E)
3773    return ExprError();
3774
3775  if (!Context.getLangOptions().CPlusPlus)
3776    return Owned(E);
3777
3778  assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3779
3780  const RecordType *RT = E->getType()->getAs<RecordType>();
3781  if (!RT)
3782    return Owned(E);
3783
3784  // If the result is a glvalue, we shouldn't bind it.
3785  if (E->Classify(Context).isGLValue())
3786    return Owned(E);
3787
3788  // That should be enough to guarantee that this type is complete.
3789  // If it has a trivial destructor, we can avoid the extra copy.
3790  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3791  if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
3792    return Owned(E);
3793
3794  CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
3795  ExprTemporaries.push_back(Temp);
3796  if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
3797    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
3798    CheckDestructorAccess(E->getExprLoc(), Destructor,
3799                          PDiag(diag::err_access_dtor_temp)
3800                            << E->getType());
3801  }
3802  // FIXME: Add the temporary to the temporaries vector.
3803  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3804}
3805
3806Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
3807  assert(SubExpr && "sub expression can't be null!");
3808
3809  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3810  assert(ExprTemporaries.size() >= FirstTemporary);
3811  if (ExprTemporaries.size() == FirstTemporary)
3812    return SubExpr;
3813
3814  Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3815                                     &ExprTemporaries[FirstTemporary],
3816                                     ExprTemporaries.size() - FirstTemporary);
3817  ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3818                        ExprTemporaries.end());
3819
3820  return E;
3821}
3822
3823ExprResult
3824Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
3825  if (SubExpr.isInvalid())
3826    return ExprError();
3827
3828  return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
3829}
3830
3831Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
3832  assert(SubStmt && "sub statement can't be null!");
3833
3834  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3835  assert(ExprTemporaries.size() >= FirstTemporary);
3836  if (ExprTemporaries.size() == FirstTemporary)
3837    return SubStmt;
3838
3839  // FIXME: In order to attach the temporaries, wrap the statement into
3840  // a StmtExpr; currently this is only used for asm statements.
3841  // This is hacky, either create a new CXXStmtWithTemporaries statement or
3842  // a new AsmStmtWithTemporaries.
3843  CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3844                                                      SourceLocation(),
3845                                                      SourceLocation());
3846  Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3847                                   SourceLocation());
3848  return MaybeCreateExprWithCleanups(E);
3849}
3850
3851ExprResult
3852Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
3853                                   tok::TokenKind OpKind, ParsedType &ObjectType,
3854                                   bool &MayBePseudoDestructor) {
3855  // Since this might be a postfix expression, get rid of ParenListExprs.
3856  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3857  if (Result.isInvalid()) return ExprError();
3858  Base = Result.get();
3859
3860  QualType BaseType = Base->getType();
3861  MayBePseudoDestructor = false;
3862  if (BaseType->isDependentType()) {
3863    // If we have a pointer to a dependent type and are using the -> operator,
3864    // the object type is the type that the pointer points to. We might still
3865    // have enough information about that type to do something useful.
3866    if (OpKind == tok::arrow)
3867      if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3868        BaseType = Ptr->getPointeeType();
3869
3870    ObjectType = ParsedType::make(BaseType);
3871    MayBePseudoDestructor = true;
3872    return Owned(Base);
3873  }
3874
3875  // C++ [over.match.oper]p8:
3876  //   [...] When operator->returns, the operator-> is applied  to the value
3877  //   returned, with the original second operand.
3878  if (OpKind == tok::arrow) {
3879    // The set of types we've considered so far.
3880    llvm::SmallPtrSet<CanQualType,8> CTypes;
3881    llvm::SmallVector<SourceLocation, 8> Locations;
3882    CTypes.insert(Context.getCanonicalType(BaseType));
3883
3884    while (BaseType->isRecordType()) {
3885      Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3886      if (Result.isInvalid())
3887        return ExprError();
3888      Base = Result.get();
3889      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
3890        Locations.push_back(OpCall->getDirectCallee()->getLocation());
3891      BaseType = Base->getType();
3892      CanQualType CBaseType = Context.getCanonicalType(BaseType);
3893      if (!CTypes.insert(CBaseType)) {
3894        Diag(OpLoc, diag::err_operator_arrow_circular);
3895        for (unsigned i = 0; i < Locations.size(); i++)
3896          Diag(Locations[i], diag::note_declared_at);
3897        return ExprError();
3898      }
3899    }
3900
3901    if (BaseType->isPointerType())
3902      BaseType = BaseType->getPointeeType();
3903  }
3904
3905  // We could end up with various non-record types here, such as extended
3906  // vector types or Objective-C interfaces. Just return early and let
3907  // ActOnMemberReferenceExpr do the work.
3908  if (!BaseType->isRecordType()) {
3909    // C++ [basic.lookup.classref]p2:
3910    //   [...] If the type of the object expression is of pointer to scalar
3911    //   type, the unqualified-id is looked up in the context of the complete
3912    //   postfix-expression.
3913    //
3914    // This also indicates that we should be parsing a
3915    // pseudo-destructor-name.
3916    ObjectType = ParsedType();
3917    MayBePseudoDestructor = true;
3918    return Owned(Base);
3919  }
3920
3921  // The object type must be complete (or dependent).
3922  if (!BaseType->isDependentType() &&
3923      RequireCompleteType(OpLoc, BaseType,
3924                          PDiag(diag::err_incomplete_member_access)))
3925    return ExprError();
3926
3927  // C++ [basic.lookup.classref]p2:
3928  //   If the id-expression in a class member access (5.2.5) is an
3929  //   unqualified-id, and the type of the object expression is of a class
3930  //   type C (or of pointer to a class type C), the unqualified-id is looked
3931  //   up in the scope of class C. [...]
3932  ObjectType = ParsedType::make(BaseType);
3933  return move(Base);
3934}
3935
3936ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
3937                                                   Expr *MemExpr) {
3938  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
3939  Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3940    << isa<CXXPseudoDestructorExpr>(MemExpr)
3941    << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
3942
3943  return ActOnCallExpr(/*Scope*/ 0,
3944                       MemExpr,
3945                       /*LPLoc*/ ExpectedLParenLoc,
3946                       MultiExprArg(),
3947                       /*RPLoc*/ ExpectedLParenLoc);
3948}
3949
3950ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
3951                                           SourceLocation OpLoc,
3952                                           tok::TokenKind OpKind,
3953                                           const CXXScopeSpec &SS,
3954                                           TypeSourceInfo *ScopeTypeInfo,
3955                                           SourceLocation CCLoc,
3956                                           SourceLocation TildeLoc,
3957                                         PseudoDestructorTypeStorage Destructed,
3958                                           bool HasTrailingLParen) {
3959  TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
3960
3961  // C++ [expr.pseudo]p2:
3962  //   The left-hand side of the dot operator shall be of scalar type. The
3963  //   left-hand side of the arrow operator shall be of pointer to scalar type.
3964  //   This scalar type is the object type.
3965  QualType ObjectType = Base->getType();
3966  if (OpKind == tok::arrow) {
3967    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3968      ObjectType = Ptr->getPointeeType();
3969    } else if (!Base->isTypeDependent()) {
3970      // The user wrote "p->" when she probably meant "p."; fix it.
3971      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3972        << ObjectType << true
3973        << FixItHint::CreateReplacement(OpLoc, ".");
3974      if (isSFINAEContext())
3975        return ExprError();
3976
3977      OpKind = tok::period;
3978    }
3979  }
3980
3981  if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3982    Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
3983      << ObjectType << Base->getSourceRange();
3984    return ExprError();
3985  }
3986
3987  // C++ [expr.pseudo]p2:
3988  //   [...] The cv-unqualified versions of the object type and of the type
3989  //   designated by the pseudo-destructor-name shall be the same type.
3990  if (DestructedTypeInfo) {
3991    QualType DestructedType = DestructedTypeInfo->getType();
3992    SourceLocation DestructedTypeStart
3993      = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
3994    if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3995        !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3996      Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
3997        << ObjectType << DestructedType << Base->getSourceRange()
3998        << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
3999
4000      // Recover by setting the destructed type to the object type.
4001      DestructedType = ObjectType;
4002      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4003                                                           DestructedTypeStart);
4004      Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4005    }
4006  }
4007
4008  // C++ [expr.pseudo]p2:
4009  //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4010  //   form
4011  //
4012  //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
4013  //
4014  //   shall designate the same scalar type.
4015  if (ScopeTypeInfo) {
4016    QualType ScopeType = ScopeTypeInfo->getType();
4017    if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
4018        !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
4019
4020      Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
4021           diag::err_pseudo_dtor_type_mismatch)
4022        << ObjectType << ScopeType << Base->getSourceRange()
4023        << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
4024
4025      ScopeType = QualType();
4026      ScopeTypeInfo = 0;
4027    }
4028  }
4029
4030  Expr *Result
4031    = new (Context) CXXPseudoDestructorExpr(Context, Base,
4032                                            OpKind == tok::arrow, OpLoc,
4033                                            SS.getWithLocInContext(Context),
4034                                            ScopeTypeInfo,
4035                                            CCLoc,
4036                                            TildeLoc,
4037                                            Destructed);
4038
4039  if (HasTrailingLParen)
4040    return Owned(Result);
4041
4042  return DiagnoseDtorReference(Destructed.getLocation(), Result);
4043}
4044
4045ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4046                                           SourceLocation OpLoc,
4047                                           tok::TokenKind OpKind,
4048                                           CXXScopeSpec &SS,
4049                                           UnqualifiedId &FirstTypeName,
4050                                           SourceLocation CCLoc,
4051                                           SourceLocation TildeLoc,
4052                                           UnqualifiedId &SecondTypeName,
4053                                           bool HasTrailingLParen) {
4054  assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4055          FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4056         "Invalid first type name in pseudo-destructor");
4057  assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4058          SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4059         "Invalid second type name in pseudo-destructor");
4060
4061  // C++ [expr.pseudo]p2:
4062  //   The left-hand side of the dot operator shall be of scalar type. The
4063  //   left-hand side of the arrow operator shall be of pointer to scalar type.
4064  //   This scalar type is the object type.
4065  QualType ObjectType = Base->getType();
4066  if (OpKind == tok::arrow) {
4067    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4068      ObjectType = Ptr->getPointeeType();
4069    } else if (!ObjectType->isDependentType()) {
4070      // The user wrote "p->" when she probably meant "p."; fix it.
4071      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4072        << ObjectType << true
4073        << FixItHint::CreateReplacement(OpLoc, ".");
4074      if (isSFINAEContext())
4075        return ExprError();
4076
4077      OpKind = tok::period;
4078    }
4079  }
4080
4081  // Compute the object type that we should use for name lookup purposes. Only
4082  // record types and dependent types matter.
4083  ParsedType ObjectTypePtrForLookup;
4084  if (!SS.isSet()) {
4085    if (ObjectType->isRecordType())
4086      ObjectTypePtrForLookup = ParsedType::make(ObjectType);
4087    else if (ObjectType->isDependentType())
4088      ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
4089  }
4090
4091  // Convert the name of the type being destructed (following the ~) into a
4092  // type (with source-location information).
4093  QualType DestructedType;
4094  TypeSourceInfo *DestructedTypeInfo = 0;
4095  PseudoDestructorTypeStorage Destructed;
4096  if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
4097    ParsedType T = getTypeName(*SecondTypeName.Identifier,
4098                               SecondTypeName.StartLocation,
4099                               S, &SS, true, false, ObjectTypePtrForLookup);
4100    if (!T &&
4101        ((SS.isSet() && !computeDeclContext(SS, false)) ||
4102         (!SS.isSet() && ObjectType->isDependentType()))) {
4103      // The name of the type being destroyed is a dependent name, and we
4104      // couldn't find anything useful in scope. Just store the identifier and
4105      // it's location, and we'll perform (qualified) name lookup again at
4106      // template instantiation time.
4107      Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4108                                               SecondTypeName.StartLocation);
4109    } else if (!T) {
4110      Diag(SecondTypeName.StartLocation,
4111           diag::err_pseudo_dtor_destructor_non_type)
4112        << SecondTypeName.Identifier << ObjectType;
4113      if (isSFINAEContext())
4114        return ExprError();
4115
4116      // Recover by assuming we had the right type all along.
4117      DestructedType = ObjectType;
4118    } else
4119      DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
4120  } else {
4121    // Resolve the template-id to a type.
4122    TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
4123    ASTTemplateArgsPtr TemplateArgsPtr(*this,
4124                                       TemplateId->getTemplateArgs(),
4125                                       TemplateId->NumArgs);
4126    TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4127                                       TemplateId->Template,
4128                                       TemplateId->TemplateNameLoc,
4129                                       TemplateId->LAngleLoc,
4130                                       TemplateArgsPtr,
4131                                       TemplateId->RAngleLoc);
4132    if (T.isInvalid() || !T.get()) {
4133      // Recover by assuming we had the right type all along.
4134      DestructedType = ObjectType;
4135    } else
4136      DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
4137  }
4138
4139  // If we've performed some kind of recovery, (re-)build the type source
4140  // information.
4141  if (!DestructedType.isNull()) {
4142    if (!DestructedTypeInfo)
4143      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
4144                                                  SecondTypeName.StartLocation);
4145    Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4146  }
4147
4148  // Convert the name of the scope type (the type prior to '::') into a type.
4149  TypeSourceInfo *ScopeTypeInfo = 0;
4150  QualType ScopeType;
4151  if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4152      FirstTypeName.Identifier) {
4153    if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
4154      ParsedType T = getTypeName(*FirstTypeName.Identifier,
4155                                 FirstTypeName.StartLocation,
4156                                 S, &SS, true, false, ObjectTypePtrForLookup);
4157      if (!T) {
4158        Diag(FirstTypeName.StartLocation,
4159             diag::err_pseudo_dtor_destructor_non_type)
4160          << FirstTypeName.Identifier << ObjectType;
4161
4162        if (isSFINAEContext())
4163          return ExprError();
4164
4165        // Just drop this type. It's unnecessary anyway.
4166        ScopeType = QualType();
4167      } else
4168        ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
4169    } else {
4170      // Resolve the template-id to a type.
4171      TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
4172      ASTTemplateArgsPtr TemplateArgsPtr(*this,
4173                                         TemplateId->getTemplateArgs(),
4174                                         TemplateId->NumArgs);
4175      TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4176                                         TemplateId->Template,
4177                                         TemplateId->TemplateNameLoc,
4178                                         TemplateId->LAngleLoc,
4179                                         TemplateArgsPtr,
4180                                         TemplateId->RAngleLoc);
4181      if (T.isInvalid() || !T.get()) {
4182        // Recover by dropping this type.
4183        ScopeType = QualType();
4184      } else
4185        ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
4186    }
4187  }
4188
4189  if (!ScopeType.isNull() && !ScopeTypeInfo)
4190    ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4191                                                  FirstTypeName.StartLocation);
4192
4193
4194  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
4195                                   ScopeTypeInfo, CCLoc, TildeLoc,
4196                                   Destructed, HasTrailingLParen);
4197}
4198
4199ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
4200                                        CXXMethodDecl *Method) {
4201  ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4202                                          FoundDecl, Method);
4203  if (Exp.isInvalid())
4204    return true;
4205
4206  MemberExpr *ME =
4207      new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
4208                               SourceLocation(), Method->getType(),
4209                               VK_RValue, OK_Ordinary);
4210  QualType ResultType = Method->getResultType();
4211  ExprValueKind VK = Expr::getValueKindForType(ResultType);
4212  ResultType = ResultType.getNonLValueExprType(Context);
4213
4214  MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
4215  CXXMemberCallExpr *CE =
4216    new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
4217                                    Exp.get()->getLocEnd());
4218  return CE;
4219}
4220
4221ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4222                                      SourceLocation RParen) {
4223  return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4224                                             Operand->CanThrow(Context),
4225                                             KeyLoc, RParen));
4226}
4227
4228ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4229                                   Expr *Operand, SourceLocation RParen) {
4230  return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
4231}
4232
4233/// Perform the conversions required for an expression used in a
4234/// context that ignores the result.
4235ExprResult Sema::IgnoredValueConversions(Expr *E) {
4236  // C99 6.3.2.1:
4237  //   [Except in specific positions,] an lvalue that does not have
4238  //   array type is converted to the value stored in the
4239  //   designated object (and is no longer an lvalue).
4240  if (E->isRValue()) return Owned(E);
4241
4242  // We always want to do this on ObjC property references.
4243  if (E->getObjectKind() == OK_ObjCProperty) {
4244    ExprResult Res = ConvertPropertyForRValue(E);
4245    if (Res.isInvalid()) return Owned(E);
4246    E = Res.take();
4247    if (E->isRValue()) return Owned(E);
4248  }
4249
4250  // Otherwise, this rule does not apply in C++, at least not for the moment.
4251  if (getLangOptions().CPlusPlus) return Owned(E);
4252
4253  // GCC seems to also exclude expressions of incomplete enum type.
4254  if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4255    if (!T->getDecl()->isComplete()) {
4256      // FIXME: stupid workaround for a codegen bug!
4257      E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4258      return Owned(E);
4259    }
4260  }
4261
4262  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4263  if (Res.isInvalid())
4264    return Owned(E);
4265  E = Res.take();
4266
4267  if (!E->getType()->isVoidType())
4268    RequireCompleteType(E->getExprLoc(), E->getType(),
4269                        diag::err_incomplete_type);
4270  return Owned(E);
4271}
4272
4273ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4274  ExprResult FullExpr = Owned(FE);
4275
4276  if (!FullExpr.get())
4277    return ExprError();
4278
4279  if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
4280    return ExprError();
4281
4282  FullExpr = CheckPlaceholderExpr(FullExpr.take());
4283  if (FullExpr.isInvalid())
4284    return ExprError();
4285
4286  FullExpr = IgnoredValueConversions(FullExpr.take());
4287  if (FullExpr.isInvalid())
4288    return ExprError();
4289
4290  CheckImplicitConversions(FullExpr.get());
4291  return MaybeCreateExprWithCleanups(FullExpr);
4292}
4293
4294StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4295  if (!FullStmt) return StmtError();
4296
4297  return MaybeCreateStmtWithCleanups(FullStmt);
4298}
4299
4300bool Sema::CheckMicrosoftIfExistsSymbol(CXXScopeSpec &SS,
4301                                        UnqualifiedId &Name) {
4302  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4303  DeclarationName TargetName = TargetNameInfo.getName();
4304  if (!TargetName)
4305    return false;
4306
4307  // Do the redeclaration lookup in the current scope.
4308  LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
4309                 Sema::NotForRedeclaration);
4310  R.suppressDiagnostics();
4311  LookupParsedName(R, getCurScope(), &SS);
4312  return !R.empty();
4313}
4314