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