blob: 95dcbe9ad8d3426a1b3f11cb2d426764c86fb379 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
James Dennettef2b5b32012-06-15 22:23:43 +00009
10// \file
11// \brief Implements semantic analysis for C++ expressions.
Reid Spencer5f016e22007-07-11 17:01:13 +000012
John McCall2d887082010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
John McCall2a7fb272010-08-25 05:32:35 +000014#include "clang/Sema/DeclSpec.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall2a7fb272010-08-25 05:32:35 +000017#include "clang/Sema/ParsedTemplate.h"
John McCall469a1eb2011-02-02 13:00:07 +000018#include "clang/Sema/ScopeInfo.h"
Richard Smith7a614d82011-06-11 17:19:42 +000019#include "clang/Sema/Scope.h"
John McCall2a7fb272010-08-25 05:32:35 +000020#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000021#include "clang/AST/ASTContext.h"
Nick Lewyckyfca84b22012-01-24 21:15:41 +000022#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000024#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000025#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000027#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000030#include "clang/Lex/Preprocessor.h"
David Blaikie91ec7892011-12-16 16:03:09 +000031#include "TypeLocBuilder.h"
Sebastian Redlbd45d252012-02-16 12:59:47 +000032#include "llvm/ADT/APInt.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Chandler Carruth73e0a912011-05-01 07:23:17 +000034#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000036using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000037
John McCallb3d87482010-08-24 05:47:05 +000038ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000039 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000040 SourceLocation NameLoc,
41 Scope *S, CXXScopeSpec &SS,
42 ParsedType ObjectTypePtr,
43 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000044 // Determine where to perform name lookup.
45
46 // FIXME: This area of the standard is very messy, and the current
47 // wording is rather unclear about which scopes we search for the
48 // destructor name; see core issues 399 and 555. Issue 399 in
49 // particular shows where the current description of destructor name
50 // lookup is completely out of line with existing practice, e.g.,
51 // this appears to be ill-formed:
52 //
53 // namespace N {
54 // template <typename T> struct S {
55 // ~S();
56 // };
57 // }
58 //
59 // void f(N::S<int>* s) {
60 // s->N::S<int>::~S();
61 // }
62 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000063 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000064 // For this reason, we're currently only doing the C++03 version of this
65 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000066 QualType SearchType;
67 DeclContext *LookupCtx = 0;
68 bool isDependent = false;
69 bool LookInScope = false;
70
71 // If we have an object type, it's because we are in a
72 // pseudo-destructor-expression or a member access expression, and
73 // we know what type we're looking for.
74 if (ObjectTypePtr)
75 SearchType = GetTypeFromParser(ObjectTypePtr);
76
77 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000078 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000079
Douglas Gregor93649fd2010-02-23 00:15:22 +000080 bool AlreadySearched = false;
81 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000082 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000083 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000084 // the type-names are looked up as types in the scope designated by the
85 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000086 //
87 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000088 //
89 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000090 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000091 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000092 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000093 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000094 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000095 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000096 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000097 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000098 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +000099 // nested-name-specifier.
100 DeclContext *DC = computeDeclContext(SS, EnteringContext);
101 if (DC && DC->isFileContext()) {
102 AlreadySearched = true;
103 LookupCtx = DC;
104 isDependent = false;
105 } else if (DC && isa<CXXRecordDecl>(DC))
106 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000107
Sebastian Redlc0fee502010-07-07 23:17:38 +0000108 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000109 NestedNameSpecifier *Prefix = 0;
110 if (AlreadySearched) {
111 // Nothing left to do.
112 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
113 CXXScopeSpec PrefixSS;
Douglas Gregor7e384942011-02-25 16:07:42 +0000114 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000115 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
116 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000117 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000118 LookupCtx = computeDeclContext(SearchType);
119 isDependent = SearchType->isDependentType();
120 } else {
121 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000122 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000123 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000124
Douglas Gregoredc90502010-02-25 04:46:04 +0000125 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000126 } else if (ObjectTypePtr) {
127 // C++ [basic.lookup.classref]p3:
128 // If the unqualified-id is ~type-name, the type-name is looked up
129 // in the context of the entire postfix-expression. If the type T
130 // of the object expression is of a class type C, the type-name is
131 // also looked up in the scope of class C. At least one of the
132 // lookups shall find a name that refers to (possibly
133 // cv-qualified) T.
134 LookupCtx = computeDeclContext(SearchType);
135 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000136 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000137 "Caller should have completed object type");
138
139 LookInScope = true;
140 } else {
141 // Perform lookup into the current scope (only).
142 LookInScope = true;
143 }
144
Douglas Gregor7ec18732011-03-04 22:32:08 +0000145 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregor124b8782010-02-16 19:09:40 +0000146 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
147 for (unsigned Step = 0; Step != 2; ++Step) {
148 // Look for the name first in the computed lookup context (if we
Douglas Gregor7ec18732011-03-04 22:32:08 +0000149 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregor124b8782010-02-16 19:09:40 +0000150 // we're allowed to look there).
151 Found.clear();
152 if (Step == 0 && LookupCtx)
153 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000154 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000155 LookupName(Found, S);
156 else
157 continue;
158
159 // FIXME: Should we be suppressing ambiguities here?
160 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000161 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000162
163 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
164 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000165
166 if (SearchType.isNull() || SearchType->isDependentType() ||
167 Context.hasSameUnqualifiedType(T, SearchType)) {
168 // We found our type!
169
John McCallb3d87482010-08-24 05:47:05 +0000170 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000171 }
John Wiegley36784e72011-03-08 08:13:22 +0000172
Douglas Gregor7ec18732011-03-04 22:32:08 +0000173 if (!SearchType.isNull())
174 NonMatchingTypeDecl = Type;
Douglas Gregor124b8782010-02-16 19:09:40 +0000175 }
176
177 // If the name that we found is a class template name, and it is
178 // the same name as the template name in the last part of the
179 // nested-name-specifier (if present) or the object type, then
180 // this is the destructor for that class.
181 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000182 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000183 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
184 QualType MemberOfType;
185 if (SS.isSet()) {
186 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
187 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000188 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
189 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000190 }
191 }
192 if (MemberOfType.isNull())
193 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000194
Douglas Gregor124b8782010-02-16 19:09:40 +0000195 if (MemberOfType.isNull())
196 continue;
197
198 // We're referring into a class template specialization. If the
199 // class template we found is the same as the template being
200 // specialized, we found what we are looking for.
201 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
202 if (ClassTemplateSpecializationDecl *Spec
203 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
204 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
205 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000206 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000207 }
208
209 continue;
210 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000211
Douglas Gregor124b8782010-02-16 19:09:40 +0000212 // We're referring to an unresolved class template
213 // specialization. Determine whether we class template we found
214 // is the same as the template being specialized or, if we don't
215 // know which template is being specialized, that it at least
216 // has the same name.
217 if (const TemplateSpecializationType *SpecType
218 = MemberOfType->getAs<TemplateSpecializationType>()) {
219 TemplateName SpecName = SpecType->getTemplateName();
220
221 // The class template we found is the same template being
222 // specialized.
223 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
224 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000225 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000226
227 continue;
228 }
229
230 // The class template we found has the same name as the
231 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000232 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000233 = SpecName.getAsDependentTemplateName()) {
234 if (DepTemplate->isIdentifier() &&
235 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000236 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000237
238 continue;
239 }
240 }
241 }
242 }
243
244 if (isDependent) {
245 // We didn't find our type, but that's okay: it's dependent
246 // anyway.
Douglas Gregore29425b2011-02-28 22:42:13 +0000247
248 // FIXME: What if we have no nested-name-specifier?
249 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
250 SS.getWithLocInContext(Context),
251 II, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000252 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000253 }
254
Douglas Gregor7ec18732011-03-04 22:32:08 +0000255 if (NonMatchingTypeDecl) {
256 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
257 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
258 << T << SearchType;
259 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
260 << T;
261 } else if (ObjectTypePtr)
262 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000263 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000264 else
265 Diag(NameLoc, diag::err_destructor_class_name);
266
John McCallb3d87482010-08-24 05:47:05 +0000267 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000268}
269
David Blaikie53a75c02011-12-08 16:13:53 +0000270ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie4db8c442011-12-12 04:13:55 +0000271 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikie53a75c02011-12-08 16:13:53 +0000272 return ParsedType();
273 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
274 && "only get destructor types from declspecs");
275 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
276 QualType SearchType = GetTypeFromParser(ObjectType);
277 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
278 return ParsedType::make(T);
279 }
280
281 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
282 << T << SearchType;
283 return ParsedType();
284}
285
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000286/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000287ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000288 SourceLocation TypeidLoc,
289 TypeSourceInfo *Operand,
290 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000291 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000292 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000293 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000294 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000295 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000296 Qualifiers Quals;
297 QualType T
298 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
299 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000300 if (T->getAs<RecordType>() &&
301 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
302 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000303
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000304 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
305 Operand,
306 SourceRange(TypeidLoc, RParenLoc)));
307}
308
309/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000310ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000311 SourceLocation TypeidLoc,
312 Expr *E,
313 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000314 if (E && !E->isTypeDependent()) {
John McCall6dbba4f2011-10-11 23:14:30 +0000315 if (E->getType()->isPlaceholderType()) {
316 ExprResult result = CheckPlaceholderExpr(E);
317 if (result.isInvalid()) return ExprError();
318 E = result.take();
319 }
320
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000321 QualType T = E->getType();
322 if (const RecordType *RecordT = T->getAs<RecordType>()) {
323 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
324 // C++ [expr.typeid]p3:
325 // [...] If the type of the expression is a class type, the class
326 // shall be completely-defined.
327 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
328 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000329
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000330 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000331 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000332 // polymorphic class type [...] [the] expression is an unevaluated
333 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000334 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Eli Friedmanef331b72012-01-20 01:26:23 +0000335 // The subexpression is potentially evaluated; switch the context
336 // and recheck the subexpression.
337 ExprResult Result = TranformToPotentiallyEvaluated(E);
338 if (Result.isInvalid()) return ExprError();
339 E = Result.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000340
341 // We require a vtable to query the type at run time.
342 MarkVTableUsed(TypeidLoc, RecordD);
343 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000344 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000345
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000346 // C++ [expr.typeid]p4:
347 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000348 // cv-qualified type, the result of the typeid expression refers to a
349 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000350 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000351 Qualifiers Quals;
352 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
353 if (!Context.hasSameType(T, UnqualT)) {
354 T = UnqualT;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000355 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000356 }
357 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000358
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000359 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000360 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000361 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000362}
363
364/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000365ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000366Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
367 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000368 // Find the std::type_info type.
Sebastian Redlce0682f2011-03-31 19:29:24 +0000369 if (!getStdNamespace())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000370 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000371
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000372 if (!CXXTypeInfoDecl) {
373 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
374 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
375 LookupQualifiedName(R, getStdNamespace());
376 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
377 if (!CXXTypeInfoDecl)
378 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
379 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000380
Nico Weber11d1a692012-05-20 01:27:21 +0000381 if (!getLangOpts().RTTI) {
382 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
383 }
384
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000385 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000386
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000387 if (isType) {
388 // The operand is a type; handle it as such.
389 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000390 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
391 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000392 if (T.isNull())
393 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000394
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000395 if (!TInfo)
396 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000397
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000398 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000399 }
Mike Stump1eb44332009-09-09 15:08:12 +0000400
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000401 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000402 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000403}
404
Francois Pichet6915c522010-12-27 01:32:00 +0000405/// Retrieve the UuidAttr associated with QT.
406static UuidAttr *GetUuidAttrOfType(QualType QT) {
407 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000408 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000409 if (QT->isPointerType() || QT->isReferenceType())
410 Ty = QT->getPointeeType().getTypePtr();
411 else if (QT->isArrayType())
412 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
413
Francois Pichet8db75a22011-05-08 10:02:20 +0000414 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichet6915c522010-12-27 01:32:00 +0000415 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet8db75a22011-05-08 10:02:20 +0000416 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
417 E = RD->redecls_end(); I != E; ++I) {
418 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichet6915c522010-12-27 01:32:00 +0000419 return Uuid;
Francois Pichet6915c522010-12-27 01:32:00 +0000420 }
Francois Pichet8db75a22011-05-08 10:02:20 +0000421
Francois Pichet6915c522010-12-27 01:32:00 +0000422 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000423}
424
Francois Pichet01b7c302010-09-08 12:20:18 +0000425/// \brief Build a Microsoft __uuidof expression with a type operand.
426ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
427 SourceLocation TypeidLoc,
428 TypeSourceInfo *Operand,
429 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000430 if (!Operand->getType()->isDependentType()) {
431 if (!GetUuidAttrOfType(Operand->getType()))
432 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
433 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000434
Francois Pichet01b7c302010-09-08 12:20:18 +0000435 // FIXME: add __uuidof semantic analysis for type operand.
436 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
437 Operand,
438 SourceRange(TypeidLoc, RParenLoc)));
439}
440
441/// \brief Build a Microsoft __uuidof expression with an expression operand.
442ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
443 SourceLocation TypeidLoc,
444 Expr *E,
445 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000446 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000447 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000448 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
449 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
450 }
451 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000452 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
453 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000454 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000455}
456
457/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
458ExprResult
459Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
460 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000461 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000462 if (!MSVCGuidDecl) {
463 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
464 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
465 LookupQualifiedName(R, Context.getTranslationUnitDecl());
466 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
467 if (!MSVCGuidDecl)
468 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000469 }
470
Francois Pichet01b7c302010-09-08 12:20:18 +0000471 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000472
Francois Pichet01b7c302010-09-08 12:20:18 +0000473 if (isType) {
474 // The operand is a type; handle it as such.
475 TypeSourceInfo *TInfo = 0;
476 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
477 &TInfo);
478 if (T.isNull())
479 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000480
Francois Pichet01b7c302010-09-08 12:20:18 +0000481 if (!TInfo)
482 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
483
484 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
485 }
486
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000487 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000488 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
489}
490
Steve Naroff1b273c42007-09-16 14:56:35 +0000491/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000492ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000493Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000494 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000495 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000496 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
497 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000498}
Chris Lattner50dd2892008-02-26 00:51:44 +0000499
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000500/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000501ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000502Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
503 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
504}
505
Chris Lattner50dd2892008-02-26 00:51:44 +0000506/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000507ExprResult
Douglas Gregorbca01b42011-07-06 22:04:06 +0000508Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
509 bool IsThrownVarInScope = false;
510 if (Ex) {
511 // C++0x [class.copymove]p31:
512 // When certain criteria are met, an implementation is allowed to omit the
513 // copy/move construction of a class object [...]
514 //
515 // - in a throw-expression, when the operand is the name of a
516 // non-volatile automatic object (other than a function or catch-
517 // clause parameter) whose scope does not extend beyond the end of the
518 // innermost enclosing try-block (if there is one), the copy/move
519 // operation from the operand to the exception object (15.1) can be
520 // omitted by constructing the automatic object directly into the
521 // exception object
522 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
523 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
524 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
525 for( ; S; S = S->getParent()) {
526 if (S->isDeclScope(Var)) {
527 IsThrownVarInScope = true;
528 break;
529 }
530
531 if (S->getFlags() &
532 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
533 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
534 Scope::TryScope))
535 break;
536 }
537 }
538 }
539 }
540
541 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
542}
543
544ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
545 bool IsThrownVarInScope) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000546 // Don't report an error if 'throw' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +0000547 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000548 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000549 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregorbca01b42011-07-06 22:04:06 +0000550
John Wiegley429bb272011-04-08 18:41:53 +0000551 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregorbca01b42011-07-06 22:04:06 +0000552 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley429bb272011-04-08 18:41:53 +0000553 if (ExRes.isInvalid())
554 return ExprError();
555 Ex = ExRes.take();
556 }
Douglas Gregorbca01b42011-07-06 22:04:06 +0000557
558 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
559 IsThrownVarInScope));
Sebastian Redl972041f2009-04-27 20:27:31 +0000560}
561
562/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000563ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
564 bool IsThrownVarInScope) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000565 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000566 // A throw-expression initializes a temporary object, called the exception
567 // object, the type of which is determined by removing any top-level
568 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000569 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000570 // or "pointer to function returning T", [...]
571 if (E->getType().hasQualifiers())
John Wiegley429bb272011-04-08 18:41:53 +0000572 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000573 E->getValueKind()).take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000574
John Wiegley429bb272011-04-08 18:41:53 +0000575 ExprResult Res = DefaultFunctionArrayConversion(E);
576 if (Res.isInvalid())
577 return ExprError();
578 E = Res.take();
Sebastian Redl972041f2009-04-27 20:27:31 +0000579
580 // If the type of the exception would be an incomplete type or a pointer
581 // to an incomplete type other than (cv) void the program is ill-formed.
582 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000583 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000584 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000585 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000586 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000587 }
588 if (!isPointer || !Ty->isVoidType()) {
589 if (RequireCompleteType(ThrowLoc, Ty,
Douglas Gregord10099e2012-05-04 16:32:21 +0000590 isPointer? diag::err_throw_incomplete_ptr
591 : diag::err_throw_incomplete,
592 E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000593 return ExprError();
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000594
Douglas Gregorbf422f92010-04-15 18:05:39 +0000595 if (RequireNonAbstractType(ThrowLoc, E->getType(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +0000596 diag::err_throw_abstract_type, E))
John Wiegley429bb272011-04-08 18:41:53 +0000597 return ExprError();
Sebastian Redl972041f2009-04-27 20:27:31 +0000598 }
599
John McCallac418162010-04-22 01:10:34 +0000600 // Initialize the exception result. This implicitly weeds out
601 // abstract types or types with inaccessible copy constructors.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000602
603 // C++0x [class.copymove]p31:
604 // When certain criteria are met, an implementation is allowed to omit the
605 // copy/move construction of a class object [...]
606 //
607 // - in a throw-expression, when the operand is the name of a
608 // non-volatile automatic object (other than a function or catch-clause
609 // parameter) whose scope does not extend beyond the end of the
610 // innermost enclosing try-block (if there is one), the copy/move
611 // operation from the operand to the exception object (15.1) can be
612 // omitted by constructing the automatic object directly into the
613 // exception object
614 const VarDecl *NRVOVariable = 0;
615 if (IsThrownVarInScope)
616 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
617
John McCallac418162010-04-22 01:10:34 +0000618 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000619 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregorbca01b42011-07-06 22:04:06 +0000620 /*NRVO=*/NRVOVariable != 0);
John Wiegley429bb272011-04-08 18:41:53 +0000621 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000622 QualType(), E,
623 IsThrownVarInScope);
John McCallac418162010-04-22 01:10:34 +0000624 if (Res.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000625 return ExprError();
626 E = Res.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000627
Eli Friedman5ed9b932010-06-03 20:39:03 +0000628 // If the exception has class type, we need additional handling.
629 const RecordType *RecordTy = Ty->getAs<RecordType>();
630 if (!RecordTy)
John Wiegley429bb272011-04-08 18:41:53 +0000631 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000632 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
633
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000634 // If we are throwing a polymorphic class type or pointer thereof,
635 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000636 MarkVTableUsed(ThrowLoc, RD);
637
Eli Friedman98efb9f2010-10-12 20:32:36 +0000638 // If a pointer is thrown, the referenced object will not be destroyed.
639 if (isPointer)
John Wiegley429bb272011-04-08 18:41:53 +0000640 return Owned(E);
Eli Friedman98efb9f2010-10-12 20:32:36 +0000641
Richard Smith213d70b2012-02-18 04:13:32 +0000642 // If the class has a destructor, we must be able to call it.
643 if (RD->hasIrrelevantDestructor())
John Wiegley429bb272011-04-08 18:41:53 +0000644 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000645
Sebastian Redl28357452012-03-05 19:35:43 +0000646 CXXDestructorDecl *Destructor = LookupDestructor(RD);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000647 if (!Destructor)
John Wiegley429bb272011-04-08 18:41:53 +0000648 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000649
Eli Friedman5f2987c2012-02-02 03:46:19 +0000650 MarkFunctionReferenced(E->getExprLoc(), Destructor);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000651 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000652 PDiag(diag::err_access_dtor_exception) << Ty);
Richard Smith213d70b2012-02-18 04:13:32 +0000653 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
John Wiegley429bb272011-04-08 18:41:53 +0000654 return Owned(E);
Chris Lattner50dd2892008-02-26 00:51:44 +0000655}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000656
Eli Friedman72899c32012-01-07 04:59:52 +0000657QualType Sema::getCurrentThisType() {
658 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000659 QualType ThisTy = CXXThisTypeOverride;
Richard Smith7a614d82011-06-11 17:19:42 +0000660 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
661 if (method && method->isInstance())
662 ThisTy = method->getThisType(Context);
Richard Smith7a614d82011-06-11 17:19:42 +0000663 }
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000664
Richard Smith7a614d82011-06-11 17:19:42 +0000665 return ThisTy;
John McCall5808ce42011-02-03 08:15:49 +0000666}
667
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000668Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
669 Decl *ContextDecl,
670 unsigned CXXThisTypeQuals,
671 bool Enabled)
672 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
673{
674 if (!Enabled || !ContextDecl)
675 return;
676
677 CXXRecordDecl *Record = 0;
678 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
679 Record = Template->getTemplatedDecl();
680 else
681 Record = cast<CXXRecordDecl>(ContextDecl);
682
683 S.CXXThisTypeOverride
684 = S.Context.getPointerType(
685 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
686
687 this->Enabled = true;
688}
689
690
691Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
692 if (Enabled) {
693 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
694 }
695}
696
Douglas Gregora1f21142012-02-01 17:04:21 +0000697void Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit) {
Eli Friedman72899c32012-01-07 04:59:52 +0000698 // We don't need to capture this in an unevaluated context.
Douglas Gregora1f21142012-02-01 17:04:21 +0000699 if (ExprEvalContexts.back().Context == Unevaluated && !Explicit)
Eli Friedman72899c32012-01-07 04:59:52 +0000700 return;
701
702 // Otherwise, check that we can capture 'this'.
703 unsigned NumClosures = 0;
704 for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000705 if (CapturingScopeInfo *CSI =
706 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
707 if (CSI->CXXThisCaptureIndex != 0) {
708 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman72899c32012-01-07 04:59:52 +0000709 break;
710 }
Douglas Gregora1f21142012-02-01 17:04:21 +0000711
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000712 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000713 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregora1f21142012-02-01 17:04:21 +0000714 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
715 Explicit) {
716 // This closure can capture 'this'; continue looking upwards.
Eli Friedman72899c32012-01-07 04:59:52 +0000717 NumClosures++;
Douglas Gregora1f21142012-02-01 17:04:21 +0000718 Explicit = false;
Eli Friedman72899c32012-01-07 04:59:52 +0000719 continue;
720 }
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000721 // This context can't implicitly capture 'this'; fail out.
Douglas Gregora1f21142012-02-01 17:04:21 +0000722 Diag(Loc, diag::err_this_capture) << Explicit;
Eli Friedman72899c32012-01-07 04:59:52 +0000723 return;
724 }
Eli Friedman72899c32012-01-07 04:59:52 +0000725 break;
726 }
727
728 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
729 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
730 // contexts.
731 for (unsigned idx = FunctionScopes.size() - 1;
732 NumClosures; --idx, --NumClosures) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000733 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Eli Friedman668165a2012-02-11 02:51:16 +0000734 Expr *ThisExpr = 0;
Douglas Gregor999713e2012-02-18 09:37:24 +0000735 QualType ThisTy = getCurrentThisType();
Eli Friedman668165a2012-02-11 02:51:16 +0000736 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
737 // For lambda expressions, build a field and an initializing expression.
Eli Friedman668165a2012-02-11 02:51:16 +0000738 CXXRecordDecl *Lambda = LSI->Lambda;
739 FieldDecl *Field
740 = FieldDecl::Create(Context, Lambda, Loc, Loc, 0, ThisTy,
741 Context.getTrivialTypeSourceInfo(ThisTy, Loc),
Richard Smithca523302012-06-10 03:12:00 +0000742 0, false, ICIS_NoInit);
Eli Friedman668165a2012-02-11 02:51:16 +0000743 Field->setImplicit(true);
744 Field->setAccess(AS_private);
745 Lambda->addDecl(Field);
746 ThisExpr = new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/true);
747 }
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000748 bool isNested = NumClosures > 1;
Douglas Gregor999713e2012-02-18 09:37:24 +0000749 CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
Eli Friedman72899c32012-01-07 04:59:52 +0000750 }
751}
752
Richard Smith7a614d82011-06-11 17:19:42 +0000753ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCall5808ce42011-02-03 08:15:49 +0000754 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
755 /// is a non-lvalue expression whose value is the address of the object for
756 /// which the function is called.
757
Douglas Gregor341350e2011-10-18 16:47:30 +0000758 QualType ThisTy = getCurrentThisType();
Richard Smith7a614d82011-06-11 17:19:42 +0000759 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCall5808ce42011-02-03 08:15:49 +0000760
Eli Friedman72899c32012-01-07 04:59:52 +0000761 CheckCXXThisCapture(Loc);
Richard Smith7a614d82011-06-11 17:19:42 +0000762 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000763}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000764
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000765bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
766 // If we're outside the body of a member function, then we'll have a specified
767 // type for 'this'.
768 if (CXXThisTypeOverride.isNull())
769 return false;
770
771 // Determine whether we're looking into a class that's currently being
772 // defined.
773 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
774 return Class && Class->isBeingDefined();
775}
776
John McCall60d7b3a2010-08-24 06:29:42 +0000777ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000778Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000779 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000780 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000781 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000782 if (!TypeRep)
783 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000784
John McCall9d125032010-01-15 18:39:57 +0000785 TypeSourceInfo *TInfo;
786 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
787 if (!TInfo)
788 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000789
790 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
791}
792
793/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
794/// Can be interpreted either as function-style casting ("int(x)")
795/// or class type construction ("ClassType(x,y,z)")
796/// or creation of a value-initialized type ("int()").
797ExprResult
798Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
799 SourceLocation LParenLoc,
800 MultiExprArg exprs,
801 SourceLocation RParenLoc) {
802 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000803 unsigned NumExprs = exprs.size();
804 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000805 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000806
Sebastian Redlf53597f2009-03-15 17:47:39 +0000807 if (Ty->isDependentType() ||
Ahmed Charles13a140c2012-02-25 11:00:22 +0000808 CallExpr::hasAnyTypeDependentArguments(
809 llvm::makeArrayRef(Exprs, NumExprs))) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000810 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Douglas Gregorab6677e2010-09-08 00:15:04 +0000812 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000813 LParenLoc,
814 Exprs, NumExprs,
815 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000816 }
817
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000818 bool ListInitialization = LParenLoc.isInvalid();
819 assert((!ListInitialization || (NumExprs == 1 && isa<InitListExpr>(Exprs[0])))
820 && "List initialization must have initializer list as expression.");
821 SourceRange FullRange = SourceRange(TyBeginLoc,
822 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
823
Douglas Gregor506ae412009-01-16 18:33:17 +0000824 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000825 // If the expression list is a single expression, the type conversion
826 // expression is equivalent (in definedness, and if defined in meaning) to the
827 // corresponding cast expression.
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000828 if (NumExprs == 1 && !ListInitialization) {
John McCallb45ae252011-10-05 07:41:44 +0000829 Expr *Arg = Exprs[0];
Anders Carlsson0aebc812009-09-09 21:33:21 +0000830 exprs.release();
John McCallb45ae252011-10-05 07:41:44 +0000831 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000832 }
833
Eli Friedmanc60ccf52012-02-29 00:00:28 +0000834 QualType ElemTy = Ty;
835 if (Ty->isArrayType()) {
836 if (!ListInitialization)
837 return ExprError(Diag(TyBeginLoc,
838 diag::err_value_init_for_array_type) << FullRange);
839 ElemTy = Context.getBaseElementType(Ty);
840 }
841
842 if (!Ty->isVoidType() &&
843 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregord10099e2012-05-04 16:32:21 +0000844 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedmanc60ccf52012-02-29 00:00:28 +0000845 return ExprError();
846
847 if (RequireNonAbstractType(TyBeginLoc, Ty,
848 diag::err_allocation_of_abstract_type))
849 return ExprError();
850
Douglas Gregor19311e72010-09-08 21:40:08 +0000851 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
852 InitializationKind Kind
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000853 = NumExprs ? ListInitialization
854 ? InitializationKind::CreateDirectList(TyBeginLoc)
855 : InitializationKind::CreateDirect(TyBeginLoc,
856 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000857 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000858 LParenLoc, RParenLoc);
859 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
860 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000861
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000862 if (!Result.isInvalid() && ListInitialization &&
863 isa<InitListExpr>(Result.get())) {
864 // If the list-initialization doesn't involve a constructor call, we'll get
865 // the initializer-list (with corrected type) back, but that's not what we
866 // want, since it will be treated as an initializer list in further
867 // processing. Explicitly insert a cast here.
868 InitListExpr *List = cast<InitListExpr>(Result.take());
869 Result = Owned(CXXFunctionalCastExpr::Create(Context, List->getType(),
870 Expr::getValueKindForType(TInfo->getType()),
871 TInfo, TyBeginLoc, CK_NoOp,
872 List, /*Path=*/0, RParenLoc));
873 }
874
Douglas Gregor19311e72010-09-08 21:40:08 +0000875 // FIXME: Improve AST representation?
876 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000877}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000878
John McCall6ec278d2011-01-27 09:37:56 +0000879/// doesUsualArrayDeleteWantSize - Answers whether the usual
880/// operator delete[] for the given type has a size_t parameter.
881static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
882 QualType allocType) {
883 const RecordType *record =
884 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
885 if (!record) return false;
886
887 // Try to find an operator delete[] in class scope.
888
889 DeclarationName deleteName =
890 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
891 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
892 S.LookupQualifiedName(ops, record->getDecl());
893
894 // We're just doing this for information.
895 ops.suppressDiagnostics();
896
897 // Very likely: there's no operator delete[].
898 if (ops.empty()) return false;
899
900 // If it's ambiguous, it should be illegal to call operator delete[]
901 // on this thing, so it doesn't matter if we allocate extra space or not.
902 if (ops.isAmbiguous()) return false;
903
904 LookupResult::Filter filter = ops.makeFilter();
905 while (filter.hasNext()) {
906 NamedDecl *del = filter.next()->getUnderlyingDecl();
907
908 // C++0x [basic.stc.dynamic.deallocation]p2:
909 // A template instance is never a usual deallocation function,
910 // regardless of its signature.
911 if (isa<FunctionTemplateDecl>(del)) {
912 filter.erase();
913 continue;
914 }
915
916 // C++0x [basic.stc.dynamic.deallocation]p2:
917 // If class T does not declare [an operator delete[] with one
918 // parameter] but does declare a member deallocation function
919 // named operator delete[] with exactly two parameters, the
920 // second of which has type std::size_t, then this function
921 // is a usual deallocation function.
922 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
923 filter.erase();
924 continue;
925 }
926 }
927 filter.done();
928
929 if (!ops.isSingleResult()) return false;
930
931 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
932 return (del->getNumParams() == 2);
933}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000934
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000935/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettef2b5b32012-06-15 22:23:43 +0000936///
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000937/// E.g.:
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000938/// @code new (memory) int[size][4] @endcode
939/// or
940/// @code ::new Foo(23, "hello") @endcode
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000941///
942/// \param StartLoc The first location of the expression.
943/// \param UseGlobal True if 'new' was prefixed with '::'.
944/// \param PlacementLParen Opening paren of the placement arguments.
945/// \param PlacementArgs Placement new arguments.
946/// \param PlacementRParen Closing paren of the placement arguments.
947/// \param TypeIdParens If the type is in parens, the source range.
948/// \param D The type to be allocated, as well as array dimensions.
James Dennettef2b5b32012-06-15 22:23:43 +0000949/// \param Initializer The initializing expression or initializer-list, or null
950/// if there is none.
John McCall60d7b3a2010-08-24 06:29:42 +0000951ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000952Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000953 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000954 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000955 Declarator &D, Expr *Initializer) {
Richard Smith34b41d92011-02-20 03:19:35 +0000956 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
957
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000958 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000959 // If the specified type is an array, unwrap it and save the expression.
960 if (D.getNumTypeObjects() > 0 &&
961 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
James Dennettef2b5b32012-06-15 22:23:43 +0000962 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000963 if (TypeContainsAuto)
964 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
965 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000966 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000967 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
968 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000969 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000970 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
971 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000972
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000973 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000974 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000975 }
976
Douglas Gregor043cad22009-09-11 00:18:58 +0000977 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000978 if (ArraySize) {
979 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000980 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
981 break;
982
983 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
984 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smith282e7e62012-02-04 09:53:13 +0000985 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000986 Array.NumElts
987 = VerifyIntegerConstantExpression(NumElts, 0,
988 diag::err_new_array_nonconst)
989 .take();
Richard Smith282e7e62012-02-04 09:53:13 +0000990 if (!Array.NumElts)
991 return ExprError();
Douglas Gregor043cad22009-09-11 00:18:58 +0000992 }
993 }
994 }
995 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000996
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +0000997 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCallbf1a0282010-06-04 23:28:52 +0000998 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000999 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001000 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001001
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001002 SourceRange DirectInitRange;
1003 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1004 DirectInitRange = List->getSourceRange();
1005
Mike Stump1eb44332009-09-09 15:08:12 +00001006 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +00001007 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +00001008 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +00001009 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001010 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +00001011 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001012 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00001013 ArraySize,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001014 DirectInitRange,
1015 Initializer,
Richard Smith34b41d92011-02-20 03:19:35 +00001016 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +00001017}
1018
Sebastian Redlbd45d252012-02-16 12:59:47 +00001019static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1020 Expr *Init) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001021 if (!Init)
1022 return true;
Sebastian Redl1f278052012-02-17 08:42:32 +00001023 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1024 return PLE->getNumExprs() == 0;
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001025 if (isa<ImplicitValueInitExpr>(Init))
1026 return true;
1027 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1028 return !CCE->isListInitialization() &&
1029 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlbd45d252012-02-16 12:59:47 +00001030 else if (Style == CXXNewExpr::ListInit) {
1031 assert(isa<InitListExpr>(Init) &&
1032 "Shouldn't create list CXXConstructExprs for arrays.");
1033 return true;
1034 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001035 return false;
1036}
1037
John McCall60d7b3a2010-08-24 06:29:42 +00001038ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +00001039Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
1040 SourceLocation PlacementLParen,
1041 MultiExprArg PlacementArgs,
1042 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001043 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +00001044 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001045 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +00001046 Expr *ArraySize,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001047 SourceRange DirectInitRange,
1048 Expr *Initializer,
Richard Smith34b41d92011-02-20 03:19:35 +00001049 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001050 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001051
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001052 CXXNewExpr::InitializationStyle initStyle;
1053 if (DirectInitRange.isValid()) {
1054 assert(Initializer && "Have parens but no initializer.");
1055 initStyle = CXXNewExpr::CallInit;
1056 } else if (Initializer && isa<InitListExpr>(Initializer))
1057 initStyle = CXXNewExpr::ListInit;
1058 else {
Sebastian Redl428c6202012-02-22 09:07:21 +00001059 // In template instantiation, the initializer could be a CXXDefaultArgExpr
1060 // unwrapped from a CXXConstructExpr that was implicitly built. There is no
1061 // particularly sane way we can handle this (especially since it can even
1062 // occur for array new), so we throw the initializer away and have it be
1063 // rebuilt.
1064 if (Initializer && isa<CXXDefaultArgExpr>(Initializer))
1065 Initializer = 0;
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001066 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1067 isa<CXXConstructExpr>(Initializer)) &&
1068 "Initializer expression that cannot have been implicitly created.");
1069 initStyle = CXXNewExpr::NoInit;
1070 }
1071
1072 Expr **Inits = &Initializer;
1073 unsigned NumInits = Initializer ? 1 : 0;
1074 if (initStyle == CXXNewExpr::CallInit) {
1075 if (ParenListExpr *List = dyn_cast<ParenListExpr>(Initializer)) {
1076 Inits = List->getExprs();
1077 NumInits = List->getNumExprs();
1078 } else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Initializer)){
1079 if (!isa<CXXTemporaryObjectExpr>(CCE)) {
1080 // Can happen in template instantiation. Since this is just an implicit
1081 // construction, we just take it apart and rebuild it.
1082 Inits = CCE->getArgs();
1083 NumInits = CCE->getNumArgs();
1084 }
1085 }
1086 }
1087
Richard Smith34b41d92011-02-20 03:19:35 +00001088 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1089 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001090 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith34b41d92011-02-20 03:19:35 +00001091 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1092 << AllocType << TypeRange);
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001093 if (initStyle == CXXNewExpr::ListInit)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001094 return ExprError(Diag(Inits[0]->getLocStart(),
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001095 diag::err_auto_new_requires_parens)
1096 << AllocType << TypeRange);
1097 if (NumInits > 1) {
1098 Expr *FirstBad = Inits[1];
Daniel Dunbar96a00142012-03-09 18:35:03 +00001099 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith34b41d92011-02-20 03:19:35 +00001100 diag::err_auto_new_ctor_multiple_expressions)
1101 << AllocType << TypeRange);
1102 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001103 Expr *Deduce = Inits[0];
Richard Smitha085da82011-03-17 16:11:59 +00001104 TypeSourceInfo *DeducedType = 0;
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001105 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001106 DAR_Failed)
Richard Smith34b41d92011-02-20 03:19:35 +00001107 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001108 << AllocType << Deduce->getType()
1109 << TypeRange << Deduce->getSourceRange());
Richard Smitha085da82011-03-17 16:11:59 +00001110 if (!DeducedType)
1111 return ExprError();
Richard Smith34b41d92011-02-20 03:19:35 +00001112
Richard Smitha085da82011-03-17 16:11:59 +00001113 AllocTypeInfo = DeducedType;
1114 AllocType = AllocTypeInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +00001115 }
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001116
Douglas Gregor3caf04e2010-05-16 16:01:03 +00001117 // Per C++0x [expr.new]p5, the type being constructed may be a
1118 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +00001119 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +00001120 if (const ConstantArrayType *Array
1121 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001122 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1123 Context.getSizeType(),
1124 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +00001125 AllocType = Array->getElementType();
1126 }
1127 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001128
Douglas Gregora0750762010-10-06 16:00:31 +00001129 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1130 return ExprError();
1131
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001132 if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001133 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1134 diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001135 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001136 }
1137
John McCallf85e1932011-06-15 23:02:42 +00001138 // In ARC, infer 'retaining' for the allocated
David Blaikie4e4d0842012-03-11 07:00:24 +00001139 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001140 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1141 AllocType->isObjCLifetimeType()) {
1142 AllocType = Context.getLifetimeQualifiedType(AllocType,
1143 AllocType->getObjCARCImplicitLifetime());
1144 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001145
John McCallf85e1932011-06-15 23:02:42 +00001146 QualType ResultType = Context.getPointerType(AllocType);
1147
Richard Smithf39aec12012-02-04 07:07:42 +00001148 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1149 // integral or enumeration type with a non-negative value."
1150 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1151 // enumeration type, or a class type for which a single non-explicit
1152 // conversion function to integral or unscoped enumeration type exists.
Sebastian Redl28507842009-02-26 14:39:58 +00001153 if (ArraySize && !ArraySize->isTypeDependent()) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00001154 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1155 Expr *ArraySize;
1156
1157 public:
1158 SizeConvertDiagnoser(Expr *ArraySize)
1159 : ICEConvertDiagnoser(false, false), ArraySize(ArraySize) { }
1160
1161 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1162 QualType T) {
1163 return S.Diag(Loc, diag::err_array_size_not_integral)
1164 << S.getLangOpts().CPlusPlus0x << T;
1165 }
1166
1167 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
1168 QualType T) {
1169 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1170 << T << ArraySize->getSourceRange();
1171 }
1172
1173 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
1174 SourceLocation Loc,
1175 QualType T,
1176 QualType ConvTy) {
1177 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1178 }
1179
1180 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
1181 CXXConversionDecl *Conv,
1182 QualType ConvTy) {
1183 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1184 << ConvTy->isEnumeralType() << ConvTy;
1185 }
1186
1187 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
1188 QualType T) {
1189 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1190 }
1191
1192 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
1193 QualType ConvTy) {
1194 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1195 << ConvTy->isEnumeralType() << ConvTy;
1196 }
1197
1198 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1199 QualType T,
1200 QualType ConvTy) {
1201 return S.Diag(Loc,
1202 S.getLangOpts().CPlusPlus0x
1203 ? diag::warn_cxx98_compat_array_size_conversion
1204 : diag::ext_array_size_conversion)
1205 << T << ConvTy->isEnumeralType() << ConvTy;
1206 }
1207 } SizeDiagnoser(ArraySize);
1208
1209 ExprResult ConvertedSize
1210 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize, SizeDiagnoser,
1211 /*AllowScopedEnumerations*/ false);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001212 if (ConvertedSize.isInvalid())
1213 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001214
John McCall9ae2f072010-08-23 23:25:46 +00001215 ArraySize = ConvertedSize.take();
John McCall806054d2012-01-11 00:14:46 +00001216 QualType SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001217 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001218 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001219
Richard Smith0b458fd2012-02-04 05:35:53 +00001220 // C++98 [expr.new]p7:
1221 // The expression in a direct-new-declarator shall have integral type
1222 // with a non-negative value.
1223 //
1224 // Let's see if this is a constant < 0. If so, we reject it out of
1225 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1226 // array type.
1227 //
1228 // Note: such a construct has well-defined semantics in C++11: it throws
1229 // std::bad_array_new_length.
Sebastian Redl28507842009-02-26 14:39:58 +00001230 if (!ArraySize->isValueDependent()) {
1231 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +00001232 // We've already performed any required implicit conversion to integer or
1233 // unscoped enumeration type.
Richard Smith0b458fd2012-02-04 05:35:53 +00001234 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Sebastian Redl28507842009-02-26 14:39:58 +00001235 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001236 llvm::APInt::getNullValue(Value.getBitWidth()),
Richard Smith0b458fd2012-02-04 05:35:53 +00001237 Value.isUnsigned())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001238 if (getLangOpts().CPlusPlus0x)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001239 Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001240 diag::warn_typecheck_negative_array_new_size)
Douglas Gregor2767ce22010-08-18 00:39:00 +00001241 << ArraySize->getSourceRange();
Richard Smith0b458fd2012-02-04 05:35:53 +00001242 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00001243 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001244 diag::err_typecheck_negative_array_size)
1245 << ArraySize->getSourceRange());
1246 } else if (!AllocType->isDependentType()) {
1247 unsigned ActiveSizeBits =
1248 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1249 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001250 if (getLangOpts().CPlusPlus0x)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001251 Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001252 diag::warn_array_new_too_large)
1253 << Value.toString(10)
1254 << ArraySize->getSourceRange();
1255 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00001256 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001257 diag::err_array_too_large)
1258 << Value.toString(10)
1259 << ArraySize->getSourceRange());
Douglas Gregor2767ce22010-08-18 00:39:00 +00001260 }
1261 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001262 } else if (TypeIdParens.isValid()) {
1263 // Can't have dynamic array size when the type-id is in parentheses.
1264 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1265 << ArraySize->getSourceRange()
1266 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1267 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001268
Douglas Gregor4bd40312010-07-13 15:54:32 +00001269 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001270 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001271 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001272
John McCallf85e1932011-06-15 23:02:42 +00001273 // ARC: warn about ABI issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00001274 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001275 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1276 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1277 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1278 << 0 << BaseAllocType;
1279 }
1280
John McCall7d166272011-05-15 07:14:44 +00001281 // Note that we do *not* convert the argument in any way. It can
1282 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001283 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001284
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001285 FunctionDecl *OperatorNew = 0;
1286 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001287 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1288 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001289
Sebastian Redl28507842009-02-26 14:39:58 +00001290 if (!AllocType->isDependentType() &&
Ahmed Charles13a140c2012-02-25 11:00:22 +00001291 !Expr::hasAnyTypeDependentArguments(
1292 llvm::makeArrayRef(PlaceArgs, NumPlaceArgs)) &&
Sebastian Redl28507842009-02-26 14:39:58 +00001293 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001294 SourceRange(PlacementLParen, PlacementRParen),
1295 UseGlobal, AllocType, ArraySize, PlaceArgs,
1296 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001297 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001298
1299 // If this is an array allocation, compute whether the usual array
1300 // deallocation function for the type has a size_t parameter.
1301 bool UsualArrayDeleteWantsSize = false;
1302 if (ArraySize && !AllocType->isDependentType())
1303 UsualArrayDeleteWantsSize
1304 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1305
Chris Lattner5f9e2722011-07-23 10:55:15 +00001306 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001307 if (OperatorNew) {
1308 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001309 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001310 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001311 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001312 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001313
Anders Carlsson28e94832010-05-03 02:07:56 +00001314 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001315 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +00001316 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001317 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001318
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001319 NumPlaceArgs = AllPlaceArgs.size();
1320 if (NumPlaceArgs > 0)
1321 PlaceArgs = &AllPlaceArgs[0];
Eli Friedmane61eb042012-02-18 04:48:30 +00001322
1323 DiagnoseSentinelCalls(OperatorNew, PlacementLParen,
1324 PlaceArgs, NumPlaceArgs);
1325
1326 // FIXME: Missing call to CheckFunctionCall or equivalent
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001327 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001328
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001329 // Warn if the type is over-aligned and is being allocated by global operator
1330 // new.
Nick Lewycky507a8a32012-02-04 03:30:14 +00001331 if (NumPlaceArgs == 0 && OperatorNew &&
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001332 (OperatorNew->isImplicit() ||
1333 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1334 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1335 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1336 if (Align > SuitableAlign)
1337 Diag(StartLoc, diag::warn_overaligned_type)
1338 << AllocType
1339 << unsigned(Align / Context.getCharWidth())
1340 << unsigned(SuitableAlign / Context.getCharWidth());
1341 }
1342 }
1343
Sebastian Redlbd45d252012-02-16 12:59:47 +00001344 QualType InitType = AllocType;
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001345 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlbd45d252012-02-16 12:59:47 +00001346 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1347 // dialect distinction.
1348 if (ResultType->isArrayType() || ArraySize) {
1349 if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1350 SourceRange InitRange(Inits[0]->getLocStart(),
1351 Inits[NumInits - 1]->getLocEnd());
1352 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1353 return ExprError();
1354 }
1355 if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1356 // We do the initialization typechecking against the array type
1357 // corresponding to the number of initializers + 1 (to also check
1358 // default-initialization).
1359 unsigned NumElements = ILE->getNumInits() + 1;
1360 InitType = Context.getConstantArrayType(AllocType,
1361 llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1362 ArrayType::Normal, 0);
1363 }
Anders Carlsson48c95012010-05-03 15:45:23 +00001364 }
1365
Douglas Gregor99a2e602009-12-16 01:38:02 +00001366 if (!AllocType->isDependentType() &&
Ahmed Charles13a140c2012-02-25 11:00:22 +00001367 !Expr::hasAnyTypeDependentArguments(
1368 llvm::makeArrayRef(Inits, NumInits))) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001369 // C++11 [expr.new]p15:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001370 // A new-expression that creates an object of type T initializes that
1371 // object as follows:
1372 InitializationKind Kind
1373 // - If the new-initializer is omitted, the object is default-
1374 // initialized (8.5); if no initialization is performed,
1375 // the object has indeterminate value
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001376 = initStyle == CXXNewExpr::NoInit
1377 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001378 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001379 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001380 : initStyle == CXXNewExpr::ListInit
1381 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1382 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1383 DirectInitRange.getBegin(),
1384 DirectInitRange.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001385
Douglas Gregor99a2e602009-12-16 01:38:02 +00001386 InitializedEntity Entity
Sebastian Redlbd45d252012-02-16 12:59:47 +00001387 = InitializedEntity::InitializeNew(StartLoc, InitType);
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001388 InitializationSequence InitSeq(*this, Entity, Kind, Inits, NumInits);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001389 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001390 MultiExprArg(Inits, NumInits));
Douglas Gregor99a2e602009-12-16 01:38:02 +00001391 if (FullInit.isInvalid())
1392 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001393
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001394 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1395 // we don't want the initialized object to be destructed.
1396 if (CXXBindTemporaryExpr *Binder =
1397 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1398 FullInit = Owned(Binder->getSubExpr());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001399
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001400 Initializer = FullInit.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001401 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001402
Douglas Gregor6d908702010-02-26 05:06:18 +00001403 // Mark the new and delete operators as referenced.
1404 if (OperatorNew)
Eli Friedman5f2987c2012-02-02 03:46:19 +00001405 MarkFunctionReferenced(StartLoc, OperatorNew);
Douglas Gregor6d908702010-02-26 05:06:18 +00001406 if (OperatorDelete)
Eli Friedman5f2987c2012-02-02 03:46:19 +00001407 MarkFunctionReferenced(StartLoc, OperatorDelete);
Douglas Gregor6d908702010-02-26 05:06:18 +00001408
John McCall84ff0fc2011-07-13 20:12:57 +00001409 // C++0x [expr.new]p17:
1410 // If the new expression creates an array of objects of class type,
1411 // access and ambiguity control are done for the destructor.
David Blaikie426d6ca2012-03-10 23:40:02 +00001412 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1413 if (ArraySize && !BaseAllocType->isDependentType()) {
1414 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1415 if (CXXDestructorDecl *dtor = LookupDestructor(
1416 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1417 MarkFunctionReferenced(StartLoc, dtor);
1418 CheckDestructorAccess(StartLoc, dtor,
1419 PDiag(diag::err_access_dtor)
1420 << BaseAllocType);
1421 DiagnoseUseOfDecl(dtor, StartLoc);
1422 }
John McCall84ff0fc2011-07-13 20:12:57 +00001423 }
1424 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001425
Sebastian Redlf53597f2009-03-15 17:47:39 +00001426 PlacementArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001427
Ted Kremenekad7fe862010-02-11 22:51:03 +00001428 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001429 OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001430 UsualArrayDeleteWantsSize,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001431 PlaceArgs, NumPlaceArgs, TypeIdParens,
1432 ArraySize, initStyle, Initializer,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001433 ResultType, AllocTypeInfo,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001434 StartLoc, DirectInitRange));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001435}
1436
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001437/// \brief Checks that a type is suitable as the allocated type
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001438/// in a new-expression.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001439bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001440 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001441 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1442 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001443 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001444 return Diag(Loc, diag::err_bad_new_type)
1445 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001446 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001447 return Diag(Loc, diag::err_bad_new_type)
1448 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001449 else if (!AllocType->isDependentType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001450 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001451 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001452 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001453 diag::err_allocation_of_abstract_type))
1454 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001455 else if (AllocType->isVariablyModifiedType())
1456 return Diag(Loc, diag::err_variably_modified_new_type)
1457 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001458 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1459 return Diag(Loc, diag::err_address_space_qualified_new)
1460 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikie4e4d0842012-03-11 07:00:24 +00001461 else if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001462 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1463 QualType BaseAllocType = Context.getBaseElementType(AT);
1464 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1465 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001466 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001467 << BaseAllocType;
1468 }
1469 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001470
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001471 return false;
1472}
1473
Douglas Gregor6d908702010-02-26 05:06:18 +00001474/// \brief Determine whether the given function is a non-placement
1475/// deallocation function.
1476static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1477 if (FD->isInvalidDecl())
1478 return false;
1479
1480 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1481 return Method->isUsualDeallocationFunction();
1482
1483 return ((FD->getOverloadedOperator() == OO_Delete ||
1484 FD->getOverloadedOperator() == OO_Array_Delete) &&
1485 FD->getNumParams() == 1);
1486}
1487
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001488/// FindAllocationFunctions - Finds the overloads of operator new and delete
1489/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001490bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1491 bool UseGlobal, QualType AllocType,
1492 bool IsArray, Expr **PlaceArgs,
1493 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001494 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001495 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001496 // --- Choosing an allocation function ---
1497 // C++ 5.3.4p8 - 14 & 18
1498 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1499 // in the scope of the allocated class.
1500 // 2) If an array size is given, look for operator new[], else look for
1501 // operator new.
1502 // 3) The first argument is always size_t. Append the arguments from the
1503 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001504
Chris Lattner5f9e2722011-07-23 10:55:15 +00001505 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001506 // We don't care about the actual value of this argument.
1507 // FIXME: Should the Sema create the expression and embed it in the syntax
1508 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001509 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001510 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001511 Context.getSizeType(),
1512 SourceLocation());
1513 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001514 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1515
Douglas Gregor6d908702010-02-26 05:06:18 +00001516 // C++ [expr.new]p8:
1517 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001518 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001519 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001520 // type, the allocation function's name is operator new[] and the
1521 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001522 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1523 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001524 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1525 IsArray ? OO_Array_Delete : OO_Delete);
1526
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001527 QualType AllocElemType = Context.getBaseElementType(AllocType);
1528
1529 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001530 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001531 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001532 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001533 AllocArgs.size(), Record, /*AllowMissing=*/true,
1534 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001535 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001536 }
1537 if (!OperatorNew) {
1538 // Didn't find a member overload. Look for a global one.
1539 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001540 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001541 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001542 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1543 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001544 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001545 }
1546
John McCall9c82afc2010-04-20 02:18:25 +00001547 // We don't need an operator delete if we're running under
1548 // -fno-exceptions.
David Blaikie4e4d0842012-03-11 07:00:24 +00001549 if (!getLangOpts().Exceptions) {
John McCall9c82afc2010-04-20 02:18:25 +00001550 OperatorDelete = 0;
1551 return false;
1552 }
1553
Anders Carlssond9583892009-05-31 20:26:12 +00001554 // FindAllocationOverload can change the passed in arguments, so we need to
1555 // copy them back.
1556 if (NumPlaceArgs > 0)
1557 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Douglas Gregor6d908702010-02-26 05:06:18 +00001559 // C++ [expr.new]p19:
1560 //
1561 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001562 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001563 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001564 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001565 // the scope of T. If this lookup fails to find the name, or if
1566 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001567 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001568 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001569 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001570 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001571 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001572 LookupQualifiedName(FoundDelete, RD);
1573 }
John McCall90c8c572010-03-18 08:19:33 +00001574 if (FoundDelete.isAmbiguous())
1575 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001576
1577 if (FoundDelete.empty()) {
1578 DeclareGlobalNewDelete();
1579 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1580 }
1581
1582 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001583
Chris Lattner5f9e2722011-07-23 10:55:15 +00001584 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001585
John McCalledeb6c92010-09-14 21:34:24 +00001586 // Whether we're looking for a placement operator delete is dictated
1587 // by whether we selected a placement operator new, not by whether
1588 // we had explicit placement arguments. This matters for things like
1589 // struct A { void *operator new(size_t, int = 0); ... };
1590 // A *a = new A()
1591 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1592
1593 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001594 // C++ [expr.new]p20:
1595 // A declaration of a placement deallocation function matches the
1596 // declaration of a placement allocation function if it has the
1597 // same number of parameters and, after parameter transformations
1598 // (8.3.5), all parameter types except the first are
1599 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001600 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001601 // To perform this comparison, we compute the function type that
1602 // the deallocation function should have, and use that type both
1603 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001604 //
1605 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001606 QualType ExpectedFunctionType;
1607 {
1608 const FunctionProtoType *Proto
1609 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001610
Chris Lattner5f9e2722011-07-23 10:55:15 +00001611 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001612 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001613 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1614 ArgTypes.push_back(Proto->getArgType(I));
1615
John McCalle23cf432010-12-14 08:05:40 +00001616 FunctionProtoType::ExtProtoInfo EPI;
1617 EPI.Variadic = Proto->isVariadic();
1618
Douglas Gregor6d908702010-02-26 05:06:18 +00001619 ExpectedFunctionType
1620 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001621 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001622 }
1623
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001624 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001625 DEnd = FoundDelete.end();
1626 D != DEnd; ++D) {
1627 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001628 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001629 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1630 // Perform template argument deduction to try to match the
1631 // expected function type.
1632 TemplateDeductionInfo Info(Context, StartLoc);
1633 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1634 continue;
1635 } else
1636 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1637
1638 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001639 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001640 }
1641 } else {
1642 // C++ [expr.new]p20:
1643 // [...] Any non-placement deallocation function matches a
1644 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001645 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001646 DEnd = FoundDelete.end();
1647 D != DEnd; ++D) {
1648 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1649 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001650 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001651 }
1652 }
1653
1654 // C++ [expr.new]p20:
1655 // [...] If the lookup finds a single matching deallocation
1656 // function, that function will be called; otherwise, no
1657 // deallocation function will be called.
1658 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001659 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001660
1661 // C++0x [expr.new]p20:
1662 // If the lookup finds the two-parameter form of a usual
1663 // deallocation function (3.7.4.2) and that function, considered
1664 // as a placement deallocation function, would have been
1665 // selected as a match for the allocation function, the program
1666 // is ill-formed.
David Blaikie4e4d0842012-03-11 07:00:24 +00001667 if (NumPlaceArgs && getLangOpts().CPlusPlus0x &&
Douglas Gregor6d908702010-02-26 05:06:18 +00001668 isNonPlacementDeallocationFunction(OperatorDelete)) {
1669 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001670 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001671 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1672 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1673 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001674 } else {
1675 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001676 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001677 }
1678 }
1679
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001680 return false;
1681}
1682
Sebastian Redl7f662392008-12-04 22:20:51 +00001683/// FindAllocationOverload - Find an fitting overload for the allocation
1684/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001685bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1686 DeclarationName Name, Expr** Args,
1687 unsigned NumArgs, DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001688 bool AllowMissing, FunctionDecl *&Operator,
1689 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001690 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1691 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001692 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001693 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001694 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001695 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001696 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001697 }
1698
John McCall90c8c572010-03-18 08:19:33 +00001699 if (R.isAmbiguous())
1700 return true;
1701
1702 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001703
John McCall5769d612010-02-08 23:07:23 +00001704 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001705 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001706 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001707 // Even member operator new/delete are implicitly treated as
1708 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001709 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001710
John McCall9aa472c2010-03-19 07:35:19 +00001711 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1712 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001713 /*ExplicitTemplateArgs=*/0,
1714 llvm::makeArrayRef(Args, NumArgs),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001715 Candidates,
1716 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001717 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001718 }
1719
John McCall9aa472c2010-03-19 07:35:19 +00001720 FunctionDecl *Fn = cast<FunctionDecl>(D);
Ahmed Charles13a140c2012-02-25 11:00:22 +00001721 AddOverloadCandidate(Fn, Alloc.getPair(),
1722 llvm::makeArrayRef(Args, NumArgs), Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001723 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001724 }
1725
1726 // Do the resolution.
1727 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001728 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001729 case OR_Success: {
1730 // Got one!
1731 FunctionDecl *FnDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00001732 MarkFunctionReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001733 // The first argument is size_t, and the first parameter must be size_t,
1734 // too. This is checked on declaration and can be assumed. (It can't be
1735 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001736 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001737 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1738 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001739 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1740 FnDecl->getParamDecl(i));
1741
1742 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1743 return true;
1744
John McCall60d7b3a2010-08-24 06:29:42 +00001745 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001746 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001747 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001748 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001749
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001750 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001751 }
Richard Smith9a561d52012-02-26 09:11:52 +00001752
Sebastian Redl7f662392008-12-04 22:20:51 +00001753 Operator = FnDecl;
Richard Smith9a561d52012-02-26 09:11:52 +00001754
1755 if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1756 Best->FoundDecl, Diagnose) == AR_inaccessible)
1757 return true;
1758
Sebastian Redl7f662392008-12-04 22:20:51 +00001759 return false;
1760 }
1761
1762 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001763 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001764 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1765 << Name << Range;
Ahmed Charles13a140c2012-02-25 11:00:22 +00001766 Candidates.NoteCandidates(*this, OCD_AllCandidates,
1767 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruth361d3802011-06-08 10:26:03 +00001768 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001769 return true;
1770
1771 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001772 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001773 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1774 << Name << Range;
Ahmed Charles13a140c2012-02-25 11:00:22 +00001775 Candidates.NoteCandidates(*this, OCD_ViableCandidates,
1776 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruth361d3802011-06-08 10:26:03 +00001777 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001778 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001779
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001780 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001781 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001782 Diag(StartLoc, diag::err_ovl_deleted_call)
1783 << Best->Function->isDeleted()
1784 << Name
1785 << getDeletedOrUnavailableSuffix(Best->Function)
1786 << Range;
Ahmed Charles13a140c2012-02-25 11:00:22 +00001787 Candidates.NoteCandidates(*this, OCD_AllCandidates,
1788 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruth361d3802011-06-08 10:26:03 +00001789 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001790 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001791 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001792 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001793 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl7f662392008-12-04 22:20:51 +00001794}
1795
1796
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001797/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1798/// delete. These are:
1799/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001800/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001801/// void* operator new(std::size_t) throw(std::bad_alloc);
1802/// void* operator new[](std::size_t) throw(std::bad_alloc);
1803/// void operator delete(void *) throw();
1804/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001805/// // C++0x:
1806/// void* operator new(std::size_t);
1807/// void* operator new[](std::size_t);
1808/// void operator delete(void *);
1809/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001810/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001811/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001812/// Note that the placement and nothrow forms of new are *not* implicitly
1813/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001814void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001815 if (GlobalNewDeleteDeclared)
1816 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001817
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001818 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001819 // [...] The following allocation and deallocation functions (18.4) are
1820 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001821 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001822 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001823 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001824 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001825 // void* operator new[](std::size_t) throw(std::bad_alloc);
1826 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001827 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001828 // C++0x:
1829 // void* operator new(std::size_t);
1830 // void* operator new[](std::size_t);
1831 // void operator delete(void*);
1832 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001833 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001834 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001835 // new, operator new[], operator delete, operator delete[].
1836 //
1837 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1838 // "std" or "bad_alloc" as necessary to form the exception specification.
1839 // However, we do not make these implicit declarations visible to name
1840 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001841 // Note that the C++0x versions of operator delete are deallocation functions,
1842 // and thus are implicitly noexcept.
David Blaikie4e4d0842012-03-11 07:00:24 +00001843 if (!StdBadAlloc && !getLangOpts().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001844 // The "std::bad_alloc" class has not yet been declared, so build it
1845 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001846 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1847 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001848 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001849 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001850 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001851 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001852 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001853
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001854 GlobalNewDeleteDeclared = true;
1855
1856 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1857 QualType SizeT = Context.getSizeType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001858 bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001859
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001860 DeclareGlobalAllocationFunction(
1861 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001862 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001863 DeclareGlobalAllocationFunction(
1864 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001865 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001866 DeclareGlobalAllocationFunction(
1867 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1868 Context.VoidTy, VoidPtr);
1869 DeclareGlobalAllocationFunction(
1870 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1871 Context.VoidTy, VoidPtr);
1872}
1873
1874/// DeclareGlobalAllocationFunction - Declares a single implicit global
1875/// allocation function if it doesn't already exist.
1876void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001877 QualType Return, QualType Argument,
1878 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001879 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1880
1881 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001882 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001883 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001884 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001885 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001886 // Only look at non-template functions, as it is the predefined,
1887 // non-templated allocation function we are trying to declare here.
1888 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1889 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001890 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001891 Func->getParamDecl(0)->getType().getUnqualifiedType());
1892 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001893 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1894 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001895 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001896 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001897 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001898 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001899 }
1900 }
1901
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001902 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001903 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001904 = (Name.getCXXOverloadedOperator() == OO_New ||
1905 Name.getCXXOverloadedOperator() == OO_Array_New);
David Blaikie4e4d0842012-03-11 07:00:24 +00001906 if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001907 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001908 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001909 }
John McCalle23cf432010-12-14 08:05:40 +00001910
1911 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001912 if (HasBadAllocExceptionSpec) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001913 if (!getLangOpts().CPlusPlus0x) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001914 EPI.ExceptionSpecType = EST_Dynamic;
1915 EPI.NumExceptions = 1;
1916 EPI.Exceptions = &BadAllocType;
1917 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001918 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00001919 EPI.ExceptionSpecType = getLangOpts().CPlusPlus0x ?
Sebastian Redl8999fe12011-03-14 18:08:30 +00001920 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001921 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001922
John McCalle23cf432010-12-14 08:05:40 +00001923 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001924 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001925 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1926 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001927 FnType, /*TInfo=*/0, SC_None,
1928 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001929 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001930
Nuno Lopesfc284482009-12-16 16:59:22 +00001931 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001932 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001933
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001934 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001935 SourceLocation(), 0,
1936 Argument, /*TInfo=*/0,
1937 SC_None, SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00001938 Alloc->setParams(Param);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001939
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001940 // FIXME: Also add this declaration to the IdentifierResolver, but
1941 // make sure it is at the end of the chain to coincide with the
1942 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001943 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001944}
1945
Anders Carlsson78f74552009-11-15 18:45:20 +00001946bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1947 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001948 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001949 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001950 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001951 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001952
John McCalla24dc2e2009-11-17 02:14:36 +00001953 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001954 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001955
Chandler Carruth23893242010-06-28 00:30:51 +00001956 Found.suppressDiagnostics();
1957
Chris Lattner5f9e2722011-07-23 10:55:15 +00001958 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001959 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1960 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001961 NamedDecl *ND = (*F)->getUnderlyingDecl();
1962
1963 // Ignore template operator delete members from the check for a usual
1964 // deallocation function.
1965 if (isa<FunctionTemplateDecl>(ND))
1966 continue;
1967
1968 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001969 Matches.push_back(F.getPair());
1970 }
1971
1972 // There's exactly one suitable operator; pick it.
1973 if (Matches.size() == 1) {
1974 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00001975
1976 if (Operator->isDeleted()) {
1977 if (Diagnose) {
1978 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +00001979 NoteDeletedFunction(Operator);
Sean Hunt2be7e902011-05-12 22:46:29 +00001980 }
1981 return true;
1982 }
1983
Richard Smith9a561d52012-02-26 09:11:52 +00001984 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1985 Matches[0], Diagnose) == AR_inaccessible)
1986 return true;
1987
John McCall046a7462010-08-04 00:31:26 +00001988 return false;
1989
1990 // We found multiple suitable operators; complain about the ambiguity.
1991 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001992 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001993 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1994 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001995
Chris Lattner5f9e2722011-07-23 10:55:15 +00001996 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00001997 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1998 Diag((*F)->getUnderlyingDecl()->getLocation(),
1999 diag::note_member_declared_here) << Name;
2000 }
John McCall046a7462010-08-04 00:31:26 +00002001 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00002002 }
2003
2004 // We did find operator delete/operator delete[] declarations, but
2005 // none of them were suitable.
2006 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00002007 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00002008 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2009 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002010
Sean Huntcb45a0f2011-05-12 22:46:25 +00002011 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2012 F != FEnd; ++F)
2013 Diag((*F)->getUnderlyingDecl()->getLocation(),
2014 diag::note_member_declared_here) << Name;
2015 }
Anders Carlsson78f74552009-11-15 18:45:20 +00002016 return true;
2017 }
2018
2019 // Look for a global declaration.
2020 DeclareGlobalNewDelete();
2021 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002022
Anders Carlsson78f74552009-11-15 18:45:20 +00002023 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
2024 Expr* DeallocArgs[1];
2025 DeallocArgs[0] = &Null;
2026 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00002027 DeallocArgs, 1, TUDecl, !Diagnose,
2028 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00002029 return true;
2030
2031 assert(Operator && "Did not find a deallocation function!");
2032 return false;
2033}
2034
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002035/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2036/// @code ::delete ptr; @endcode
2037/// or
2038/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00002039ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002040Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00002041 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002042 // C++ [expr.delete]p1:
2043 // The operand shall have a pointer type, or a class type having a single
2044 // conversion function to a pointer type. The result has type void.
2045 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002046 // DR599 amends "pointer type" to "pointer to object type" in both cases.
2047
John Wiegley429bb272011-04-08 18:41:53 +00002048 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00002049 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002050 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00002051 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002052
John Wiegley429bb272011-04-08 18:41:53 +00002053 if (!Ex.get()->isTypeDependent()) {
John McCall5aba3eb2012-03-09 04:08:29 +00002054 // Perform lvalue-to-rvalue cast, if needed.
2055 Ex = DefaultLvalueConversion(Ex.take());
2056
John Wiegley429bb272011-04-08 18:41:53 +00002057 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002058
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002059 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002060 if (RequireCompleteType(StartLoc, Type,
Douglas Gregord10099e2012-05-04 16:32:21 +00002061 diag::err_delete_incomplete_class_type))
Douglas Gregor254a9422010-07-29 14:44:35 +00002062 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002063
Chris Lattner5f9e2722011-07-23 10:55:15 +00002064 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCall32daa422010-03-31 01:36:47 +00002065
Fariborz Jahanian53462782009-09-11 21:44:33 +00002066 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002067 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002068 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002069 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00002070 NamedDecl *D = I.getDecl();
2071 if (isa<UsingShadowDecl>(D))
2072 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2073
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002074 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00002075 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002076 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002077
John McCall32daa422010-03-31 01:36:47 +00002078 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002079
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002080 QualType ConvType = Conv->getConversionType().getNonReferenceType();
2081 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00002082 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00002083 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002084 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00002085 if (ObjectPtrConversions.size() == 1) {
2086 // We have a single conversion to a pointer-to-object type. Perform
2087 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00002088 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00002089 ExprResult Res =
2090 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00002091 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00002092 AA_Converting);
2093 if (Res.isUsable()) {
2094 Ex = move(Res);
2095 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00002096 }
2097 }
2098 else if (ObjectPtrConversions.size() > 1) {
2099 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002100 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00002101 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
2102 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00002103 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002104 }
Sebastian Redl28507842009-02-26 14:39:58 +00002105 }
2106
Sebastian Redlf53597f2009-03-15 17:47:39 +00002107 if (!Type->isPointerType())
2108 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002109 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00002110
Ted Kremenek6217b802009-07-29 21:53:49 +00002111 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00002112 QualType PointeeElem = Context.getBaseElementType(Pointee);
2113
2114 if (unsigned AddressSpace = Pointee.getAddressSpace())
2115 return Diag(Ex.get()->getLocStart(),
2116 diag::err_address_space_qualified_delete)
2117 << Pointee.getUnqualifiedType() << AddressSpace;
2118
2119 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00002120 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002121 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00002122 // effectively bans deletion of "void*". However, most compilers support
2123 // this, so we treat it as a warning unless we're in a SFINAE context.
2124 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002125 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00002126 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00002127 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002128 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00002129 } else if (!Pointee->isDependentType()) {
2130 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregord10099e2012-05-04 16:32:21 +00002131 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmane52c9142011-07-26 22:25:31 +00002132 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2133 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2134 }
2135 }
2136
Douglas Gregor1070c9f2009-09-29 21:38:53 +00002137 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002138 // [Note: a pointer to a const type can be the operand of a
2139 // delete-expression; it is not necessary to cast away the constness
2140 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00002141 // of the delete-expression. ]
John McCallf85e1932011-06-15 23:02:42 +00002142 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnara30bb4202011-11-16 15:42:13 +00002143 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
2144 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002145
2146 if (Pointee->isArrayType() && !ArrayForm) {
2147 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00002148 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002149 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2150 ArrayForm = true;
2151 }
2152
Anders Carlssond67c4c32009-08-16 20:29:29 +00002153 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2154 ArrayForm ? OO_Array_Delete : OO_Delete);
2155
Eli Friedmane52c9142011-07-26 22:25:31 +00002156 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002157 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00002158 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2159 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00002160 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002161
John McCall6ec278d2011-01-27 09:37:56 +00002162 // If we're allocating an array of records, check whether the
2163 // usual operator delete[] has a size_t parameter.
2164 if (ArrayForm) {
2165 // If the user specifically asked to use the global allocator,
2166 // we'll need to do the lookup into the class.
2167 if (UseGlobal)
2168 UsualArrayDeleteWantsSize =
2169 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2170
2171 // Otherwise, the usual operator delete[] should be the
2172 // function we just found.
2173 else if (isa<CXXMethodDecl>(OperatorDelete))
2174 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2175 }
2176
Richard Smith213d70b2012-02-18 04:13:32 +00002177 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmane52c9142011-07-26 22:25:31 +00002178 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002179 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002180 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00002181 DiagnoseUseOfDecl(Dtor, StartLoc);
2182 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00002183
2184 // C++ [expr.delete]p3:
2185 // In the first alternative (delete object), if the static type of the
2186 // object to be deleted is different from its dynamic type, the static
2187 // type shall be a base class of the dynamic type of the object to be
2188 // deleted and the static type shall have a virtual destructor or the
2189 // behavior is undefined.
2190 //
2191 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00002192 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00002193 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00002194 if (dtor && !dtor->isVirtual()) {
2195 if (PointeeRD->isAbstract()) {
2196 // If the class is abstract, we warn by default, because we're
2197 // sure the code has undefined behavior.
2198 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2199 << PointeeElem;
2200 } else if (!ArrayForm) {
2201 // Otherwise, if this is not an array delete, it's a bit suspect,
2202 // but not necessarily wrong.
2203 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2204 }
2205 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00002206 }
John McCallf85e1932011-06-15 23:02:42 +00002207
David Blaikie4e4d0842012-03-11 07:00:24 +00002208 } else if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002209 PointeeElem->isObjCLifetimeType() &&
2210 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
2211 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
2212 ArrayForm) {
2213 Diag(StartLoc, diag::warn_err_new_delete_object_array)
2214 << 1 << PointeeElem;
Anders Carlssond67c4c32009-08-16 20:29:29 +00002215 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002216
Anders Carlssond67c4c32009-08-16 20:29:29 +00002217 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00002218 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00002219 DeclareGlobalNewDelete();
2220 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00002221 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00002222 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00002223 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00002224 OperatorDelete))
2225 return ExprError();
2226 }
Mike Stump1eb44332009-09-09 15:08:12 +00002227
Eli Friedman5f2987c2012-02-02 03:46:19 +00002228 MarkFunctionReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00002229
Douglas Gregord880f522011-02-01 15:50:11 +00002230 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00002231 if (PointeeRD) {
2232 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00002233 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00002234 PDiag(diag::err_access_dtor) << PointeeElem);
2235 }
2236 }
2237
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002238 }
2239
Sebastian Redlf53597f2009-03-15 17:47:39 +00002240 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00002241 ArrayFormAsWritten,
2242 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00002243 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002244}
2245
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002246/// \brief Check the use of the given variable as a C++ condition in an if,
2247/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00002248ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00002249 SourceLocation StmtLoc,
2250 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002251 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002252
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002253 // C++ [stmt.select]p2:
2254 // The declarator shall not specify a function or an array.
2255 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002256 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002257 diag::err_invalid_use_of_function_type)
2258 << ConditionVar->getSourceRange());
2259 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002260 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002261 diag::err_invalid_use_of_array_type)
2262 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00002263
John Wiegley429bb272011-04-08 18:41:53 +00002264 ExprResult Condition =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002265 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2266 SourceLocation(),
2267 ConditionVar,
John McCallf4b88a42012-03-10 09:33:50 +00002268 /*enclosing*/ false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002269 ConditionVar->getLocation(),
2270 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00002271 VK_LValue));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002272
Eli Friedman5f2987c2012-02-02 03:46:19 +00002273 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002274
John Wiegley429bb272011-04-08 18:41:53 +00002275 if (ConvertToBoolean) {
2276 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2277 if (Condition.isInvalid())
2278 return ExprError();
2279 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002280
John Wiegley429bb272011-04-08 18:41:53 +00002281 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002282}
2283
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002284/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00002285ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002286 // C++ 6.4p4:
2287 // The value of a condition that is an initialized declaration in a statement
2288 // other than a switch statement is the value of the declared variable
2289 // implicitly converted to type bool. If that conversion is ill-formed, the
2290 // program is ill-formed.
2291 // The value of a condition that is an expression is the value of the
2292 // expression, implicitly converted to bool.
2293 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002294 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002295}
Douglas Gregor77a52232008-09-12 00:47:35 +00002296
2297/// Helper function to determine whether this is the (deprecated) C++
2298/// conversion from a string literal to a pointer to non-const char or
2299/// non-const wchar_t (for narrow and wide string literals,
2300/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002301bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002302Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2303 // Look inside the implicit cast, if it exists.
2304 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2305 From = Cast->getSubExpr();
2306
2307 // A string literal (2.13.4) that is not a wide string literal can
2308 // be converted to an rvalue of type "pointer to char"; a wide
2309 // string literal can be converted to an rvalue of type "pointer
2310 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002311 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002312 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002313 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002314 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002315 // This conversion is considered only when there is an
2316 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002317 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2318 switch (StrLit->getKind()) {
2319 case StringLiteral::UTF8:
2320 case StringLiteral::UTF16:
2321 case StringLiteral::UTF32:
2322 // We don't allow UTF literals to be implicitly converted
2323 break;
2324 case StringLiteral::Ascii:
2325 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2326 ToPointeeType->getKind() == BuiltinType::Char_S);
2327 case StringLiteral::Wide:
2328 return ToPointeeType->isWideCharType();
2329 }
2330 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002331 }
2332
2333 return false;
2334}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002335
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002336static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002337 SourceLocation CastLoc,
2338 QualType Ty,
2339 CastKind Kind,
2340 CXXMethodDecl *Method,
John McCallca82a822011-09-21 08:36:56 +00002341 DeclAccessPair FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002342 bool HadMultipleCandidates,
John McCall2de56d12010-08-25 11:45:40 +00002343 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002344 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002345 default: llvm_unreachable("Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002346 case CK_ConstructorConversion: {
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002347 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCallca0408f2010-08-23 06:44:23 +00002348 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002349
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002350 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00002351 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00002352 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002353 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002354
John McCallb9abd8722012-04-07 03:04:20 +00002355 S.CheckConstructorAccess(CastLoc, Constructor,
2356 InitializedEntity::InitializeTemporary(Ty),
2357 Constructor->getAccess());
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002358
2359 ExprResult Result
2360 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2361 move_arg(ConstructorArgs),
2362 HadMultipleCandidates, /*ZeroInit*/ false,
2363 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002364 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002365 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002366
Douglas Gregorba70ab62010-04-16 22:17:36 +00002367 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2368 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002369
John McCall2de56d12010-08-25 11:45:40 +00002370 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002371 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002372
Douglas Gregorba70ab62010-04-16 22:17:36 +00002373 // Create an implicit call expr that calls it.
Eli Friedman3f01c8a2012-03-01 01:30:04 +00002374 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
2375 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002376 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002377 if (Result.isInvalid())
2378 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00002379 // Record usage of conversion in an implicit cast.
2380 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2381 Result.get()->getType(),
2382 CK_UserDefinedConversion,
2383 Result.get(), 0,
2384 Result.get()->getValueKind()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002385
John McCallca82a822011-09-21 08:36:56 +00002386 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2387
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002388 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002389 }
2390 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002391}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002392
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002393/// PerformImplicitConversion - Perform an implicit conversion of the
2394/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002395/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002396/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002397/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002398ExprResult
2399Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002400 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002401 AssignmentAction Action,
2402 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002403 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002404 case ImplicitConversionSequence::StandardConversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002405 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2406 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002407 if (Res.isInvalid())
2408 return ExprError();
2409 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002410 break;
John Wiegley429bb272011-04-08 18:41:53 +00002411 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002412
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002413 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002414
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002415 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002416 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002417 QualType BeforeToType;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002418 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002419 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002420 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002421
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002422 // If the user-defined conversion is specified by a conversion function,
2423 // the initial standard conversion sequence converts the source type to
2424 // the implicit object parameter of the conversion function.
2425 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002426 } else {
2427 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002428 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002429 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002430 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002431 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002432 // initial standard conversion sequence converts the source type to the
2433 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002434 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2435 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002436 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00002437 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002438 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002439 ExprResult Res =
Richard Smithc8d7f582011-11-29 22:48:16 +00002440 PerformImplicitConversion(From, BeforeToType,
2441 ICS.UserDefined.Before, AA_Converting,
2442 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002443 if (Res.isInvalid())
2444 return ExprError();
2445 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002446 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002447
2448 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002449 = BuildCXXCastArgument(*this,
2450 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002451 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002452 CastKind, cast<CXXMethodDecl>(FD),
2453 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002454 ICS.UserDefined.HadMultipleCandidates,
John McCall9ae2f072010-08-23 23:25:46 +00002455 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002456
2457 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002458 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002459
John Wiegley429bb272011-04-08 18:41:53 +00002460 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002461
Richard Smithc8d7f582011-11-29 22:48:16 +00002462 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2463 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002464 }
John McCall1d318332010-01-12 00:44:57 +00002465
2466 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002467 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002468 PDiag(diag::err_typecheck_ambiguous_condition)
2469 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002470 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002471
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002472 case ImplicitConversionSequence::EllipsisConversion:
David Blaikieb219cfc2011-09-23 05:06:16 +00002473 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002474
2475 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002476 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002477 }
2478
2479 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002480 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002481}
2482
Richard Smithc8d7f582011-11-29 22:48:16 +00002483/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002484/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002485/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002486/// expression. Flavor is the context in which we're performing this
2487/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002488ExprResult
Richard Smithc8d7f582011-11-29 22:48:16 +00002489Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002490 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002491 AssignmentAction Action,
2492 CheckedConversionKind CCK) {
2493 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2494
Mike Stump390b4cc2009-05-16 07:39:55 +00002495 // Overall FIXME: we are recomputing too many types here and doing far too
2496 // much extra work. What this means is that we need to keep track of more
2497 // information that is computed when we try the implicit conversion initially,
2498 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002499 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002500
Douglas Gregor225c41e2008-11-03 19:09:14 +00002501 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002502 // FIXME: When can ToType be a reference type?
2503 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002504 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002505 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002506 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002507 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002508 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002509 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002510 return ExprError();
2511 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2512 ToType, SCS.CopyConstructor,
2513 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002514 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002515 /*ZeroInit*/ false,
2516 CXXConstructExpr::CK_Complete,
2517 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002518 }
John Wiegley429bb272011-04-08 18:41:53 +00002519 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2520 ToType, SCS.CopyConstructor,
2521 MultiExprArg(*this, &From, 1),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002522 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002523 /*ZeroInit*/ false,
2524 CXXConstructExpr::CK_Complete,
2525 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002526 }
2527
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002528 // Resolve overloaded function references.
2529 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2530 DeclAccessPair Found;
2531 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2532 true, Found);
2533 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002534 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002535
Daniel Dunbar96a00142012-03-09 18:35:03 +00002536 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley429bb272011-04-08 18:41:53 +00002537 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002538
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002539 From = FixOverloadedFunctionReference(From, Found, Fn);
2540 FromType = From->getType();
2541 }
2542
Richard Smithc8d7f582011-11-29 22:48:16 +00002543 // Perform the first implicit conversion.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002544 switch (SCS.First) {
2545 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002546 // Nothing to do.
2547 break;
2548
Eli Friedmand814eaf2012-01-24 22:51:26 +00002549 case ICK_Lvalue_To_Rvalue: {
John McCall3c3b7f92011-10-25 17:37:35 +00002550 assert(From->getObjectKind() != OK_ObjCProperty);
John McCallf6a16482010-12-04 03:47:34 +00002551 FromType = FromType.getUnqualifiedType();
Eli Friedmand814eaf2012-01-24 22:51:26 +00002552 ExprResult FromRes = DefaultLvalueConversion(From);
2553 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2554 From = FromRes.take();
John McCallf6a16482010-12-04 03:47:34 +00002555 break;
Eli Friedmand814eaf2012-01-24 22:51:26 +00002556 }
John McCallf6a16482010-12-04 03:47:34 +00002557
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002558 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002559 FromType = Context.getArrayDecayedType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002560 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2561 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002562 break;
2563
2564 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002565 FromType = Context.getPointerType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002566 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2567 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002568 break;
2569
2570 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002571 llvm_unreachable("Improper first standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002572 }
2573
Richard Smithc8d7f582011-11-29 22:48:16 +00002574 // Perform the second implicit conversion
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002575 switch (SCS.Second) {
2576 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002577 // If both sides are functions (or pointers/references to them), there could
2578 // be incompatible exception declarations.
2579 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002580 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002581 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002582 break;
2583
Douglas Gregor43c79c22009-12-09 00:47:37 +00002584 case ICK_NoReturn_Adjustment:
2585 // If both sides are functions (or pointers/references to them), there could
2586 // be incompatible exception declarations.
2587 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002588 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002589
Richard Smithc8d7f582011-11-29 22:48:16 +00002590 From = ImpCastExprToType(From, ToType, CK_NoOp,
2591 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002592 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002593
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002594 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002595 case ICK_Integral_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002596 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2597 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002598 break;
2599
2600 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002601 case ICK_Floating_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002602 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2603 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002604 break;
2605
2606 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002607 case ICK_Complex_Conversion: {
2608 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2609 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2610 CastKind CK;
2611 if (FromEl->isRealFloatingType()) {
2612 if (ToEl->isRealFloatingType())
2613 CK = CK_FloatingComplexCast;
2614 else
2615 CK = CK_FloatingComplexToIntegralComplex;
2616 } else if (ToEl->isRealFloatingType()) {
2617 CK = CK_IntegralComplexToFloatingComplex;
2618 } else {
2619 CK = CK_IntegralComplexCast;
2620 }
Richard Smithc8d7f582011-11-29 22:48:16 +00002621 From = ImpCastExprToType(From, ToType, CK,
2622 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002623 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002624 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002625
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002626 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002627 if (ToType->isRealFloatingType())
Richard Smithc8d7f582011-11-29 22:48:16 +00002628 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2629 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002630 else
Richard Smithc8d7f582011-11-29 22:48:16 +00002631 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2632 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002633 break;
2634
Douglas Gregorf9201e02009-02-11 23:02:49 +00002635 case ICK_Compatible_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002636 From = ImpCastExprToType(From, ToType, CK_NoOp,
2637 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002638 break;
2639
John McCallf85e1932011-06-15 23:02:42 +00002640 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002641 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002642 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002643 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002644 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002645 Diag(From->getLocStart(),
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002646 diag::ext_typecheck_convert_incompatible_pointer)
2647 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002648 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002649 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00002650 Diag(From->getLocStart(),
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002651 diag::ext_typecheck_convert_incompatible_pointer)
2652 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002653 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002654
Douglas Gregor926df6c2011-06-11 01:09:30 +00002655 if (From->getType()->isObjCObjectPointerType() &&
2656 ToType->isObjCObjectPointerType())
2657 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002658 }
David Blaikie4e4d0842012-03-11 07:00:24 +00002659 else if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002660 !CheckObjCARCUnavailableWeakConversion(ToType,
2661 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002662 if (Action == AA_Initializing)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002663 Diag(From->getLocStart(),
John McCall7f3a6d32011-09-09 06:12:06 +00002664 diag::err_arc_weak_unavailable_assign);
2665 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00002666 Diag(From->getLocStart(),
John McCall7f3a6d32011-09-09 06:12:06 +00002667 diag::err_arc_convesion_of_weak_unavailable)
2668 << (Action == AA_Casting) << From->getType() << ToType
2669 << From->getSourceRange();
2670 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002671
John McCalldaa8e4e2010-11-15 09:13:47 +00002672 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002673 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002674 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002675 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002676
2677 // Make sure we extend blocks if necessary.
2678 // FIXME: doing this here is really ugly.
2679 if (Kind == CK_BlockPointerToObjCPointerCast) {
2680 ExprResult E = From;
2681 (void) PrepareCastToObjCObjectPointer(E);
2682 From = E.take();
2683 }
2684
Richard Smithc8d7f582011-11-29 22:48:16 +00002685 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2686 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002687 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002688 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002689
Anders Carlsson61faec12009-09-12 04:46:44 +00002690 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002691 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002692 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002693 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002694 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002695 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002696 return ExprError();
Richard Smithc8d7f582011-11-29 22:48:16 +00002697 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2698 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002699 break;
2700 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002701
Abramo Bagnara737d5442011-04-07 09:26:19 +00002702 case ICK_Boolean_Conversion:
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002703 // Perform half-to-boolean conversion via float.
2704 if (From->getType()->isHalfType()) {
2705 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2706 FromType = Context.FloatTy;
2707 }
2708
Richard Smithc8d7f582011-11-29 22:48:16 +00002709 From = ImpCastExprToType(From, Context.BoolTy,
2710 ScalarTypeToBooleanCastKind(FromType),
2711 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002712 break;
2713
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002714 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002715 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002716 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002717 ToType.getNonReferenceType(),
2718 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002719 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002720 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002721 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002722 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002723
Richard Smithc8d7f582011-11-29 22:48:16 +00002724 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2725 CK_DerivedToBase, From->getValueKind(),
2726 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002727 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002728 }
2729
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002730 case ICK_Vector_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002731 From = ImpCastExprToType(From, ToType, CK_BitCast,
2732 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002733 break;
2734
2735 case ICK_Vector_Splat:
Richard Smithc8d7f582011-11-29 22:48:16 +00002736 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2737 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002738 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002739
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002740 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002741 // Case 1. x -> _Complex y
2742 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2743 QualType ElType = ToComplex->getElementType();
2744 bool isFloatingComplex = ElType->isRealFloatingType();
2745
2746 // x -> y
2747 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2748 // do nothing
2749 } else if (From->getType()->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002750 From = ImpCastExprToType(From, ElType,
2751 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002752 } else {
2753 assert(From->getType()->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002754 From = ImpCastExprToType(From, ElType,
2755 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002756 }
2757 // y -> _Complex y
Richard Smithc8d7f582011-11-29 22:48:16 +00002758 From = ImpCastExprToType(From, ToType,
2759 isFloatingComplex ? CK_FloatingRealToComplex
2760 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002761
2762 // Case 2. _Complex x -> y
2763 } else {
2764 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2765 assert(FromComplex);
2766
2767 QualType ElType = FromComplex->getElementType();
2768 bool isFloatingComplex = ElType->isRealFloatingType();
2769
2770 // _Complex x -> x
Richard Smithc8d7f582011-11-29 22:48:16 +00002771 From = ImpCastExprToType(From, ElType,
2772 isFloatingComplex ? CK_FloatingComplexToReal
2773 : CK_IntegralComplexToReal,
2774 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002775
2776 // x -> y
2777 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2778 // do nothing
2779 } else if (ToType->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002780 From = ImpCastExprToType(From, ToType,
2781 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2782 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002783 } else {
2784 assert(ToType->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002785 From = ImpCastExprToType(From, ToType,
2786 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2787 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002788 }
2789 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002790 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002791
2792 case ICK_Block_Pointer_Conversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002793 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2794 VK_RValue, /*BasePath=*/0, CCK).take();
John McCallf85e1932011-06-15 23:02:42 +00002795 break;
2796 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002797
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002798 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002799 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002800 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002801 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2802 if (FromRes.isInvalid())
2803 return ExprError();
2804 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002805 assert ((ConvTy == Sema::Compatible) &&
2806 "Improper transparent union conversion");
2807 (void)ConvTy;
2808 break;
2809 }
2810
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002811 case ICK_Lvalue_To_Rvalue:
2812 case ICK_Array_To_Pointer:
2813 case ICK_Function_To_Pointer:
2814 case ICK_Qualification:
2815 case ICK_Num_Conversion_Kinds:
David Blaikieb219cfc2011-09-23 05:06:16 +00002816 llvm_unreachable("Improper second standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002817 }
2818
2819 switch (SCS.Third) {
2820 case ICK_Identity:
2821 // Nothing to do.
2822 break;
2823
Sebastian Redl906082e2010-07-20 04:20:21 +00002824 case ICK_Qualification: {
2825 // The qualification keeps the category of the inner expression, unless the
2826 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002827 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002828 From->getValueKind() : VK_RValue;
Richard Smithc8d7f582011-11-29 22:48:16 +00002829 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2830 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002831
Douglas Gregor069a6da2011-03-14 16:13:32 +00002832 if (SCS.DeprecatedStringLiteralToCharPtr &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002833 !getLangOpts().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002834 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2835 << ToType.getNonReferenceType();
2836
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002837 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002838 }
2839
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002840 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002841 llvm_unreachable("Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002842 }
2843
Douglas Gregor47bfcca2012-04-12 20:42:30 +00002844 // If this conversion sequence involved a scalar -> atomic conversion, perform
2845 // that conversion now.
2846 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>())
2847 if (Context.hasSameType(ToAtomic->getValueType(), From->getType()))
2848 From = ImpCastExprToType(From, ToType, CK_NonAtomicToAtomic, VK_RValue, 0,
2849 CCK).take();
2850
John Wiegley429bb272011-04-08 18:41:53 +00002851 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002852}
2853
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002854ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002855 SourceLocation KWLoc,
2856 ParsedType Ty,
2857 SourceLocation RParen) {
2858 TypeSourceInfo *TSInfo;
2859 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002860
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002861 if (!TSInfo)
2862 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002863 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002864}
2865
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002866/// \brief Check the completeness of a type in a unary type trait.
2867///
2868/// If the particular type trait requires a complete type, tries to complete
2869/// it. If completing the type fails, a diagnostic is emitted and false
2870/// returned. If completing the type succeeds or no completion was required,
2871/// returns true.
2872static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2873 UnaryTypeTrait UTT,
2874 SourceLocation Loc,
2875 QualType ArgTy) {
2876 // C++0x [meta.unary.prop]p3:
2877 // For all of the class templates X declared in this Clause, instantiating
2878 // that template with a template argument that is a class template
2879 // specialization may result in the implicit instantiation of the template
2880 // argument if and only if the semantics of X require that the argument
2881 // must be a complete type.
2882 // We apply this rule to all the type trait expressions used to implement
2883 // these class templates. We also try to follow any GCC documented behavior
2884 // in these expressions to ensure portability of standard libraries.
2885 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002886 // is_complete_type somewhat obviously cannot require a complete type.
2887 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002888 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002889
2890 // These traits are modeled on the type predicates in C++0x
2891 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2892 // requiring a complete type, as whether or not they return true cannot be
2893 // impacted by the completeness of the type.
2894 case UTT_IsVoid:
2895 case UTT_IsIntegral:
2896 case UTT_IsFloatingPoint:
2897 case UTT_IsArray:
2898 case UTT_IsPointer:
2899 case UTT_IsLvalueReference:
2900 case UTT_IsRvalueReference:
2901 case UTT_IsMemberFunctionPointer:
2902 case UTT_IsMemberObjectPointer:
2903 case UTT_IsEnum:
2904 case UTT_IsUnion:
2905 case UTT_IsClass:
2906 case UTT_IsFunction:
2907 case UTT_IsReference:
2908 case UTT_IsArithmetic:
2909 case UTT_IsFundamental:
2910 case UTT_IsObject:
2911 case UTT_IsScalar:
2912 case UTT_IsCompound:
2913 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002914 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002915
2916 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2917 // which requires some of its traits to have the complete type. However,
2918 // the completeness of the type cannot impact these traits' semantics, and
2919 // so they don't require it. This matches the comments on these traits in
2920 // Table 49.
2921 case UTT_IsConst:
2922 case UTT_IsVolatile:
2923 case UTT_IsSigned:
2924 case UTT_IsUnsigned:
2925 return true;
2926
2927 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002928 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002929 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00002930 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002931 case UTT_IsStandardLayout:
2932 case UTT_IsPOD:
2933 case UTT_IsLiteral:
2934 case UTT_IsEmpty:
2935 case UTT_IsPolymorphic:
2936 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002937 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002938
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002939 // These traits require a complete type.
2940 case UTT_IsFinal:
2941
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002942 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002943 // [meta.unary.prop] despite not being named the same. They are specified
2944 // by both GCC and the Embarcadero C++ compiler, and require the complete
2945 // type due to the overarching C++0x type predicates being implemented
2946 // requiring the complete type.
2947 case UTT_HasNothrowAssign:
2948 case UTT_HasNothrowConstructor:
2949 case UTT_HasNothrowCopy:
2950 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002951 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002952 case UTT_HasTrivialCopy:
2953 case UTT_HasTrivialDestructor:
2954 case UTT_HasVirtualDestructor:
2955 // Arrays of unknown bound are expressly allowed.
2956 QualType ElTy = ArgTy;
2957 if (ArgTy->isIncompleteArrayType())
2958 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2959
2960 // The void type is expressly allowed.
2961 if (ElTy->isVoidType())
2962 return true;
2963
2964 return !S.RequireCompleteType(
2965 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002966 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002967 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002968}
2969
2970static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2971 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002972 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002973
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002974 ASTContext &C = Self.Context;
2975 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002976 // Type trait expressions corresponding to the primary type category
2977 // predicates in C++0x [meta.unary.cat].
2978 case UTT_IsVoid:
2979 return T->isVoidType();
2980 case UTT_IsIntegral:
2981 return T->isIntegralType(C);
2982 case UTT_IsFloatingPoint:
2983 return T->isFloatingType();
2984 case UTT_IsArray:
2985 return T->isArrayType();
2986 case UTT_IsPointer:
2987 return T->isPointerType();
2988 case UTT_IsLvalueReference:
2989 return T->isLValueReferenceType();
2990 case UTT_IsRvalueReference:
2991 return T->isRValueReferenceType();
2992 case UTT_IsMemberFunctionPointer:
2993 return T->isMemberFunctionPointerType();
2994 case UTT_IsMemberObjectPointer:
2995 return T->isMemberDataPointerType();
2996 case UTT_IsEnum:
2997 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00002998 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002999 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003000 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00003001 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003002 case UTT_IsFunction:
3003 return T->isFunctionType();
3004
3005 // Type trait expressions which correspond to the convenient composition
3006 // predicates in C++0x [meta.unary.comp].
3007 case UTT_IsReference:
3008 return T->isReferenceType();
3009 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00003010 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003011 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00003012 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003013 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00003014 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003015 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00003016 // Note: semantic analysis depends on Objective-C lifetime types to be
3017 // considered scalar types. However, such types do not actually behave
3018 // like scalar types at run time (since they may require retain/release
3019 // operations), so we report them as non-scalar.
3020 if (T->isObjCLifetimeType()) {
3021 switch (T.getObjCLifetime()) {
3022 case Qualifiers::OCL_None:
3023 case Qualifiers::OCL_ExplicitNone:
3024 return true;
3025
3026 case Qualifiers::OCL_Strong:
3027 case Qualifiers::OCL_Weak:
3028 case Qualifiers::OCL_Autoreleasing:
3029 return false;
3030 }
3031 }
3032
Chandler Carruthcec0ced2011-05-01 09:29:55 +00003033 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003034 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00003035 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003036 case UTT_IsMemberPointer:
3037 return T->isMemberPointerType();
3038
3039 // Type trait expressions which correspond to the type property predicates
3040 // in C++0x [meta.unary.prop].
3041 case UTT_IsConst:
3042 return T.isConstQualified();
3043 case UTT_IsVolatile:
3044 return T.isVolatileQualified();
3045 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00003046 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00003047 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00003048 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003049 case UTT_IsStandardLayout:
3050 return T->isStandardLayoutType();
3051 case UTT_IsPOD:
Benjamin Kramer470360d2012-04-28 10:00:33 +00003052 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003053 case UTT_IsLiteral:
3054 return T->isLiteralType();
3055 case UTT_IsEmpty:
3056 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3057 return !RD->isUnion() && RD->isEmpty();
3058 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003059 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00003060 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3061 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003062 return false;
3063 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00003064 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3065 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003066 return false;
Douglas Gregor5e9392b2011-12-03 18:14:24 +00003067 case UTT_IsFinal:
3068 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3069 return RD->hasAttr<FinalAttr>();
3070 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00003071 case UTT_IsSigned:
3072 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00003073 case UTT_IsUnsigned:
3074 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003075
3076 // Type trait expressions which query classes regarding their construction,
3077 // destruction, and copying. Rather than being based directly on the
3078 // related type predicates in the standard, they are specified by both
3079 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3080 // specifications.
3081 //
3082 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3083 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00003084 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003085 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3086 // If __is_pod (type) is true then the trait is true, else if type is
3087 // a cv class or union type (or array thereof) with a trivial default
3088 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003089 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003090 return true;
3091 if (const RecordType *RT =
3092 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00003093 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003094 return false;
3095 case UTT_HasTrivialCopy:
3096 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3097 // If __is_pod (type) is true or type is a reference type then
3098 // the trait is true, else if type is a cv class or union type
3099 // with a trivial copy constructor ([class.copy]) then the trait
3100 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003101 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003102 return true;
3103 if (const RecordType *RT = T->getAs<RecordType>())
3104 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
3105 return false;
3106 case UTT_HasTrivialAssign:
3107 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3108 // If type is const qualified or is a reference type then the
3109 // trait is false. Otherwise if __is_pod (type) is true then the
3110 // trait is true, else if type is a cv class or union type with
3111 // a trivial copy assignment ([class.copy]) then the trait is
3112 // true, else it is false.
3113 // Note: the const and reference restrictions are interesting,
3114 // given that const and reference members don't prevent a class
3115 // from having a trivial copy assignment operator (but do cause
3116 // errors if the copy assignment operator is actually used, q.v.
3117 // [class.copy]p12).
3118
3119 if (C.getBaseElementType(T).isConstQualified())
3120 return false;
John McCallf85e1932011-06-15 23:02:42 +00003121 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003122 return true;
3123 if (const RecordType *RT = T->getAs<RecordType>())
3124 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
3125 return false;
3126 case UTT_HasTrivialDestructor:
3127 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3128 // If __is_pod (type) is true or type is a reference type
3129 // then the trait is true, else if type is a cv class or union
3130 // type (or array thereof) with a trivial destructor
3131 // ([class.dtor]) then the trait is true, else it is
3132 // false.
John McCallf85e1932011-06-15 23:02:42 +00003133 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003134 return true;
John McCallf85e1932011-06-15 23:02:42 +00003135
3136 // Objective-C++ ARC: autorelease types don't require destruction.
3137 if (T->isObjCLifetimeType() &&
3138 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3139 return true;
3140
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003141 if (const RecordType *RT =
3142 C.getBaseElementType(T)->getAs<RecordType>())
3143 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
3144 return false;
3145 // TODO: Propagate nothrowness for implicitly declared special members.
3146 case UTT_HasNothrowAssign:
3147 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3148 // If type is const qualified or is a reference type then the
3149 // trait is false. Otherwise if __has_trivial_assign (type)
3150 // is true then the trait is true, else if type is a cv class
3151 // or union type with copy assignment operators that are known
3152 // not to throw an exception then the trait is true, else it is
3153 // false.
3154 if (C.getBaseElementType(T).isConstQualified())
3155 return false;
3156 if (T->isReferenceType())
3157 return false;
John McCallf85e1932011-06-15 23:02:42 +00003158 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
3159 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003160 if (const RecordType *RT = T->getAs<RecordType>()) {
3161 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
3162 if (RD->hasTrivialCopyAssignment())
3163 return true;
3164
3165 bool FoundAssign = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003166 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00003167 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
3168 Sema::LookupOrdinaryName);
3169 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregord41679d2011-10-12 15:40:49 +00003170 Res.suppressDiagnostics();
Sebastian Redlf8aca862010-09-14 23:40:14 +00003171 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3172 Op != OpEnd; ++Op) {
Douglas Gregord41679d2011-10-12 15:40:49 +00003173 if (isa<FunctionTemplateDecl>(*Op))
3174 continue;
3175
Sebastian Redlf8aca862010-09-14 23:40:14 +00003176 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3177 if (Operator->isCopyAssignmentOperator()) {
3178 FoundAssign = true;
3179 const FunctionProtoType *CPT
3180 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +00003181 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3182 if (!CPT)
3183 return false;
Richard Smith7a614d82011-06-11 17:19:42 +00003184 if (CPT->getExceptionSpecType() == EST_Delayed)
3185 return false;
3186 if (!CPT->isNothrow(Self.Context))
3187 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003188 }
3189 }
3190 }
Douglas Gregord41679d2011-10-12 15:40:49 +00003191
Richard Smith7a614d82011-06-11 17:19:42 +00003192 return FoundAssign;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003193 }
3194 return false;
3195 case UTT_HasNothrowCopy:
3196 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3197 // If __has_trivial_copy (type) is true then the trait is true, else
3198 // if type is a cv class or union type with copy constructors that are
3199 // known not to throw an exception then the trait is true, else it is
3200 // false.
John McCallf85e1932011-06-15 23:02:42 +00003201 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003202 return true;
3203 if (const RecordType *RT = T->getAs<RecordType>()) {
3204 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3205 if (RD->hasTrivialCopyConstructor())
3206 return true;
3207
3208 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003209 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003210 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00003211 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003212 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003213 // A template constructor is never a copy constructor.
3214 // FIXME: However, it may actually be selected at the actual overload
3215 // resolution point.
3216 if (isa<FunctionTemplateDecl>(*Con))
3217 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003218 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3219 if (Constructor->isCopyConstructor(FoundTQs)) {
3220 FoundConstructor = true;
3221 const FunctionProtoType *CPT
3222 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +00003223 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3224 if (!CPT)
3225 return false;
Richard Smith7a614d82011-06-11 17:19:42 +00003226 if (CPT->getExceptionSpecType() == EST_Delayed)
3227 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003228 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00003229 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00003230 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3231 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003232 }
3233 }
3234
Richard Smith7a614d82011-06-11 17:19:42 +00003235 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003236 }
3237 return false;
3238 case UTT_HasNothrowConstructor:
3239 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3240 // If __has_trivial_constructor (type) is true then the trait is
3241 // true, else if type is a cv class or union type (or array
3242 // thereof) with a default constructor that is known not to
3243 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003244 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003245 return true;
3246 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3247 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00003248 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003249 return true;
3250
Sebastian Redl751025d2010-09-13 22:02:47 +00003251 DeclContext::lookup_const_iterator Con, ConEnd;
3252 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3253 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003254 // FIXME: In C++0x, a constructor template can be a default constructor.
3255 if (isa<FunctionTemplateDecl>(*Con))
3256 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00003257 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3258 if (Constructor->isDefaultConstructor()) {
3259 const FunctionProtoType *CPT
3260 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +00003261 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3262 if (!CPT)
3263 return false;
Richard Smith7a614d82011-06-11 17:19:42 +00003264 if (CPT->getExceptionSpecType() == EST_Delayed)
3265 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00003266 // TODO: check whether evaluating default arguments can throw.
3267 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003268 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00003269 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003270 }
3271 }
3272 return false;
3273 case UTT_HasVirtualDestructor:
3274 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3275 // If type is a class type with a virtual destructor ([class.dtor])
3276 // then the trait is true, else it is false.
3277 if (const RecordType *Record = T->getAs<RecordType>()) {
3278 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00003279 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003280 return Destructor->isVirtual();
3281 }
3282 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003283
3284 // These type trait expressions are modeled on the specifications for the
3285 // Embarcadero C++0x type trait functions:
3286 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3287 case UTT_IsCompleteType:
3288 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3289 // Returns True if and only if T is a complete type at the point of the
3290 // function call.
3291 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003292 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00003293 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003294}
3295
3296ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00003297 SourceLocation KWLoc,
3298 TypeSourceInfo *TSInfo,
3299 SourceLocation RParen) {
3300 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00003301 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3302 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00003303
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003304 bool Value = false;
3305 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003306 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003307
3308 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00003309 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00003310}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003311
Francois Pichet6ad6f282010-12-07 00:08:36 +00003312ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3313 SourceLocation KWLoc,
3314 ParsedType LhsTy,
3315 ParsedType RhsTy,
3316 SourceLocation RParen) {
3317 TypeSourceInfo *LhsTSInfo;
3318 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3319 if (!LhsTSInfo)
3320 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3321
3322 TypeSourceInfo *RhsTSInfo;
3323 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3324 if (!RhsTSInfo)
3325 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3326
3327 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3328}
3329
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003330static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3331 ArrayRef<TypeSourceInfo *> Args,
3332 SourceLocation RParenLoc) {
3333 switch (Kind) {
3334 case clang::TT_IsTriviallyConstructible: {
3335 // C++11 [meta.unary.prop]:
Dmitri Gribenko62348f02012-02-24 20:03:35 +00003336 // is_trivially_constructible is defined as:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003337 //
Dmitri Gribenko62348f02012-02-24 20:03:35 +00003338 // is_constructible<T, Args...>::value is true and the variable
3339 // definition for is_constructible, as defined below, is known to call no
3340 // operation that is not trivial.
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003341 //
3342 // The predicate condition for a template specialization
3343 // is_constructible<T, Args...> shall be satisfied if and only if the
3344 // following variable definition would be well-formed for some invented
3345 // variable t:
3346 //
3347 // T t(create<Args>()...);
3348 if (Args.empty()) {
3349 S.Diag(KWLoc, diag::err_type_trait_arity)
3350 << 1 << 1 << 1 << (int)Args.size();
3351 return false;
3352 }
3353
3354 bool SawVoid = false;
3355 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3356 if (Args[I]->getType()->isVoidType()) {
3357 SawVoid = true;
3358 continue;
3359 }
3360
3361 if (!Args[I]->getType()->isIncompleteType() &&
3362 S.RequireCompleteType(KWLoc, Args[I]->getType(),
3363 diag::err_incomplete_type_used_in_type_trait_expr))
3364 return false;
3365 }
3366
3367 // If any argument was 'void', of course it won't type-check.
3368 if (SawVoid)
3369 return false;
3370
3371 llvm::SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3372 llvm::SmallVector<Expr *, 2> ArgExprs;
3373 ArgExprs.reserve(Args.size() - 1);
3374 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3375 QualType T = Args[I]->getType();
3376 if (T->isObjectType() || T->isFunctionType())
3377 T = S.Context.getRValueReferenceType(T);
3378 OpaqueArgExprs.push_back(
Daniel Dunbar96a00142012-03-09 18:35:03 +00003379 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003380 T.getNonLValueExprType(S.Context),
3381 Expr::getValueKindForType(T)));
3382 ArgExprs.push_back(&OpaqueArgExprs.back());
3383 }
3384
3385 // Perform the initialization in an unevaluated context within a SFINAE
3386 // trap at translation unit scope.
3387 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3388 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3389 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3390 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3391 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3392 RParenLoc));
3393 InitializationSequence Init(S, To, InitKind,
3394 ArgExprs.begin(), ArgExprs.size());
3395 if (Init.Failed())
3396 return false;
3397
3398 ExprResult Result = Init.Perform(S, To, InitKind,
3399 MultiExprArg(ArgExprs.data(),
3400 ArgExprs.size()));
3401 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3402 return false;
3403
3404 // The initialization succeeded; not make sure there are no non-trivial
3405 // calls.
3406 return !Result.get()->hasNonTrivialCall(S.Context);
3407 }
3408 }
3409
3410 return false;
3411}
3412
3413ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3414 ArrayRef<TypeSourceInfo *> Args,
3415 SourceLocation RParenLoc) {
3416 bool Dependent = false;
3417 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3418 if (Args[I]->getType()->isDependentType()) {
3419 Dependent = true;
3420 break;
3421 }
3422 }
3423
3424 bool Value = false;
3425 if (!Dependent)
3426 Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3427
3428 return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind,
3429 Args, RParenLoc, Value);
3430}
3431
3432ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3433 ArrayRef<ParsedType> Args,
3434 SourceLocation RParenLoc) {
3435 llvm::SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
3436 ConvertedArgs.reserve(Args.size());
3437
3438 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3439 TypeSourceInfo *TInfo;
3440 QualType T = GetTypeFromParser(Args[I], &TInfo);
3441 if (!TInfo)
3442 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3443
3444 ConvertedArgs.push_back(TInfo);
3445 }
3446
3447 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3448}
3449
Francois Pichet6ad6f282010-12-07 00:08:36 +00003450static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3451 QualType LhsT, QualType RhsT,
3452 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003453 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3454 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003455
3456 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003457 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003458 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003459 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003460 // Base and Derived are not unions and name the same class type without
3461 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003462
John McCalld89d30f2011-01-28 22:02:36 +00003463 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3464 if (!lhsRecord) return false;
3465
3466 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3467 if (!rhsRecord) return false;
3468
3469 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3470 == (lhsRecord == rhsRecord));
3471
3472 if (lhsRecord == rhsRecord)
3473 return !lhsRecord->getDecl()->isUnion();
3474
3475 // C++0x [meta.rel]p2:
3476 // If Base and Derived are class types and are different types
3477 // (ignoring possible cv-qualifiers) then Derived shall be a
3478 // complete type.
3479 if (Self.RequireCompleteType(KeyLoc, RhsT,
3480 diag::err_incomplete_type_used_in_type_trait_expr))
3481 return false;
3482
3483 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3484 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3485 }
John Wiegley20c0da72011-04-27 23:09:49 +00003486 case BTT_IsSame:
3487 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003488 case BTT_TypeCompatible:
3489 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3490 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003491 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003492 case BTT_IsConvertibleTo: {
3493 // C++0x [meta.rel]p4:
3494 // Given the following function prototype:
3495 //
3496 // template <class T>
3497 // typename add_rvalue_reference<T>::type create();
3498 //
3499 // the predicate condition for a template specialization
3500 // is_convertible<From, To> shall be satisfied if and only if
3501 // the return expression in the following code would be
3502 // well-formed, including any implicit conversions to the return
3503 // type of the function:
3504 //
3505 // To test() {
3506 // return create<From>();
3507 // }
3508 //
3509 // Access checking is performed as if in a context unrelated to To and
3510 // From. Only the validity of the immediate context of the expression
3511 // of the return-statement (including conversions to the return type)
3512 // is considered.
3513 //
3514 // We model the initialization as a copy-initialization of a temporary
3515 // of the appropriate type, which for this expression is identical to the
3516 // return statement (since NRVO doesn't apply).
3517 if (LhsT->isObjectType() || LhsT->isFunctionType())
3518 LhsT = Self.Context.getRValueReferenceType(LhsT);
3519
3520 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003521 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003522 Expr::getValueKindForType(LhsT));
3523 Expr *FromPtr = &From;
3524 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3525 SourceLocation()));
3526
Eli Friedman3add9f02012-01-25 01:05:57 +00003527 // Perform the initialization in an unevaluated context within a SFINAE
3528 // trap at translation unit scope.
3529 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003530 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3531 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00003532 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003533 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003534 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003535
Douglas Gregor9f361132011-01-27 20:28:01 +00003536 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3537 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3538 }
Douglas Gregor25d0a0f2012-02-23 07:33:15 +00003539
3540 case BTT_IsTriviallyAssignable: {
3541 // C++11 [meta.unary.prop]p3:
3542 // is_trivially_assignable is defined as:
3543 // is_assignable<T, U>::value is true and the assignment, as defined by
3544 // is_assignable, is known to call no operation that is not trivial
3545 //
3546 // is_assignable is defined as:
3547 // The expression declval<T>() = declval<U>() is well-formed when
3548 // treated as an unevaluated operand (Clause 5).
3549 //
3550 // For both, T and U shall be complete types, (possibly cv-qualified)
3551 // void, or arrays of unknown bound.
3552 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3553 Self.RequireCompleteType(KeyLoc, LhsT,
3554 diag::err_incomplete_type_used_in_type_trait_expr))
3555 return false;
3556 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3557 Self.RequireCompleteType(KeyLoc, RhsT,
3558 diag::err_incomplete_type_used_in_type_trait_expr))
3559 return false;
3560
3561 // cv void is never assignable.
3562 if (LhsT->isVoidType() || RhsT->isVoidType())
3563 return false;
3564
3565 // Build expressions that emulate the effect of declval<T>() and
3566 // declval<U>().
3567 if (LhsT->isObjectType() || LhsT->isFunctionType())
3568 LhsT = Self.Context.getRValueReferenceType(LhsT);
3569 if (RhsT->isObjectType() || RhsT->isFunctionType())
3570 RhsT = Self.Context.getRValueReferenceType(RhsT);
3571 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3572 Expr::getValueKindForType(LhsT));
3573 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3574 Expr::getValueKindForType(RhsT));
3575
3576 // Attempt the assignment in an unevaluated context within a SFINAE
3577 // trap at translation unit scope.
3578 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3579 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3580 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3581 ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs);
3582 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3583 return false;
3584
3585 return !Result.get()->hasNonTrivialCall(Self.Context);
3586 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003587 }
3588 llvm_unreachable("Unknown type trait or not implemented");
3589}
3590
3591ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3592 SourceLocation KWLoc,
3593 TypeSourceInfo *LhsTSInfo,
3594 TypeSourceInfo *RhsTSInfo,
3595 SourceLocation RParen) {
3596 QualType LhsT = LhsTSInfo->getType();
3597 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003598
John McCalld89d30f2011-01-28 22:02:36 +00003599 if (BTT == BTT_TypeCompatible) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003600 if (getLangOpts().CPlusPlus) {
Francois Pichetf1872372010-12-08 22:35:30 +00003601 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3602 << SourceRange(KWLoc, RParen);
3603 return ExprError();
3604 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003605 }
3606
3607 bool Value = false;
3608 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3609 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3610
Francois Pichetf1872372010-12-08 22:35:30 +00003611 // Select trait result type.
3612 QualType ResultType;
3613 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003614 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003615 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3616 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003617 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003618 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Douglas Gregor25d0a0f2012-02-23 07:33:15 +00003619 case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy;
Francois Pichetf1872372010-12-08 22:35:30 +00003620 }
3621
Francois Pichet6ad6f282010-12-07 00:08:36 +00003622 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3623 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003624 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003625}
3626
John Wiegley21ff2e52011-04-28 00:16:57 +00003627ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3628 SourceLocation KWLoc,
3629 ParsedType Ty,
3630 Expr* DimExpr,
3631 SourceLocation RParen) {
3632 TypeSourceInfo *TSInfo;
3633 QualType T = GetTypeFromParser(Ty, &TSInfo);
3634 if (!TSInfo)
3635 TSInfo = Context.getTrivialTypeSourceInfo(T);
3636
3637 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3638}
3639
3640static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3641 QualType T, Expr *DimExpr,
3642 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003643 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003644
3645 switch(ATT) {
3646 case ATT_ArrayRank:
3647 if (T->isArrayType()) {
3648 unsigned Dim = 0;
3649 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3650 ++Dim;
3651 T = AT->getElementType();
3652 }
3653 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003654 }
John Wiegleycf566412011-04-28 02:06:46 +00003655 return 0;
3656
John Wiegley21ff2e52011-04-28 00:16:57 +00003657 case ATT_ArrayExtent: {
3658 llvm::APSInt Value;
3659 uint64_t Dim;
Richard Smith282e7e62012-02-04 09:53:13 +00003660 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregorab41fe92012-05-04 22:38:52 +00003661 diag::err_dimension_expr_not_constant_integer,
Richard Smith282e7e62012-02-04 09:53:13 +00003662 false).isInvalid())
3663 return 0;
3664 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbare7d6ca02012-03-09 21:38:22 +00003665 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
3666 << DimExpr->getSourceRange();
Richard Smith282e7e62012-02-04 09:53:13 +00003667 return 0;
John Wiegleycf566412011-04-28 02:06:46 +00003668 }
Richard Smith282e7e62012-02-04 09:53:13 +00003669 Dim = Value.getLimitedValue();
John Wiegley21ff2e52011-04-28 00:16:57 +00003670
3671 if (T->isArrayType()) {
3672 unsigned D = 0;
3673 bool Matched = false;
3674 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3675 if (Dim == D) {
3676 Matched = true;
3677 break;
3678 }
3679 ++D;
3680 T = AT->getElementType();
3681 }
3682
John Wiegleycf566412011-04-28 02:06:46 +00003683 if (Matched && T->isArrayType()) {
3684 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3685 return CAT->getSize().getLimitedValue();
3686 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003687 }
John Wiegleycf566412011-04-28 02:06:46 +00003688 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003689 }
3690 }
3691 llvm_unreachable("Unknown type trait or not implemented");
3692}
3693
3694ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3695 SourceLocation KWLoc,
3696 TypeSourceInfo *TSInfo,
3697 Expr* DimExpr,
3698 SourceLocation RParen) {
3699 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003700
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003701 // FIXME: This should likely be tracked as an APInt to remove any host
3702 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003703 uint64_t Value = 0;
3704 if (!T->isDependentType())
3705 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3706
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003707 // While the specification for these traits from the Embarcadero C++
3708 // compiler's documentation says the return type is 'unsigned int', Clang
3709 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3710 // compiler, there is no difference. On several other platforms this is an
3711 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003712 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003713 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003714 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003715}
3716
John Wiegley55262202011-04-25 06:54:41 +00003717ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003718 SourceLocation KWLoc,
3719 Expr *Queried,
3720 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003721 // If error parsing the expression, ignore.
3722 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003723 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003724
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003725 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003726
3727 return move(Result);
3728}
3729
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003730static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3731 switch (ET) {
3732 case ET_IsLValueExpr: return E->isLValue();
3733 case ET_IsRValueExpr: return E->isRValue();
3734 }
3735 llvm_unreachable("Expression trait not covered by switch");
3736}
3737
John Wiegley55262202011-04-25 06:54:41 +00003738ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003739 SourceLocation KWLoc,
3740 Expr *Queried,
3741 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003742 if (Queried->isTypeDependent()) {
3743 // Delay type-checking for type-dependent expressions.
3744 } else if (Queried->getType()->isPlaceholderType()) {
3745 ExprResult PE = CheckPlaceholderExpr(Queried);
3746 if (PE.isInvalid()) return ExprError();
3747 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3748 }
3749
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003750 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003751
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003752 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3753 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003754}
3755
Richard Trieudd225092011-09-15 21:56:47 +00003756QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003757 ExprValueKind &VK,
3758 SourceLocation Loc,
3759 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003760 assert(!LHS.get()->getType()->isPlaceholderType() &&
3761 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003762 "placeholders should have been weeded out by now");
3763
3764 // The LHS undergoes lvalue conversions if this is ->*.
3765 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003766 LHS = DefaultLvalueConversion(LHS.take());
3767 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003768 }
3769
3770 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003771 RHS = DefaultLvalueConversion(RHS.take());
3772 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003773
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003774 const char *OpSpelling = isIndirect ? "->*" : ".*";
3775 // C++ 5.5p2
3776 // The binary operator .* [p3: ->*] binds its second operand, which shall
3777 // be of type "pointer to member of T" (where T is a completely-defined
3778 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003779 QualType RHSType = RHS.get()->getType();
3780 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003781 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003782 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003783 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003784 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003785 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003786
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003787 QualType Class(MemPtr->getClass(), 0);
3788
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003789 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3790 // member pointer points must be completely-defined. However, there is no
3791 // reason for this semantic distinction, and the rule is not enforced by
3792 // other compilers. Therefore, we do not check this property, as it is
3793 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003794
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003795 // C++ 5.5p2
3796 // [...] to its first operand, which shall be of class T or of a class of
3797 // which T is an unambiguous and accessible base class. [p3: a pointer to
3798 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00003799 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003800 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003801 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3802 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003803 else {
3804 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00003805 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00003806 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003807 return QualType();
3808 }
3809 }
3810
Richard Trieudd225092011-09-15 21:56:47 +00003811 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003812 // If we want to check the hierarchy, we need a complete type.
Douglas Gregord10099e2012-05-04 16:32:21 +00003813 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
3814 OpSpelling, (int)isIndirect)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003815 return QualType();
3816 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003817 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003818 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003819 // FIXME: Would it be useful to print full ambiguity paths, or is that
3820 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00003821 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003822 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3823 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00003824 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003825 return QualType();
3826 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003827 // Cast LHS to type of use.
3828 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003829 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00003830
John McCallf871d0c2010-08-07 06:22:56 +00003831 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003832 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00003833 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3834 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003835 }
3836
Richard Trieudd225092011-09-15 21:56:47 +00003837 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003838 // Diagnose use of pointer-to-member type which when used as
3839 // the functional cast in a pointer-to-member expression.
3840 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3841 return QualType();
3842 }
John McCallf89e55a2010-11-18 06:31:45 +00003843
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003844 // C++ 5.5p2
3845 // The result is an object or a function of the type specified by the
3846 // second operand.
3847 // The cv qualifiers are the union of those in the pointer and the left side,
3848 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003849 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00003850 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003851
Douglas Gregor6b4df912011-01-26 16:40:18 +00003852 // C++0x [expr.mptr.oper]p6:
3853 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003854 // ill-formed if the second operand is a pointer to member function with
3855 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3856 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003857 // is a pointer to member function with ref-qualifier &&.
3858 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3859 switch (Proto->getRefQualifier()) {
3860 case RQ_None:
3861 // Do nothing
3862 break;
3863
3864 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00003865 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003866 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003867 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003868 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003869
Douglas Gregor6b4df912011-01-26 16:40:18 +00003870 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00003871 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003872 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003873 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003874 break;
3875 }
3876 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003877
John McCallf89e55a2010-11-18 06:31:45 +00003878 // C++ [expr.mptr.oper]p6:
3879 // The result of a .* expression whose second operand is a pointer
3880 // to a data member is of the same value category as its
3881 // first operand. The result of a .* expression whose second
3882 // operand is a pointer to a member function is a prvalue. The
3883 // result of an ->* expression is an lvalue if its second operand
3884 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003885 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003886 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003887 return Context.BoundMemberTy;
3888 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003889 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003890 } else {
Richard Trieudd225092011-09-15 21:56:47 +00003891 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003892 }
John McCallf89e55a2010-11-18 06:31:45 +00003893
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003894 return Result;
3895}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003896
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003897/// \brief Try to convert a type to another according to C++0x 5.16p3.
3898///
3899/// This is part of the parameter validation for the ? operator. If either
3900/// value operand is a class type, the two operands are attempted to be
3901/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003902/// It returns true if the program is ill-formed and has already been diagnosed
3903/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003904static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3905 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003906 bool &HaveConversion,
3907 QualType &ToType) {
3908 HaveConversion = false;
3909 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003910
3911 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003912 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003913 // C++0x 5.16p3
3914 // The process for determining whether an operand expression E1 of type T1
3915 // can be converted to match an operand expression E2 of type T2 is defined
3916 // as follows:
3917 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003918 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003919 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003920 // E1 can be converted to match E2 if E1 can be implicitly converted to
3921 // type "lvalue reference to T2", subject to the constraint that in the
3922 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003923 QualType T = Self.Context.getLValueReferenceType(ToType);
3924 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003925
Douglas Gregorb70cf442010-03-26 20:14:36 +00003926 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3927 if (InitSeq.isDirectReferenceBinding()) {
3928 ToType = T;
3929 HaveConversion = true;
3930 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003931 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003932
Douglas Gregorb70cf442010-03-26 20:14:36 +00003933 if (InitSeq.isAmbiguous())
3934 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003935 }
John McCallb1bdc622010-02-25 01:37:24 +00003936
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003937 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3938 // -- if E1 and E2 have class type, and the underlying class types are
3939 // the same or one is a base class of the other:
3940 QualType FTy = From->getType();
3941 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003942 const RecordType *FRec = FTy->getAs<RecordType>();
3943 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003944 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003945 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003946 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003947 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003948 // E1 can be converted to match E2 if the class of T2 is the
3949 // same type as, or a base class of, the class of T1, and
3950 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003951 if (FRec == TRec || FDerivedFromT) {
3952 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003953 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3954 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003955 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003956 HaveConversion = true;
3957 return false;
3958 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003959
Douglas Gregorb70cf442010-03-26 20:14:36 +00003960 if (InitSeq.isAmbiguous())
3961 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003962 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003963 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003964
Douglas Gregorb70cf442010-03-26 20:14:36 +00003965 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003966 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003967
Douglas Gregorb70cf442010-03-26 20:14:36 +00003968 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3969 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003970 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003971 // an rvalue).
3972 //
3973 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3974 // to the array-to-pointer or function-to-pointer conversions.
3975 if (!TTy->getAs<TagType>())
3976 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003977
Douglas Gregorb70cf442010-03-26 20:14:36 +00003978 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3979 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003980 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003981 ToType = TTy;
3982 if (InitSeq.isAmbiguous())
3983 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3984
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003985 return false;
3986}
3987
3988/// \brief Try to find a common type for two according to C++0x 5.16p5.
3989///
3990/// This is part of the parameter validation for the ? operator. If either
3991/// value operand is a class type, overload resolution is used to find a
3992/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003993static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003994 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003995 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003996 OverloadCandidateSet CandidateSet(QuestionLoc);
3997 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3998 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003999
4000 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00004001 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00004002 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004003 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00004004 ExprResult LHSRes =
4005 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
4006 Best->Conversions[0], Sema::AA_Converting);
4007 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004008 break;
John Wiegley429bb272011-04-08 18:41:53 +00004009 LHS = move(LHSRes);
4010
4011 ExprResult RHSRes =
4012 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
4013 Best->Conversions[1], Sema::AA_Converting);
4014 if (RHSRes.isInvalid())
4015 break;
4016 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00004017 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00004018 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004019 return false;
John Wiegley429bb272011-04-08 18:41:53 +00004020 }
4021
Douglas Gregor20093b42009-12-09 23:02:17 +00004022 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00004023
4024 // Emit a better diagnostic if one of the expressions is a null pointer
4025 // constant and the other is a pointer type. In this case, the user most
4026 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004027 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004028 return true;
4029
4030 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00004031 << LHS.get()->getType() << RHS.get()->getType()
4032 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004033 return true;
4034
Douglas Gregor20093b42009-12-09 23:02:17 +00004035 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00004036 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00004037 << LHS.get()->getType() << RHS.get()->getType()
4038 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00004039 // FIXME: Print the possible common types by printing the return types of
4040 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004041 break;
4042
Douglas Gregor20093b42009-12-09 23:02:17 +00004043 case OR_Deleted:
David Blaikieb219cfc2011-09-23 05:06:16 +00004044 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004045 }
4046 return true;
4047}
4048
Sebastian Redl76458502009-04-17 16:30:52 +00004049/// \brief Perform an "extended" implicit conversion as returned by
4050/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00004051static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00004052 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00004053 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00004054 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00004055 Expr *Arg = E.take();
4056 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
4057 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00004058 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00004059 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004060
John Wiegley429bb272011-04-08 18:41:53 +00004061 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00004062 return false;
4063}
4064
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004065/// \brief Check the operands of ?: under C++ semantics.
4066///
4067/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4068/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00004069QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00004070 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004071 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00004072 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4073 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004074
4075 // C++0x 5.16p1
4076 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00004077 if (!Cond.get()->isTypeDependent()) {
4078 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
4079 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004080 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004081 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004082 }
4083
John McCallf89e55a2010-11-18 06:31:45 +00004084 // Assume r-value.
4085 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004086 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00004087
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004088 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00004089 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004090 return Context.DependentTy;
4091
4092 // C++0x 5.16p2
4093 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00004094 QualType LTy = LHS.get()->getType();
4095 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004096 bool LVoid = LTy->isVoidType();
4097 bool RVoid = RTy->isVoidType();
4098 if (LVoid || RVoid) {
4099 // ... then the [l2r] conversions are performed on the second and third
4100 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00004101 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4102 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4103 if (LHS.isInvalid() || RHS.isInvalid())
4104 return QualType();
4105 LTy = LHS.get()->getType();
4106 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004107
4108 // ... and one of the following shall hold:
4109 // -- The second or the third operand (but not both) is a throw-
4110 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00004111 bool LThrow = isa<CXXThrowExpr>(LHS.get());
4112 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004113 if (LThrow && !RThrow)
4114 return RTy;
4115 if (RThrow && !LThrow)
4116 return LTy;
4117
4118 // -- Both the second and third operands have type void; the result is of
4119 // type void and is an rvalue.
4120 if (LVoid && RVoid)
4121 return Context.VoidTy;
4122
4123 // Neither holds, error.
4124 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4125 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00004126 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004127 return QualType();
4128 }
4129
4130 // Neither is void.
4131
4132 // C++0x 5.16p3
4133 // Otherwise, if the second and third operand have different types, and
4134 // either has (cv) class type, and attempt is made to convert each of those
4135 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004136 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004137 (LTy->isRecordType() || RTy->isRecordType())) {
4138 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
4139 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00004140 QualType L2RType, R2LType;
4141 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00004142 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004143 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004144 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004145 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004146
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004147 // If both can be converted, [...] the program is ill-formed.
4148 if (HaveL2R && HaveR2L) {
4149 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00004150 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004151 return QualType();
4152 }
4153
4154 // If exactly one conversion is possible, that conversion is applied to
4155 // the chosen operand and the converted operands are used in place of the
4156 // original operands for the remainder of this section.
4157 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00004158 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004159 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004160 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004161 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00004162 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004163 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004164 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004165 }
4166 }
4167
4168 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00004169 // If the second and third operands are glvalues of the same value
4170 // category and have the same type, the result is of that type and
4171 // value category and it is a bit-field if the second or the third
4172 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00004173 // We only extend this to bitfields, not to the crazy other kinds of
4174 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00004175 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00004176 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00004177 LHS.get()->isGLValue() &&
4178 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
4179 LHS.get()->isOrdinaryOrBitFieldObject() &&
4180 RHS.get()->isOrdinaryOrBitFieldObject()) {
4181 VK = LHS.get()->getValueKind();
4182 if (LHS.get()->getObjectKind() == OK_BitField ||
4183 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00004184 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00004185 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00004186 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004187
4188 // C++0x 5.16p5
4189 // Otherwise, the result is an rvalue. If the second and third operands
4190 // do not have the same type, and either has (cv) class type, ...
4191 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4192 // ... overload resolution is used to determine the conversions (if any)
4193 // to be applied to the operands. If the overload resolution fails, the
4194 // program is ill-formed.
4195 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4196 return QualType();
4197 }
4198
4199 // C++0x 5.16p6
4200 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
4201 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00004202 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4203 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4204 if (LHS.isInvalid() || RHS.isInvalid())
4205 return QualType();
4206 LTy = LHS.get()->getType();
4207 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004208
4209 // After those conversions, one of the following shall hold:
4210 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00004211 // is of that type. If the operands have class type, the result
4212 // is a prvalue temporary of the result type, which is
4213 // copy-initialized from either the second operand or the third
4214 // operand depending on the value of the first operand.
4215 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4216 if (LTy->isRecordType()) {
4217 // The operands have class type. Make a temporary copy.
4218 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004219 ExprResult LHSCopy = PerformCopyInitialization(Entity,
4220 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00004221 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00004222 if (LHSCopy.isInvalid())
4223 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004224
4225 ExprResult RHSCopy = PerformCopyInitialization(Entity,
4226 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00004227 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00004228 if (RHSCopy.isInvalid())
4229 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004230
John Wiegley429bb272011-04-08 18:41:53 +00004231 LHS = LHSCopy;
4232 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00004233 }
4234
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004235 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00004236 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004237
Douglas Gregorfb4a5432010-05-18 22:42:18 +00004238 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004239 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004240 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00004241
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004242 // -- The second and third operands have arithmetic or enumeration type;
4243 // the usual arithmetic conversions are performed to bring them to a
4244 // common type, and the result is of that type.
4245 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4246 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004247 if (LHS.isInvalid() || RHS.isInvalid())
4248 return QualType();
4249 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004250 }
4251
4252 // -- The second and third operands have pointer type, or one has pointer
4253 // type and the other is a null pointer constant; pointer conversions
4254 // and qualification conversions are performed to bring them to their
4255 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00004256 // -- The second and third operands have pointer to member type, or one has
4257 // pointer to member type and the other is a null pointer constant;
4258 // pointer to member conversions and qualification conversions are
4259 // performed to bring them to a common type, whose cv-qualification
4260 // shall match the cv-qualification of either the second or the third
4261 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004262 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004263 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004264 isSFINAEContext()? 0 : &NonStandardCompositeType);
4265 if (!Composite.isNull()) {
4266 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004267 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004268 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4269 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00004270 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004271
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004272 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004273 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004274
Douglas Gregor1927b1f2010-04-01 22:47:07 +00004275 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00004276 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4277 if (!Composite.isNull())
4278 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004279
Chandler Carruth7ef93242011-02-19 00:13:59 +00004280 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00004281 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00004282 return QualType();
4283
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004284 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00004285 << LHS.get()->getType() << RHS.get()->getType()
4286 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004287 return QualType();
4288}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004289
4290/// \brief Find a merged pointer type and convert the two expressions to it.
4291///
Douglas Gregor20b3e992009-08-24 17:42:35 +00004292/// This finds the composite pointer type (or member pointer type) for @p E1
4293/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
4294/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004295/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004296///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004297/// \param Loc The location of the operator requiring these two expressions to
4298/// be converted to the composite pointer type.
4299///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004300/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4301/// a non-standard (but still sane) composite type to which both expressions
4302/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4303/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004304QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004305 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004306 bool *NonStandardCompositeType) {
4307 if (NonStandardCompositeType)
4308 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004309
David Blaikie4e4d0842012-03-11 07:00:24 +00004310 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004311 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004312
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00004313 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4314 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00004315 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004316
4317 // C++0x 5.9p2
4318 // Pointer conversions and qualification conversions are performed on
4319 // pointer operands to bring them to their composite pointer type. If
4320 // one operand is a null pointer constant, the composite pointer type is
4321 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00004322 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004323 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00004324 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004325 else
John Wiegley429bb272011-04-08 18:41:53 +00004326 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004327 return T2;
4328 }
Douglas Gregorce940492009-09-25 04:25:58 +00004329 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004330 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00004331 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004332 else
John Wiegley429bb272011-04-08 18:41:53 +00004333 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004334 return T1;
4335 }
Mike Stump1eb44332009-09-09 15:08:12 +00004336
Douglas Gregor20b3e992009-08-24 17:42:35 +00004337 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004338 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4339 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004340 return QualType();
4341
4342 // Otherwise, of one of the operands has type "pointer to cv1 void," then
4343 // the other has type "pointer to cv2 T" and the composite pointer type is
4344 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4345 // Otherwise, the composite pointer type is a pointer type similar to the
4346 // type of one of the operands, with a cv-qualification signature that is
4347 // the union of the cv-qualification signatures of the operand types.
4348 // In practice, the first part here is redundant; it's subsumed by the second.
4349 // What we do here is, we build the two possible composite types, and try the
4350 // conversions in both directions. If only one works, or if the two composite
4351 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00004352 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00004353 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00004354 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004355 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00004356 ContainingClassVector;
4357 ContainingClassVector MemberOfClass;
4358 QualType Composite1 = Context.getCanonicalType(T1),
4359 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004360 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00004361 do {
4362 const PointerType *Ptr1, *Ptr2;
4363 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4364 (Ptr2 = Composite2->getAs<PointerType>())) {
4365 Composite1 = Ptr1->getPointeeType();
4366 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004367
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004368 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004369 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004370 if (NonStandardCompositeType &&
4371 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4372 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004373
Douglas Gregor20b3e992009-08-24 17:42:35 +00004374 QualifierUnion.push_back(
4375 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4376 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
4377 continue;
4378 }
Mike Stump1eb44332009-09-09 15:08:12 +00004379
Douglas Gregor20b3e992009-08-24 17:42:35 +00004380 const MemberPointerType *MemPtr1, *MemPtr2;
4381 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4382 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4383 Composite1 = MemPtr1->getPointeeType();
4384 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004385
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004386 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004387 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004388 if (NonStandardCompositeType &&
4389 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4390 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004391
Douglas Gregor20b3e992009-08-24 17:42:35 +00004392 QualifierUnion.push_back(
4393 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4394 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4395 MemPtr2->getClass()));
4396 continue;
4397 }
Mike Stump1eb44332009-09-09 15:08:12 +00004398
Douglas Gregor20b3e992009-08-24 17:42:35 +00004399 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00004400
Douglas Gregor20b3e992009-08-24 17:42:35 +00004401 // Cannot unwrap any more types.
4402 break;
4403 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00004404
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004405 if (NeedConstBefore && NonStandardCompositeType) {
4406 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004407 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004408 // requirements of C++ [conv.qual]p4 bullet 3.
4409 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4410 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4411 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4412 *NonStandardCompositeType = true;
4413 }
4414 }
4415 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004416
Douglas Gregor20b3e992009-08-24 17:42:35 +00004417 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004418 ContainingClassVector::reverse_iterator MOC
4419 = MemberOfClass.rbegin();
4420 for (QualifierVector::reverse_iterator
4421 I = QualifierUnion.rbegin(),
4422 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00004423 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00004424 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004425 if (MOC->first && MOC->second) {
4426 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00004427 Composite1 = Context.getMemberPointerType(
4428 Context.getQualifiedType(Composite1, Quals),
4429 MOC->first);
4430 Composite2 = Context.getMemberPointerType(
4431 Context.getQualifiedType(Composite2, Quals),
4432 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004433 } else {
4434 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00004435 Composite1
4436 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4437 Composite2
4438 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00004439 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004440 }
4441
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004442 // Try to convert to the first composite pointer type.
4443 InitializedEntity Entity1
4444 = InitializedEntity::InitializeTemporary(Composite1);
4445 InitializationKind Kind
4446 = InitializationKind::CreateCopy(Loc, SourceLocation());
4447 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4448 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00004449
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004450 if (E1ToC1 && E2ToC1) {
4451 // Conversion to Composite1 is viable.
4452 if (!Context.hasSameType(Composite1, Composite2)) {
4453 // Composite2 is a different type from Composite1. Check whether
4454 // Composite2 is also viable.
4455 InitializedEntity Entity2
4456 = InitializedEntity::InitializeTemporary(Composite2);
4457 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4458 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4459 if (E1ToC2 && E2ToC2) {
4460 // Both Composite1 and Composite2 are viable and are different;
4461 // this is an ambiguity.
4462 return QualType();
4463 }
4464 }
4465
4466 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004467 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004468 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004469 if (E1Result.isInvalid())
4470 return QualType();
4471 E1 = E1Result.takeAs<Expr>();
4472
4473 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004474 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004475 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004476 if (E2Result.isInvalid())
4477 return QualType();
4478 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004479
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004480 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004481 }
4482
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004483 // Check whether Composite2 is viable.
4484 InitializedEntity Entity2
4485 = InitializedEntity::InitializeTemporary(Composite2);
4486 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4487 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4488 if (!E1ToC2 || !E2ToC2)
4489 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004490
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004491 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004492 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004493 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004494 if (E1Result.isInvalid())
4495 return QualType();
4496 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004497
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004498 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004499 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004500 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004501 if (E2Result.isInvalid())
4502 return QualType();
4503 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004504
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004505 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004506}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004507
John McCall60d7b3a2010-08-24 06:29:42 +00004508ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004509 if (!E)
4510 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004511
John McCallf85e1932011-06-15 23:02:42 +00004512 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4513
4514 // If the result is a glvalue, we shouldn't bind it.
4515 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004516 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004517
John McCallf85e1932011-06-15 23:02:42 +00004518 // In ARC, calls that return a retainable type can return retained,
4519 // in which case we have to insert a consuming cast.
David Blaikie4e4d0842012-03-11 07:00:24 +00004520 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004521 E->getType()->isObjCRetainableType()) {
4522
4523 bool ReturnsRetained;
4524
4525 // For actual calls, we compute this by examining the type of the
4526 // called value.
4527 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4528 Expr *Callee = Call->getCallee()->IgnoreParens();
4529 QualType T = Callee->getType();
4530
4531 if (T == Context.BoundMemberTy) {
4532 // Handle pointer-to-members.
4533 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4534 T = BinOp->getRHS()->getType();
4535 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4536 T = Mem->getMemberDecl()->getType();
4537 }
4538
4539 if (const PointerType *Ptr = T->getAs<PointerType>())
4540 T = Ptr->getPointeeType();
4541 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4542 T = Ptr->getPointeeType();
4543 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4544 T = MemPtr->getPointeeType();
4545
4546 const FunctionType *FTy = T->getAs<FunctionType>();
4547 assert(FTy && "call to value not of function type?");
4548 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4549
4550 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4551 // type always produce a +1 object.
4552 } else if (isa<StmtExpr>(E)) {
4553 ReturnsRetained = true;
4554
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004555 // We hit this case with the lambda conversion-to-block optimization;
4556 // we don't want any extra casts here.
4557 } else if (isa<CastExpr>(E) &&
4558 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
4559 return Owned(E);
4560
John McCallf85e1932011-06-15 23:02:42 +00004561 // For message sends and property references, we try to find an
4562 // actual method. FIXME: we should infer retention by selector in
4563 // cases where we don't have an actual method.
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004564 } else {
4565 ObjCMethodDecl *D = 0;
4566 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4567 D = Send->getMethodDecl();
Patrick Beardeb382ec2012-04-19 00:25:12 +00004568 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
4569 D = BoxedExpr->getBoxingMethod();
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004570 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
4571 D = ArrayLit->getArrayWithObjectsMethod();
4572 } else if (ObjCDictionaryLiteral *DictLit
4573 = dyn_cast<ObjCDictionaryLiteral>(E)) {
4574 D = DictLit->getDictWithObjectsMethod();
4575 }
John McCallf85e1932011-06-15 23:02:42 +00004576
4577 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004578
4579 // Don't do reclaims on performSelector calls; despite their
4580 // return type, the invoked method doesn't necessarily actually
4581 // return an object.
4582 if (!ReturnsRetained &&
4583 D && D->getMethodFamily() == OMF_performSelector)
4584 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004585 }
4586
John McCall567c5862011-11-14 19:53:16 +00004587 // Don't reclaim an object of Class type.
4588 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4589 return Owned(E);
4590
John McCall7e5e5f42011-07-07 06:58:02 +00004591 ExprNeedsCleanups = true;
4592
John McCall33e56f32011-09-10 06:18:15 +00004593 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4594 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004595 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4596 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004597 }
4598
David Blaikie4e4d0842012-03-11 07:00:24 +00004599 if (!getLangOpts().CPlusPlus)
John McCallf85e1932011-06-15 23:02:42 +00004600 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004601
Peter Collingbourneb4ab8432012-01-26 03:33:51 +00004602 // Search for the base element type (cf. ASTContext::getBaseElementType) with
4603 // a fast path for the common case that the type is directly a RecordType.
4604 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4605 const RecordType *RT = 0;
4606 while (!RT) {
4607 switch (T->getTypeClass()) {
4608 case Type::Record:
4609 RT = cast<RecordType>(T);
4610 break;
4611 case Type::ConstantArray:
4612 case Type::IncompleteArray:
4613 case Type::VariableArray:
4614 case Type::DependentSizedArray:
4615 T = cast<ArrayType>(T)->getElementType().getTypePtr();
4616 break;
4617 default:
4618 return Owned(E);
4619 }
4620 }
Mike Stump1eb44332009-09-09 15:08:12 +00004621
Richard Smith76f3f692012-02-22 02:04:18 +00004622 // That should be enough to guarantee that this type is complete, if we're
4623 // not processing a decltype expression.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004624 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith213d70b2012-02-18 04:13:32 +00004625 if (RD->isInvalidDecl() || RD->isDependentContext())
John McCall86ff3082010-02-04 22:26:26 +00004626 return Owned(E);
Richard Smith76f3f692012-02-22 02:04:18 +00004627
4628 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
4629 CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD);
John McCallf85e1932011-06-15 23:02:42 +00004630
John McCallf85e1932011-06-15 23:02:42 +00004631 if (Destructor) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00004632 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004633 CheckDestructorAccess(E->getExprLoc(), Destructor,
4634 PDiag(diag::err_access_dtor_temp)
4635 << E->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00004636 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00004637
Richard Smith76f3f692012-02-22 02:04:18 +00004638 // If destructor is trivial, we can avoid the extra copy.
4639 if (Destructor->isTrivial())
4640 return Owned(E);
Richard Smith213d70b2012-02-18 04:13:32 +00004641
John McCall80ee6e82011-11-10 05:35:25 +00004642 // We need a cleanup, but we don't need to remember the temporary.
John McCallf85e1932011-06-15 23:02:42 +00004643 ExprNeedsCleanups = true;
Richard Smith76f3f692012-02-22 02:04:18 +00004644 }
Richard Smith213d70b2012-02-18 04:13:32 +00004645
4646 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smith76f3f692012-02-22 02:04:18 +00004647 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
4648
4649 if (IsDecltype)
4650 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
4651
4652 return Owned(Bind);
Anders Carlssondef11992009-05-30 20:36:53 +00004653}
4654
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004655ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004656Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004657 if (SubExpr.isInvalid())
4658 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004659
John McCall4765fa02010-12-06 08:20:24 +00004660 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004661}
4662
John McCall80ee6e82011-11-10 05:35:25 +00004663Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4664 assert(SubExpr && "sub expression can't be null!");
4665
Eli Friedmand2cce132012-02-02 23:15:15 +00004666 CleanupVarDeclMarking();
4667
John McCall80ee6e82011-11-10 05:35:25 +00004668 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4669 assert(ExprCleanupObjects.size() >= FirstCleanup);
4670 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4671 if (!ExprNeedsCleanups)
4672 return SubExpr;
4673
4674 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4675 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4676 ExprCleanupObjects.size() - FirstCleanup);
4677
4678 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4679 DiscardCleanupsInEvaluationContext();
4680
4681 return E;
4682}
4683
John McCall4765fa02010-12-06 08:20:24 +00004684Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004685 assert(SubStmt && "sub statement can't be null!");
4686
Eli Friedmand2cce132012-02-02 23:15:15 +00004687 CleanupVarDeclMarking();
4688
John McCallf85e1932011-06-15 23:02:42 +00004689 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004690 return SubStmt;
4691
4692 // FIXME: In order to attach the temporaries, wrap the statement into
4693 // a StmtExpr; currently this is only used for asm statements.
4694 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4695 // a new AsmStmtWithTemporaries.
4696 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4697 SourceLocation(),
4698 SourceLocation());
4699 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4700 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004701 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004702}
4703
Richard Smith76f3f692012-02-22 02:04:18 +00004704/// Process the expression contained within a decltype. For such expressions,
4705/// certain semantic checks on temporaries are delayed until this point, and
4706/// are omitted for the 'topmost' call in the decltype expression. If the
4707/// topmost call bound a temporary, strip that temporary off the expression.
4708ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
4709 ExpressionEvaluationContextRecord &Rec = ExprEvalContexts.back();
4710 assert(Rec.IsDecltype && "not in a decltype expression");
4711
4712 // C++11 [expr.call]p11:
4713 // If a function call is a prvalue of object type,
4714 // -- if the function call is either
4715 // -- the operand of a decltype-specifier, or
4716 // -- the right operand of a comma operator that is the operand of a
4717 // decltype-specifier,
4718 // a temporary object is not introduced for the prvalue.
4719
4720 // Recursively rebuild ParenExprs and comma expressions to strip out the
4721 // outermost CXXBindTemporaryExpr, if any.
4722 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4723 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
4724 if (SubExpr.isInvalid())
4725 return ExprError();
4726 if (SubExpr.get() == PE->getSubExpr())
4727 return Owned(E);
4728 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take());
4729 }
4730 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4731 if (BO->getOpcode() == BO_Comma) {
4732 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
4733 if (RHS.isInvalid())
4734 return ExprError();
4735 if (RHS.get() == BO->getRHS())
4736 return Owned(E);
4737 return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(),
4738 BO_Comma, BO->getType(),
4739 BO->getValueKind(),
4740 BO->getObjectKind(),
4741 BO->getOperatorLoc()));
4742 }
4743 }
4744
4745 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
4746 if (TopBind)
4747 E = TopBind->getSubExpr();
4748
4749 // Disable the special decltype handling now.
4750 Rec.IsDecltype = false;
4751
4752 // Perform the semantic checks we delayed until this point.
4753 CallExpr *TopCall = dyn_cast<CallExpr>(E);
4754 for (unsigned I = 0, N = Rec.DelayedDecltypeCalls.size(); I != N; ++I) {
4755 CallExpr *Call = Rec.DelayedDecltypeCalls[I];
4756 if (Call == TopCall)
4757 continue;
4758
4759 if (CheckCallReturnType(Call->getCallReturnType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004760 Call->getLocStart(),
Richard Smith76f3f692012-02-22 02:04:18 +00004761 Call, Call->getDirectCallee()))
4762 return ExprError();
4763 }
4764
4765 // Now all relevant types are complete, check the destructors are accessible
4766 // and non-deleted, and annotate them on the temporaries.
4767 for (unsigned I = 0, N = Rec.DelayedDecltypeBinds.size(); I != N; ++I) {
4768 CXXBindTemporaryExpr *Bind = Rec.DelayedDecltypeBinds[I];
4769 if (Bind == TopBind)
4770 continue;
4771
4772 CXXTemporary *Temp = Bind->getTemporary();
4773
4774 CXXRecordDecl *RD =
4775 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
4776 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4777 Temp->setDestructor(Destructor);
4778
Richard Smith2f68ca02012-05-11 22:20:10 +00004779 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
4780 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smith76f3f692012-02-22 02:04:18 +00004781 PDiag(diag::err_access_dtor_temp)
Richard Smith2f68ca02012-05-11 22:20:10 +00004782 << Bind->getType());
4783 DiagnoseUseOfDecl(Destructor, Bind->getExprLoc());
Richard Smith76f3f692012-02-22 02:04:18 +00004784
4785 // We need a cleanup, but we don't need to remember the temporary.
4786 ExprNeedsCleanups = true;
4787 }
4788
4789 // Possibly strip off the top CXXBindTemporaryExpr.
4790 return Owned(E);
4791}
4792
John McCall60d7b3a2010-08-24 06:29:42 +00004793ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004794Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00004795 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00004796 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004797 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004798 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004799 if (Result.isInvalid()) return ExprError();
4800 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004801
John McCall3c3b7f92011-10-25 17:37:35 +00004802 Result = CheckPlaceholderExpr(Base);
4803 if (Result.isInvalid()) return ExprError();
4804 Base = Result.take();
4805
John McCall9ae2f072010-08-23 23:25:46 +00004806 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004807 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004808 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00004809 // If we have a pointer to a dependent type and are using the -> operator,
4810 // the object type is the type that the pointer points to. We might still
4811 // have enough information about that type to do something useful.
4812 if (OpKind == tok::arrow)
4813 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4814 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004815
John McCallb3d87482010-08-24 05:47:05 +00004816 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00004817 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004818 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004819 }
Mike Stump1eb44332009-09-09 15:08:12 +00004820
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004821 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00004822 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004823 // returned, with the original second operand.
4824 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00004825 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00004826 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004827 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00004828 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004829
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004830 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00004831 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4832 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004833 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004834 Base = Result.get();
4835 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00004836 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00004837 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00004838 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00004839 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004840 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00004841 for (unsigned i = 0; i < Locations.size(); i++)
4842 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004843 return ExprError();
4844 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004845 }
Mike Stump1eb44332009-09-09 15:08:12 +00004846
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004847 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
Douglas Gregor31658df2009-11-20 19:58:21 +00004848 BaseType = BaseType->getPointeeType();
4849 }
Mike Stump1eb44332009-09-09 15:08:12 +00004850
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004851 // Objective-C properties allow "." access on Objective-C pointer types,
4852 // so adjust the base type to the object type itself.
4853 if (BaseType->isObjCObjectPointerType())
4854 BaseType = BaseType->getPointeeType();
4855
4856 // C++ [basic.lookup.classref]p2:
4857 // [...] If the type of the object expression is of pointer to scalar
4858 // type, the unqualified-id is looked up in the context of the complete
4859 // postfix-expression.
4860 //
4861 // This also indicates that we could be parsing a pseudo-destructor-name.
4862 // Note that Objective-C class and object types can be pseudo-destructor
4863 // expressions or normal member (ivar or property) access expressions.
4864 if (BaseType->isObjCObjectOrInterfaceType()) {
4865 MayBePseudoDestructor = true;
4866 } else if (!BaseType->isRecordType()) {
John McCallb3d87482010-08-24 05:47:05 +00004867 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004868 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004869 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00004870 }
Mike Stump1eb44332009-09-09 15:08:12 +00004871
Douglas Gregorcefc3af2012-04-16 07:05:22 +00004872 // The object type must be complete (or dependent), or
4873 // C++11 [expr.prim.general]p3:
4874 // Unlike the object expression in other contexts, *this is not required to
4875 // be of complete type for purposes of class member access (5.2.5) outside
4876 // the member function body.
Douglas Gregor03c57052009-11-17 05:17:33 +00004877 if (!BaseType->isDependentType() &&
Douglas Gregorcefc3af2012-04-16 07:05:22 +00004878 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00004879 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor03c57052009-11-17 05:17:33 +00004880 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004881
Douglas Gregorc68afe22009-09-03 21:38:09 +00004882 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004883 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00004884 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00004885 // type C (or of pointer to a class type C), the unqualified-id is looked
4886 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00004887 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00004888 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004889}
4890
John McCall60d7b3a2010-08-24 06:29:42 +00004891ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004892 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00004893 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00004894 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4895 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00004896 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004897
Douglas Gregor77549082010-02-24 21:29:12 +00004898 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00004899 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00004900 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00004901 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00004902 /*RPLoc*/ ExpectedLParenLoc);
4903}
Douglas Gregord4dca082010-02-24 18:44:31 +00004904
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004905static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie91ec7892011-12-16 16:03:09 +00004906 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004907 if (Base->hasPlaceholderType()) {
4908 ExprResult result = S.CheckPlaceholderExpr(Base);
4909 if (result.isInvalid()) return true;
4910 Base = result.take();
4911 }
4912 ObjectType = Base->getType();
4913
David Blaikie91ec7892011-12-16 16:03:09 +00004914 // C++ [expr.pseudo]p2:
4915 // The left-hand side of the dot operator shall be of scalar type. The
4916 // left-hand side of the arrow operator shall be of pointer to scalar type.
4917 // This scalar type is the object type.
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004918 // Note that this is rather different from the normal handling for the
4919 // arrow operator.
David Blaikie91ec7892011-12-16 16:03:09 +00004920 if (OpKind == tok::arrow) {
4921 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4922 ObjectType = Ptr->getPointeeType();
4923 } else if (!Base->isTypeDependent()) {
4924 // The user wrote "p->" when she probably meant "p."; fix it.
4925 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4926 << ObjectType << true
4927 << FixItHint::CreateReplacement(OpLoc, ".");
4928 if (S.isSFINAEContext())
4929 return true;
4930
4931 OpKind = tok::period;
4932 }
4933 }
4934
4935 return false;
4936}
4937
John McCall60d7b3a2010-08-24 06:29:42 +00004938ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004939 SourceLocation OpLoc,
4940 tok::TokenKind OpKind,
4941 const CXXScopeSpec &SS,
4942 TypeSourceInfo *ScopeTypeInfo,
4943 SourceLocation CCLoc,
4944 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004945 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00004946 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004947 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004948
Eli Friedman8c9fe202012-01-25 04:35:06 +00004949 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00004950 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4951 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004952
Douglas Gregorb57fb492010-02-24 22:38:50 +00004953 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004954 if (getLangOpts().MicrosoftMode && ObjectType->isVoidType())
Nico Weber2d757ec2012-01-23 06:08:16 +00004955 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Nico Weberdf1be862012-01-23 05:50:57 +00004956 else
4957 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
4958 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004959 return ExprError();
4960 }
4961
4962 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004963 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00004964 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004965 if (DestructedTypeInfo) {
4966 QualType DestructedType = DestructedTypeInfo->getType();
4967 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004968 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00004969 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4970 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4971 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4972 << ObjectType << DestructedType << Base->getSourceRange()
4973 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004974
John McCallf85e1932011-06-15 23:02:42 +00004975 // Recover by setting the destructed type to the object type.
4976 DestructedType = ObjectType;
4977 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004978 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00004979 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4980 } else if (DestructedType.getObjCLifetime() !=
4981 ObjectType.getObjCLifetime()) {
4982
4983 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4984 // Okay: just pretend that the user provided the correctly-qualified
4985 // type.
4986 } else {
4987 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4988 << ObjectType << DestructedType << Base->getSourceRange()
4989 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4990 }
4991
4992 // Recover by setting the destructed type to the object type.
4993 DestructedType = ObjectType;
4994 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4995 DestructedTypeStart);
4996 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4997 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004998 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00004999 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005000
Douglas Gregorb57fb492010-02-24 22:38:50 +00005001 // C++ [expr.pseudo]p2:
5002 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
5003 // form
5004 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005005 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00005006 //
5007 // shall designate the same scalar type.
5008 if (ScopeTypeInfo) {
5009 QualType ScopeType = ScopeTypeInfo->getType();
5010 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00005011 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005012
Abramo Bagnarabd054db2010-05-20 10:00:11 +00005013 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00005014 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00005015 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00005016 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005017
Douglas Gregorb57fb492010-02-24 22:38:50 +00005018 ScopeType = QualType();
5019 ScopeTypeInfo = 0;
5020 }
5021 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005022
John McCall9ae2f072010-08-23 23:25:46 +00005023 Expr *Result
5024 = new (Context) CXXPseudoDestructorExpr(Context, Base,
5025 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00005026 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00005027 ScopeTypeInfo,
5028 CCLoc,
5029 TildeLoc,
5030 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005031
Douglas Gregorb57fb492010-02-24 22:38:50 +00005032 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00005033 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005034
John McCall9ae2f072010-08-23 23:25:46 +00005035 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00005036}
5037
John McCall60d7b3a2010-08-24 06:29:42 +00005038ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00005039 SourceLocation OpLoc,
5040 tok::TokenKind OpKind,
5041 CXXScopeSpec &SS,
5042 UnqualifiedId &FirstTypeName,
5043 SourceLocation CCLoc,
5044 SourceLocation TildeLoc,
5045 UnqualifiedId &SecondTypeName,
5046 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00005047 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5048 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5049 "Invalid first type name in pseudo-destructor");
5050 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5051 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5052 "Invalid second type name in pseudo-destructor");
5053
Eli Friedman8c9fe202012-01-25 04:35:06 +00005054 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00005055 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5056 return ExprError();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005057
5058 // Compute the object type that we should use for name lookup purposes. Only
5059 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00005060 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005061 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00005062 if (ObjectType->isRecordType())
5063 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00005064 else if (ObjectType->isDependentType())
5065 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005066 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005067
5068 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00005069 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00005070 QualType DestructedType;
5071 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005072 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00005073 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005074 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00005075 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00005076 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005077 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005078 ((SS.isSet() && !computeDeclContext(SS, false)) ||
5079 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005080 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005081 // couldn't find anything useful in scope. Just store the identifier and
5082 // it's location, and we'll perform (qualified) name lookup again at
5083 // template instantiation time.
5084 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
5085 SecondTypeName.StartLocation);
5086 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005087 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00005088 diag::err_pseudo_dtor_destructor_non_type)
5089 << SecondTypeName.Identifier << ObjectType;
5090 if (isSFINAEContext())
5091 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005092
Douglas Gregor77549082010-02-24 21:29:12 +00005093 // Recover by assuming we had the right type all along.
5094 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00005095 } else
Douglas Gregor77549082010-02-24 21:29:12 +00005096 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005097 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00005098 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00005099 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00005100 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5101 TemplateId->getTemplateArgs(),
5102 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00005103 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +00005104 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +00005105 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00005106 TemplateId->TemplateNameLoc,
5107 TemplateId->LAngleLoc,
5108 TemplateArgsPtr,
5109 TemplateId->RAngleLoc);
5110 if (T.isInvalid() || !T.get()) {
5111 // Recover by assuming we had the right type all along.
5112 DestructedType = ObjectType;
5113 } else
5114 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005115 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005116
5117 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00005118 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005119 if (!DestructedType.isNull()) {
5120 if (!DestructedTypeInfo)
5121 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00005122 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005123 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5124 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005125
Douglas Gregorb57fb492010-02-24 22:38:50 +00005126 // Convert the name of the scope type (the type prior to '::') into a type.
5127 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00005128 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005129 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00005130 FirstTypeName.Identifier) {
5131 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005132 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00005133 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00005134 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00005135 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005136 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00005137 diag::err_pseudo_dtor_destructor_non_type)
5138 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005139
Douglas Gregorb57fb492010-02-24 22:38:50 +00005140 if (isSFINAEContext())
5141 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005142
Douglas Gregorb57fb492010-02-24 22:38:50 +00005143 // Just drop this type. It's unnecessary anyway.
5144 ScopeType = QualType();
5145 } else
5146 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005147 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00005148 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00005149 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00005150 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5151 TemplateId->getTemplateArgs(),
5152 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00005153 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +00005154 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +00005155 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00005156 TemplateId->TemplateNameLoc,
5157 TemplateId->LAngleLoc,
5158 TemplateArgsPtr,
5159 TemplateId->RAngleLoc);
5160 if (T.isInvalid() || !T.get()) {
5161 // Recover by dropping this type.
5162 ScopeType = QualType();
5163 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005164 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005165 }
5166 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005167
Douglas Gregorb4a418f2010-02-24 23:02:30 +00005168 if (!ScopeType.isNull() && !ScopeTypeInfo)
5169 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5170 FirstTypeName.StartLocation);
5171
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005172
John McCall9ae2f072010-08-23 23:25:46 +00005173 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00005174 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005175 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00005176}
5177
David Blaikie91ec7892011-12-16 16:03:09 +00005178ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5179 SourceLocation OpLoc,
5180 tok::TokenKind OpKind,
5181 SourceLocation TildeLoc,
5182 const DeclSpec& DS,
5183 bool HasTrailingLParen) {
Eli Friedman8c9fe202012-01-25 04:35:06 +00005184 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00005185 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5186 return ExprError();
5187
5188 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5189
5190 TypeLocBuilder TLB;
5191 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5192 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5193 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5194 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5195
5196 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
5197 0, SourceLocation(), TildeLoc,
5198 Destructed, HasTrailingLParen);
5199}
5200
John Wiegley429bb272011-04-08 18:41:53 +00005201ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman3f01c8a2012-03-01 01:30:04 +00005202 CXXConversionDecl *Method,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005203 bool HadMultipleCandidates) {
Eli Friedman23f02672012-03-01 04:01:32 +00005204 if (Method->getParent()->isLambda() &&
5205 Method->getConversionType()->isBlockPointerType()) {
5206 // This is a lambda coversion to block pointer; check if the argument
5207 // is a LambdaExpr.
5208 Expr *SubE = E;
5209 CastExpr *CE = dyn_cast<CastExpr>(SubE);
5210 if (CE && CE->getCastKind() == CK_NoOp)
5211 SubE = CE->getSubExpr();
5212 SubE = SubE->IgnoreParens();
5213 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
5214 SubE = BE->getSubExpr();
5215 if (isa<LambdaExpr>(SubE)) {
5216 // For the conversion to block pointer on a lambda expression, we
5217 // construct a special BlockLiteral instead; this doesn't really make
5218 // a difference in ARC, but outside of ARC the resulting block literal
5219 // follows the normal lifetime rules for block literals instead of being
5220 // autoreleased.
5221 DiagnosticErrorTrap Trap(Diags);
5222 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
5223 E->getExprLoc(),
5224 Method, E);
5225 if (Exp.isInvalid())
5226 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
5227 return Exp;
5228 }
5229 }
5230
5231
John Wiegley429bb272011-04-08 18:41:53 +00005232 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
5233 FoundDecl, Method);
5234 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005235 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00005236
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005237 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00005238 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnara960809e2011-11-16 22:46:05 +00005239 SourceLocation(), Context.BoundMemberTy,
John McCallf89e55a2010-11-18 06:31:45 +00005240 VK_RValue, OK_Ordinary);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005241 if (HadMultipleCandidates)
5242 ME->setHadMultipleCandidates(true);
5243
John McCallf89e55a2010-11-18 06:31:45 +00005244 QualType ResultType = Method->getResultType();
5245 ExprValueKind VK = Expr::getValueKindForType(ResultType);
5246 ResultType = ResultType.getNonLValueExprType(Context);
5247
Eli Friedman5f2987c2012-02-02 03:46:19 +00005248 MarkFunctionReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005249 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00005250 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00005251 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005252 return CE;
5253}
5254
Sebastian Redl2e156222010-09-10 20:55:43 +00005255ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5256 SourceLocation RParen) {
Richard Smithe6975e92012-04-17 00:58:00 +00005257 CanThrowResult CanThrow = canThrow(Operand);
Sebastian Redl2e156222010-09-10 20:55:43 +00005258 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
Richard Smithe6975e92012-04-17 00:58:00 +00005259 CanThrow, KeyLoc, RParen));
Sebastian Redl2e156222010-09-10 20:55:43 +00005260}
5261
5262ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5263 Expr *Operand, SourceLocation RParen) {
5264 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00005265}
5266
Eli Friedmane26073c2012-05-24 22:04:19 +00005267static bool IsSpecialDiscardedValue(Expr *E) {
5268 // In C++11, discarded-value expressions of a certain form are special,
5269 // according to [expr]p10:
5270 // The lvalue-to-rvalue conversion (4.1) is applied only if the
5271 // expression is an lvalue of volatile-qualified type and it has
5272 // one of the following forms:
5273 E = E->IgnoreParens();
5274
Eli Friedman02180682012-05-24 22:36:31 +00005275 // - id-expression (5.1.1),
Eli Friedmane26073c2012-05-24 22:04:19 +00005276 if (isa<DeclRefExpr>(E))
5277 return true;
5278
Eli Friedman02180682012-05-24 22:36:31 +00005279 // - subscripting (5.2.1),
Eli Friedmane26073c2012-05-24 22:04:19 +00005280 if (isa<ArraySubscriptExpr>(E))
5281 return true;
5282
Eli Friedman02180682012-05-24 22:36:31 +00005283 // - class member access (5.2.5),
Eli Friedmane26073c2012-05-24 22:04:19 +00005284 if (isa<MemberExpr>(E))
5285 return true;
5286
Eli Friedman02180682012-05-24 22:36:31 +00005287 // - indirection (5.3.1),
Eli Friedmane26073c2012-05-24 22:04:19 +00005288 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
5289 if (UO->getOpcode() == UO_Deref)
5290 return true;
5291
5292 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedman02180682012-05-24 22:36:31 +00005293 // - pointer-to-member operation (5.5),
Eli Friedmane26073c2012-05-24 22:04:19 +00005294 if (BO->isPtrMemOp())
5295 return true;
5296
Eli Friedman02180682012-05-24 22:36:31 +00005297 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmane26073c2012-05-24 22:04:19 +00005298 if (BO->getOpcode() == BO_Comma)
5299 return IsSpecialDiscardedValue(BO->getRHS());
5300 }
5301
Eli Friedman02180682012-05-24 22:36:31 +00005302 // - conditional expression (5.16) where both the second and the third
Eli Friedmane26073c2012-05-24 22:04:19 +00005303 // operands are one of the above, or
5304 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
5305 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
5306 IsSpecialDiscardedValue(CO->getFalseExpr());
5307 // The related edge case of "*x ?: *x".
5308 if (BinaryConditionalOperator *BCO =
5309 dyn_cast<BinaryConditionalOperator>(E)) {
5310 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
5311 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
5312 IsSpecialDiscardedValue(BCO->getFalseExpr());
5313 }
5314
5315 // Objective-C++ extensions to the rule.
5316 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
5317 return true;
5318
5319 return false;
5320}
5321
John McCallf6a16482010-12-04 03:47:34 +00005322/// Perform the conversions required for an expression used in a
5323/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00005324ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall3c3b7f92011-10-25 17:37:35 +00005325 if (E->hasPlaceholderType()) {
5326 ExprResult result = CheckPlaceholderExpr(E);
5327 if (result.isInvalid()) return Owned(E);
5328 E = result.take();
5329 }
5330
John McCalla878cda2010-12-02 02:07:15 +00005331 // C99 6.3.2.1:
5332 // [Except in specific positions,] an lvalue that does not have
5333 // array type is converted to the value stored in the
5334 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00005335 if (E->isRValue()) {
5336 // In C, function designators (i.e. expressions of function type)
5337 // are r-values, but we still want to do function-to-pointer decay
5338 // on them. This is both technically correct and convenient for
5339 // some clients.
David Blaikie4e4d0842012-03-11 07:00:24 +00005340 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalle6d134b2011-06-27 21:24:11 +00005341 return DefaultFunctionArrayConversion(E);
5342
5343 return Owned(E);
5344 }
John McCalla878cda2010-12-02 02:07:15 +00005345
Eli Friedmane26073c2012-05-24 22:04:19 +00005346 if (getLangOpts().CPlusPlus) {
5347 // The C++11 standard defines the notion of a discarded-value expression;
5348 // normally, we don't need to do anything to handle it, but if it is a
5349 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
5350 // conversion.
5351 if (getLangOpts().CPlusPlus0x && E->isGLValue() &&
5352 E->getType().isVolatileQualified() &&
5353 IsSpecialDiscardedValue(E)) {
5354 ExprResult Res = DefaultLvalueConversion(E);
5355 if (Res.isInvalid())
5356 return Owned(E);
5357 E = Res.take();
5358 }
5359 return Owned(E);
5360 }
John McCallf6a16482010-12-04 03:47:34 +00005361
5362 // GCC seems to also exclude expressions of incomplete enum type.
5363 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5364 if (!T->getDecl()->isComplete()) {
5365 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00005366 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
5367 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00005368 }
5369 }
5370
John Wiegley429bb272011-04-08 18:41:53 +00005371 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5372 if (Res.isInvalid())
5373 return Owned(E);
5374 E = Res.take();
5375
John McCall85515d62010-12-04 12:29:11 +00005376 if (!E->getType()->isVoidType())
5377 RequireCompleteType(E->getExprLoc(), E->getType(),
5378 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00005379 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00005380}
5381
David Blaikiedef07622012-05-16 04:20:04 +00005382ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC) {
John Wiegley429bb272011-04-08 18:41:53 +00005383 ExprResult FullExpr = Owned(FE);
5384
5385 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00005386 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00005387
John Wiegley429bb272011-04-08 18:41:53 +00005388 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00005389 return ExprError();
5390
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00005391 // Top-level message sends default to 'id' when we're in a debugger.
David Blaikie4e4d0842012-03-11 07:00:24 +00005392 if (getLangOpts().DebuggerCastResultToId &&
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00005393 FullExpr.get()->getType() == Context.UnknownAnyTy &&
5394 isa<ObjCMessageExpr>(FullExpr.get())) {
5395 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
5396 if (FullExpr.isInvalid())
5397 return ExprError();
5398 }
5399
John McCallfb8721c2011-04-10 19:13:55 +00005400 FullExpr = CheckPlaceholderExpr(FullExpr.take());
5401 if (FullExpr.isInvalid())
5402 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00005403
John Wiegley429bb272011-04-08 18:41:53 +00005404 FullExpr = IgnoredValueConversions(FullExpr.take());
5405 if (FullExpr.isInvalid())
5406 return ExprError();
5407
David Blaikiedef07622012-05-16 04:20:04 +00005408 CheckImplicitConversions(FullExpr.get(), CC);
John McCall4765fa02010-12-06 08:20:24 +00005409 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00005410}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00005411
5412StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
5413 if (!FullStmt) return StmtError();
5414
John McCall4765fa02010-12-06 08:20:24 +00005415 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00005416}
Francois Pichet1e862692011-05-06 20:48:22 +00005417
Douglas Gregorba0513d2011-10-25 01:33:02 +00005418Sema::IfExistsResult
5419Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
5420 CXXScopeSpec &SS,
5421 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet1e862692011-05-06 20:48:22 +00005422 DeclarationName TargetName = TargetNameInfo.getName();
5423 if (!TargetName)
Douglas Gregor3896fc52011-10-24 22:31:10 +00005424 return IER_DoesNotExist;
Douglas Gregorba0513d2011-10-25 01:33:02 +00005425
Douglas Gregor3896fc52011-10-24 22:31:10 +00005426 // If the name itself is dependent, then the result is dependent.
5427 if (TargetName.isDependentName())
5428 return IER_Dependent;
Douglas Gregorba0513d2011-10-25 01:33:02 +00005429
Francois Pichet1e862692011-05-06 20:48:22 +00005430 // Do the redeclaration lookup in the current scope.
5431 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
5432 Sema::NotForRedeclaration);
Douglas Gregor3896fc52011-10-24 22:31:10 +00005433 LookupParsedName(R, S, &SS);
Francois Pichet1e862692011-05-06 20:48:22 +00005434 R.suppressDiagnostics();
Douglas Gregor3896fc52011-10-24 22:31:10 +00005435
5436 switch (R.getResultKind()) {
5437 case LookupResult::Found:
5438 case LookupResult::FoundOverloaded:
5439 case LookupResult::FoundUnresolvedValue:
5440 case LookupResult::Ambiguous:
5441 return IER_Exists;
5442
5443 case LookupResult::NotFound:
5444 return IER_DoesNotExist;
5445
5446 case LookupResult::NotFoundInCurrentInstantiation:
5447 return IER_Dependent;
5448 }
David Blaikie7530c032012-01-17 06:56:22 +00005449
5450 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet1e862692011-05-06 20:48:22 +00005451}
Douglas Gregorba0513d2011-10-25 01:33:02 +00005452
Douglas Gregor65019ac2011-10-25 03:44:56 +00005453Sema::IfExistsResult
5454Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5455 bool IsIfExists, CXXScopeSpec &SS,
5456 UnqualifiedId &Name) {
Douglas Gregorba0513d2011-10-25 01:33:02 +00005457 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor65019ac2011-10-25 03:44:56 +00005458
5459 // Check for unexpanded parameter packs.
5460 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5461 collectUnexpandedParameterPacks(SS, Unexpanded);
5462 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
5463 if (!Unexpanded.empty()) {
5464 DiagnoseUnexpandedParameterPacks(KeywordLoc,
5465 IsIfExists? UPPC_IfExists
5466 : UPPC_IfNotExists,
5467 Unexpanded);
5468 return IER_Error;
5469 }
5470
Douglas Gregorba0513d2011-10-25 01:33:02 +00005471 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
5472}