1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for C++ expressions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/DeclSpec.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/Sema/Lookup.h"
18 #include "clang/Sema/ParsedTemplate.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/Sema/Scope.h"
21 #include "clang/Sema/TemplateDeduction.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/CharUnits.h"
24 #include "clang/AST/CXXInheritance.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "TypeLocBuilder.h"
33 #include "llvm/ADT/APInt.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/Support/ErrorHandling.h"
36 using namespace clang;
37 using namespace sema;
38
getDestructorName(SourceLocation TildeLoc,IdentifierInfo & II,SourceLocation NameLoc,Scope * S,CXXScopeSpec & SS,ParsedType ObjectTypePtr,bool EnteringContext)39 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
40 IdentifierInfo &II,
41 SourceLocation NameLoc,
42 Scope *S, CXXScopeSpec &SS,
43 ParsedType ObjectTypePtr,
44 bool EnteringContext) {
45 // Determine where to perform name lookup.
46
47 // FIXME: This area of the standard is very messy, and the current
48 // wording is rather unclear about which scopes we search for the
49 // destructor name; see core issues 399 and 555. Issue 399 in
50 // particular shows where the current description of destructor name
51 // lookup is completely out of line with existing practice, e.g.,
52 // this appears to be ill-formed:
53 //
54 // namespace N {
55 // template <typename T> struct S {
56 // ~S();
57 // };
58 // }
59 //
60 // void f(N::S<int>* s) {
61 // s->N::S<int>::~S();
62 // }
63 //
64 // See also PR6358 and PR6359.
65 // For this reason, we're currently only doing the C++03 version of this
66 // code; the C++0x version has to wait until we get a proper spec.
67 QualType SearchType;
68 DeclContext *LookupCtx = 0;
69 bool isDependent = false;
70 bool LookInScope = false;
71
72 // If we have an object type, it's because we are in a
73 // pseudo-destructor-expression or a member access expression, and
74 // we know what type we're looking for.
75 if (ObjectTypePtr)
76 SearchType = GetTypeFromParser(ObjectTypePtr);
77
78 if (SS.isSet()) {
79 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
80
81 bool AlreadySearched = false;
82 bool LookAtPrefix = true;
83 // C++ [basic.lookup.qual]p6:
84 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
85 // the type-names are looked up as types in the scope designated by the
86 // nested-name-specifier. In a qualified-id of the form:
87 //
88 // ::[opt] nested-name-specifier ~ class-name
89 //
90 // where the nested-name-specifier designates a namespace scope, and in
91 // a qualified-id of the form:
92 //
93 // ::opt nested-name-specifier class-name :: ~ class-name
94 //
95 // the class-names are looked up as types in the scope designated by
96 // the nested-name-specifier.
97 //
98 // Here, we check the first case (completely) and determine whether the
99 // code below is permitted to look at the prefix of the
100 // nested-name-specifier.
101 DeclContext *DC = computeDeclContext(SS, EnteringContext);
102 if (DC && DC->isFileContext()) {
103 AlreadySearched = true;
104 LookupCtx = DC;
105 isDependent = false;
106 } else if (DC && isa<CXXRecordDecl>(DC))
107 LookAtPrefix = false;
108
109 // The second case from the C++03 rules quoted further above.
110 NestedNameSpecifier *Prefix = 0;
111 if (AlreadySearched) {
112 // Nothing left to do.
113 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
114 CXXScopeSpec PrefixSS;
115 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
116 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
117 isDependent = isDependentScopeSpecifier(PrefixSS);
118 } else if (ObjectTypePtr) {
119 LookupCtx = computeDeclContext(SearchType);
120 isDependent = SearchType->isDependentType();
121 } else {
122 LookupCtx = computeDeclContext(SS, EnteringContext);
123 isDependent = LookupCtx && LookupCtx->isDependentContext();
124 }
125
126 LookInScope = false;
127 } else if (ObjectTypePtr) {
128 // C++ [basic.lookup.classref]p3:
129 // If the unqualified-id is ~type-name, the type-name is looked up
130 // in the context of the entire postfix-expression. If the type T
131 // of the object expression is of a class type C, the type-name is
132 // also looked up in the scope of class C. At least one of the
133 // lookups shall find a name that refers to (possibly
134 // cv-qualified) T.
135 LookupCtx = computeDeclContext(SearchType);
136 isDependent = SearchType->isDependentType();
137 assert((isDependent || !SearchType->isIncompleteType()) &&
138 "Caller should have completed object type");
139
140 LookInScope = true;
141 } else {
142 // Perform lookup into the current scope (only).
143 LookInScope = true;
144 }
145
146 TypeDecl *NonMatchingTypeDecl = 0;
147 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
148 for (unsigned Step = 0; Step != 2; ++Step) {
149 // Look for the name first in the computed lookup context (if we
150 // have one) and, if that fails to find a match, in the scope (if
151 // we're allowed to look there).
152 Found.clear();
153 if (Step == 0 && LookupCtx)
154 LookupQualifiedName(Found, LookupCtx);
155 else if (Step == 1 && LookInScope && S)
156 LookupName(Found, S);
157 else
158 continue;
159
160 // FIXME: Should we be suppressing ambiguities here?
161 if (Found.isAmbiguous())
162 return ParsedType();
163
164 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
165 QualType T = Context.getTypeDeclType(Type);
166
167 if (SearchType.isNull() || SearchType->isDependentType() ||
168 Context.hasSameUnqualifiedType(T, SearchType)) {
169 // We found our type!
170
171 return ParsedType::make(T);
172 }
173
174 if (!SearchType.isNull())
175 NonMatchingTypeDecl = Type;
176 }
177
178 // If the name that we found is a class template name, and it is
179 // the same name as the template name in the last part of the
180 // nested-name-specifier (if present) or the object type, then
181 // this is the destructor for that class.
182 // FIXME: This is a workaround until we get real drafting for core
183 // issue 399, for which there isn't even an obvious direction.
184 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
185 QualType MemberOfType;
186 if (SS.isSet()) {
187 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
188 // Figure out the type of the context, if it has one.
189 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
190 MemberOfType = Context.getTypeDeclType(Record);
191 }
192 }
193 if (MemberOfType.isNull())
194 MemberOfType = SearchType;
195
196 if (MemberOfType.isNull())
197 continue;
198
199 // We're referring into a class template specialization. If the
200 // class template we found is the same as the template being
201 // specialized, we found what we are looking for.
202 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
203 if (ClassTemplateSpecializationDecl *Spec
204 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
205 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
206 Template->getCanonicalDecl())
207 return ParsedType::make(MemberOfType);
208 }
209
210 continue;
211 }
212
213 // We're referring to an unresolved class template
214 // specialization. Determine whether we class template we found
215 // is the same as the template being specialized or, if we don't
216 // know which template is being specialized, that it at least
217 // has the same name.
218 if (const TemplateSpecializationType *SpecType
219 = MemberOfType->getAs<TemplateSpecializationType>()) {
220 TemplateName SpecName = SpecType->getTemplateName();
221
222 // The class template we found is the same template being
223 // specialized.
224 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
225 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
226 return ParsedType::make(MemberOfType);
227
228 continue;
229 }
230
231 // The class template we found has the same name as the
232 // (dependent) template name being specialized.
233 if (DependentTemplateName *DepTemplate
234 = SpecName.getAsDependentTemplateName()) {
235 if (DepTemplate->isIdentifier() &&
236 DepTemplate->getIdentifier() == Template->getIdentifier())
237 return ParsedType::make(MemberOfType);
238
239 continue;
240 }
241 }
242 }
243 }
244
245 if (isDependent) {
246 // We didn't find our type, but that's okay: it's dependent
247 // anyway.
248
249 // FIXME: What if we have no nested-name-specifier?
250 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
251 SS.getWithLocInContext(Context),
252 II, NameLoc);
253 return ParsedType::make(T);
254 }
255
256 if (NonMatchingTypeDecl) {
257 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
258 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
259 << T << SearchType;
260 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
261 << T;
262 } else if (ObjectTypePtr)
263 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
264 << &II;
265 else
266 Diag(NameLoc, diag::err_destructor_class_name);
267
268 return ParsedType();
269 }
270
getDestructorType(const DeclSpec & DS,ParsedType ObjectType)271 ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
272 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
273 return ParsedType();
274 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
275 && "only get destructor types from declspecs");
276 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
277 QualType SearchType = GetTypeFromParser(ObjectType);
278 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
279 return ParsedType::make(T);
280 }
281
282 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
283 << T << SearchType;
284 return ParsedType();
285 }
286
287 /// \brief Build a C++ typeid expression with a type operand.
BuildCXXTypeId(QualType TypeInfoType,SourceLocation TypeidLoc,TypeSourceInfo * Operand,SourceLocation RParenLoc)288 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
289 SourceLocation TypeidLoc,
290 TypeSourceInfo *Operand,
291 SourceLocation RParenLoc) {
292 // C++ [expr.typeid]p4:
293 // The top-level cv-qualifiers of the lvalue expression or the type-id
294 // that is the operand of typeid are always ignored.
295 // If the type of the type-id is a class type or a reference to a class
296 // type, the class shall be completely-defined.
297 Qualifiers Quals;
298 QualType T
299 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
300 Quals);
301 if (T->getAs<RecordType>() &&
302 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
303 return ExprError();
304
305 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
306 Operand,
307 SourceRange(TypeidLoc, RParenLoc)));
308 }
309
310 /// \brief Build a C++ typeid expression with an expression operand.
BuildCXXTypeId(QualType TypeInfoType,SourceLocation TypeidLoc,Expr * E,SourceLocation RParenLoc)311 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
312 SourceLocation TypeidLoc,
313 Expr *E,
314 SourceLocation RParenLoc) {
315 if (E && !E->isTypeDependent()) {
316 if (E->getType()->isPlaceholderType()) {
317 ExprResult result = CheckPlaceholderExpr(E);
318 if (result.isInvalid()) return ExprError();
319 E = result.take();
320 }
321
322 QualType T = E->getType();
323 if (const RecordType *RecordT = T->getAs<RecordType>()) {
324 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
325 // C++ [expr.typeid]p3:
326 // [...] If the type of the expression is a class type, the class
327 // shall be completely-defined.
328 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
329 return ExprError();
330
331 // C++ [expr.typeid]p3:
332 // When typeid is applied to an expression other than an glvalue of a
333 // polymorphic class type [...] [the] expression is an unevaluated
334 // operand. [...]
335 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
336 // The subexpression is potentially evaluated; switch the context
337 // and recheck the subexpression.
338 ExprResult Result = TranformToPotentiallyEvaluated(E);
339 if (Result.isInvalid()) return ExprError();
340 E = Result.take();
341
342 // We require a vtable to query the type at run time.
343 MarkVTableUsed(TypeidLoc, RecordD);
344 }
345 }
346
347 // C++ [expr.typeid]p4:
348 // [...] If the type of the type-id is a reference to a possibly
349 // cv-qualified type, the result of the typeid expression refers to a
350 // std::type_info object representing the cv-unqualified referenced
351 // type.
352 Qualifiers Quals;
353 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
354 if (!Context.hasSameType(T, UnqualT)) {
355 T = UnqualT;
356 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
357 }
358 }
359
360 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
361 E,
362 SourceRange(TypeidLoc, RParenLoc)));
363 }
364
365 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
366 ExprResult
ActOnCXXTypeid(SourceLocation OpLoc,SourceLocation LParenLoc,bool isType,void * TyOrExpr,SourceLocation RParenLoc)367 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
368 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
369 // Find the std::type_info type.
370 if (!getStdNamespace())
371 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
372
373 if (!CXXTypeInfoDecl) {
374 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
375 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
376 LookupQualifiedName(R, getStdNamespace());
377 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
378 if (!CXXTypeInfoDecl)
379 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
380 }
381
382 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
383
384 if (isType) {
385 // The operand is a type; handle it as such.
386 TypeSourceInfo *TInfo = 0;
387 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
388 &TInfo);
389 if (T.isNull())
390 return ExprError();
391
392 if (!TInfo)
393 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
394
395 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
396 }
397
398 // The operand is an expression.
399 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
400 }
401
402 /// Retrieve the UuidAttr associated with QT.
GetUuidAttrOfType(QualType QT)403 static UuidAttr *GetUuidAttrOfType(QualType QT) {
404 // Optionally remove one level of pointer, reference or array indirection.
405 const Type *Ty = QT.getTypePtr();;
406 if (QT->isPointerType() || QT->isReferenceType())
407 Ty = QT->getPointeeType().getTypePtr();
408 else if (QT->isArrayType())
409 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
410
411 // Loop all record redeclaration looking for an uuid attribute.
412 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
413 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
414 E = RD->redecls_end(); I != E; ++I) {
415 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
416 return Uuid;
417 }
418
419 return 0;
420 }
421
422 /// \brief Build a Microsoft __uuidof expression with a type operand.
BuildCXXUuidof(QualType TypeInfoType,SourceLocation TypeidLoc,TypeSourceInfo * Operand,SourceLocation RParenLoc)423 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
424 SourceLocation TypeidLoc,
425 TypeSourceInfo *Operand,
426 SourceLocation RParenLoc) {
427 if (!Operand->getType()->isDependentType()) {
428 if (!GetUuidAttrOfType(Operand->getType()))
429 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
430 }
431
432 // FIXME: add __uuidof semantic analysis for type operand.
433 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
434 Operand,
435 SourceRange(TypeidLoc, RParenLoc)));
436 }
437
438 /// \brief Build a Microsoft __uuidof expression with an expression operand.
BuildCXXUuidof(QualType TypeInfoType,SourceLocation TypeidLoc,Expr * E,SourceLocation RParenLoc)439 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
440 SourceLocation TypeidLoc,
441 Expr *E,
442 SourceLocation RParenLoc) {
443 if (!E->getType()->isDependentType()) {
444 if (!GetUuidAttrOfType(E->getType()) &&
445 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
446 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
447 }
448 // FIXME: add __uuidof semantic analysis for type operand.
449 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
450 E,
451 SourceRange(TypeidLoc, RParenLoc)));
452 }
453
454 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
455 ExprResult
ActOnCXXUuidof(SourceLocation OpLoc,SourceLocation LParenLoc,bool isType,void * TyOrExpr,SourceLocation RParenLoc)456 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
457 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
458 // If MSVCGuidDecl has not been cached, do the lookup.
459 if (!MSVCGuidDecl) {
460 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
461 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
462 LookupQualifiedName(R, Context.getTranslationUnitDecl());
463 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
464 if (!MSVCGuidDecl)
465 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
466 }
467
468 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
469
470 if (isType) {
471 // The operand is a type; handle it as such.
472 TypeSourceInfo *TInfo = 0;
473 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
474 &TInfo);
475 if (T.isNull())
476 return ExprError();
477
478 if (!TInfo)
479 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
480
481 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
482 }
483
484 // The operand is an expression.
485 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
486 }
487
488 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
489 ExprResult
ActOnCXXBoolLiteral(SourceLocation OpLoc,tok::TokenKind Kind)490 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
491 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
492 "Unknown C++ Boolean value!");
493 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
494 Context.BoolTy, OpLoc));
495 }
496
497 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
498 ExprResult
ActOnCXXNullPtrLiteral(SourceLocation Loc)499 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
500 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
501 }
502
503 /// ActOnCXXThrow - Parse throw expressions.
504 ExprResult
ActOnCXXThrow(Scope * S,SourceLocation OpLoc,Expr * Ex)505 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
506 bool IsThrownVarInScope = false;
507 if (Ex) {
508 // C++0x [class.copymove]p31:
509 // When certain criteria are met, an implementation is allowed to omit the
510 // copy/move construction of a class object [...]
511 //
512 // - in a throw-expression, when the operand is the name of a
513 // non-volatile automatic object (other than a function or catch-
514 // clause parameter) whose scope does not extend beyond the end of the
515 // innermost enclosing try-block (if there is one), the copy/move
516 // operation from the operand to the exception object (15.1) can be
517 // omitted by constructing the automatic object directly into the
518 // exception object
519 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
520 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
521 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
522 for( ; S; S = S->getParent()) {
523 if (S->isDeclScope(Var)) {
524 IsThrownVarInScope = true;
525 break;
526 }
527
528 if (S->getFlags() &
529 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
530 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
531 Scope::TryScope))
532 break;
533 }
534 }
535 }
536 }
537
538 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
539 }
540
BuildCXXThrow(SourceLocation OpLoc,Expr * Ex,bool IsThrownVarInScope)541 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
542 bool IsThrownVarInScope) {
543 // Don't report an error if 'throw' is used in system headers.
544 if (!getLangOpts().CXXExceptions &&
545 !getSourceManager().isInSystemHeader(OpLoc))
546 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
547
548 if (Ex && !Ex->isTypeDependent()) {
549 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
550 if (ExRes.isInvalid())
551 return ExprError();
552 Ex = ExRes.take();
553 }
554
555 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
556 IsThrownVarInScope));
557 }
558
559 /// CheckCXXThrowOperand - Validate the operand of a throw.
CheckCXXThrowOperand(SourceLocation ThrowLoc,Expr * E,bool IsThrownVarInScope)560 ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
561 bool IsThrownVarInScope) {
562 // C++ [except.throw]p3:
563 // A throw-expression initializes a temporary object, called the exception
564 // object, the type of which is determined by removing any top-level
565 // cv-qualifiers from the static type of the operand of throw and adjusting
566 // the type from "array of T" or "function returning T" to "pointer to T"
567 // or "pointer to function returning T", [...]
568 if (E->getType().hasQualifiers())
569 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
570 E->getValueKind()).take();
571
572 ExprResult Res = DefaultFunctionArrayConversion(E);
573 if (Res.isInvalid())
574 return ExprError();
575 E = Res.take();
576
577 // If the type of the exception would be an incomplete type or a pointer
578 // to an incomplete type other than (cv) void the program is ill-formed.
579 QualType Ty = E->getType();
580 bool isPointer = false;
581 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
582 Ty = Ptr->getPointeeType();
583 isPointer = true;
584 }
585 if (!isPointer || !Ty->isVoidType()) {
586 if (RequireCompleteType(ThrowLoc, Ty,
587 PDiag(isPointer ? diag::err_throw_incomplete_ptr
588 : diag::err_throw_incomplete)
589 << E->getSourceRange()))
590 return ExprError();
591
592 if (RequireNonAbstractType(ThrowLoc, E->getType(),
593 PDiag(diag::err_throw_abstract_type)
594 << E->getSourceRange()))
595 return ExprError();
596 }
597
598 // Initialize the exception result. This implicitly weeds out
599 // abstract types or types with inaccessible copy constructors.
600
601 // C++0x [class.copymove]p31:
602 // When certain criteria are met, an implementation is allowed to omit the
603 // copy/move construction of a class object [...]
604 //
605 // - in a throw-expression, when the operand is the name of a
606 // non-volatile automatic object (other than a function or catch-clause
607 // parameter) whose scope does not extend beyond the end of the
608 // innermost enclosing try-block (if there is one), the copy/move
609 // operation from the operand to the exception object (15.1) can be
610 // omitted by constructing the automatic object directly into the
611 // exception object
612 const VarDecl *NRVOVariable = 0;
613 if (IsThrownVarInScope)
614 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
615
616 InitializedEntity Entity =
617 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
618 /*NRVO=*/NRVOVariable != 0);
619 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
620 QualType(), E,
621 IsThrownVarInScope);
622 if (Res.isInvalid())
623 return ExprError();
624 E = Res.take();
625
626 // If the exception has class type, we need additional handling.
627 const RecordType *RecordTy = Ty->getAs<RecordType>();
628 if (!RecordTy)
629 return Owned(E);
630 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
631
632 // If we are throwing a polymorphic class type or pointer thereof,
633 // exception handling will make use of the vtable.
634 MarkVTableUsed(ThrowLoc, RD);
635
636 // If a pointer is thrown, the referenced object will not be destroyed.
637 if (isPointer)
638 return Owned(E);
639
640 // If the class has a destructor, we must be able to call it.
641 if (RD->hasIrrelevantDestructor())
642 return Owned(E);
643
644 CXXDestructorDecl *Destructor = LookupDestructor(RD);
645 if (!Destructor)
646 return Owned(E);
647
648 MarkFunctionReferenced(E->getExprLoc(), Destructor);
649 CheckDestructorAccess(E->getExprLoc(), Destructor,
650 PDiag(diag::err_access_dtor_exception) << Ty);
651 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
652 return Owned(E);
653 }
654
getCurrentThisType()655 QualType Sema::getCurrentThisType() {
656 DeclContext *DC = getFunctionLevelDeclContext();
657 QualType ThisTy = CXXThisTypeOverride;
658 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
659 if (method && method->isInstance())
660 ThisTy = method->getThisType(Context);
661 }
662
663 return ThisTy;
664 }
665
CXXThisScopeRAII(Sema & S,Decl * ContextDecl,unsigned CXXThisTypeQuals,bool Enabled)666 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
667 Decl *ContextDecl,
668 unsigned CXXThisTypeQuals,
669 bool Enabled)
670 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
671 {
672 if (!Enabled || !ContextDecl)
673 return;
674
675 CXXRecordDecl *Record = 0;
676 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
677 Record = Template->getTemplatedDecl();
678 else
679 Record = cast<CXXRecordDecl>(ContextDecl);
680
681 S.CXXThisTypeOverride
682 = S.Context.getPointerType(
683 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
684
685 this->Enabled = true;
686 }
687
688
~CXXThisScopeRAII()689 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
690 if (Enabled) {
691 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
692 }
693 }
694
CheckCXXThisCapture(SourceLocation Loc,bool Explicit)695 void Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit) {
696 // We don't need to capture this in an unevaluated context.
697 if (ExprEvalContexts.back().Context == Unevaluated && !Explicit)
698 return;
699
700 // Otherwise, check that we can capture 'this'.
701 unsigned NumClosures = 0;
702 for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) {
703 if (CapturingScopeInfo *CSI =
704 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
705 if (CSI->CXXThisCaptureIndex != 0) {
706 // 'this' is already being captured; there isn't anything more to do.
707 break;
708 }
709
710 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
711 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
712 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
713 Explicit) {
714 // This closure can capture 'this'; continue looking upwards.
715 NumClosures++;
716 Explicit = false;
717 continue;
718 }
719 // This context can't implicitly capture 'this'; fail out.
720 Diag(Loc, diag::err_this_capture) << Explicit;
721 return;
722 }
723 break;
724 }
725
726 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
727 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
728 // contexts.
729 for (unsigned idx = FunctionScopes.size() - 1;
730 NumClosures; --idx, --NumClosures) {
731 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
732 Expr *ThisExpr = 0;
733 QualType ThisTy = getCurrentThisType();
734 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
735 // For lambda expressions, build a field and an initializing expression.
736 CXXRecordDecl *Lambda = LSI->Lambda;
737 FieldDecl *Field
738 = FieldDecl::Create(Context, Lambda, Loc, Loc, 0, ThisTy,
739 Context.getTrivialTypeSourceInfo(ThisTy, Loc),
740 0, false, false);
741 Field->setImplicit(true);
742 Field->setAccess(AS_private);
743 Lambda->addDecl(Field);
744 ThisExpr = new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/true);
745 }
746 bool isNested = NumClosures > 1;
747 CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
748 }
749 }
750
ActOnCXXThis(SourceLocation Loc)751 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
752 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
753 /// is a non-lvalue expression whose value is the address of the object for
754 /// which the function is called.
755
756 QualType ThisTy = getCurrentThisType();
757 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
758
759 CheckCXXThisCapture(Loc);
760 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
761 }
762
isThisOutsideMemberFunctionBody(QualType BaseType)763 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
764 // If we're outside the body of a member function, then we'll have a specified
765 // type for 'this'.
766 if (CXXThisTypeOverride.isNull())
767 return false;
768
769 // Determine whether we're looking into a class that's currently being
770 // defined.
771 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
772 return Class && Class->isBeingDefined();
773 }
774
775 ExprResult
ActOnCXXTypeConstructExpr(ParsedType TypeRep,SourceLocation LParenLoc,MultiExprArg exprs,SourceLocation RParenLoc)776 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
777 SourceLocation LParenLoc,
778 MultiExprArg exprs,
779 SourceLocation RParenLoc) {
780 if (!TypeRep)
781 return ExprError();
782
783 TypeSourceInfo *TInfo;
784 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
785 if (!TInfo)
786 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
787
788 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
789 }
790
791 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
792 /// Can be interpreted either as function-style casting ("int(x)")
793 /// or class type construction ("ClassType(x,y,z)")
794 /// or creation of a value-initialized type ("int()").
795 ExprResult
BuildCXXTypeConstructExpr(TypeSourceInfo * TInfo,SourceLocation LParenLoc,MultiExprArg exprs,SourceLocation RParenLoc)796 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
797 SourceLocation LParenLoc,
798 MultiExprArg exprs,
799 SourceLocation RParenLoc) {
800 QualType Ty = TInfo->getType();
801 unsigned NumExprs = exprs.size();
802 Expr **Exprs = (Expr**)exprs.get();
803 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
804
805 if (Ty->isDependentType() ||
806 CallExpr::hasAnyTypeDependentArguments(
807 llvm::makeArrayRef(Exprs, NumExprs))) {
808 exprs.release();
809
810 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
811 LParenLoc,
812 Exprs, NumExprs,
813 RParenLoc));
814 }
815
816 bool ListInitialization = LParenLoc.isInvalid();
817 assert((!ListInitialization || (NumExprs == 1 && isa<InitListExpr>(Exprs[0])))
818 && "List initialization must have initializer list as expression.");
819 SourceRange FullRange = SourceRange(TyBeginLoc,
820 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
821
822 // C++ [expr.type.conv]p1:
823 // If the expression list is a single expression, the type conversion
824 // expression is equivalent (in definedness, and if defined in meaning) to the
825 // corresponding cast expression.
826 if (NumExprs == 1 && !ListInitialization) {
827 Expr *Arg = Exprs[0];
828 exprs.release();
829 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
830 }
831
832 QualType ElemTy = Ty;
833 if (Ty->isArrayType()) {
834 if (!ListInitialization)
835 return ExprError(Diag(TyBeginLoc,
836 diag::err_value_init_for_array_type) << FullRange);
837 ElemTy = Context.getBaseElementType(Ty);
838 }
839
840 if (!Ty->isVoidType() &&
841 RequireCompleteType(TyBeginLoc, ElemTy,
842 PDiag(diag::err_invalid_incomplete_type_use)
843 << FullRange))
844 return ExprError();
845
846 if (RequireNonAbstractType(TyBeginLoc, Ty,
847 diag::err_allocation_of_abstract_type))
848 return ExprError();
849
850 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
851 InitializationKind Kind
852 = NumExprs ? ListInitialization
853 ? InitializationKind::CreateDirectList(TyBeginLoc)
854 : InitializationKind::CreateDirect(TyBeginLoc,
855 LParenLoc, RParenLoc)
856 : InitializationKind::CreateValue(TyBeginLoc,
857 LParenLoc, RParenLoc);
858 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
859 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
860
861 if (!Result.isInvalid() && ListInitialization &&
862 isa<InitListExpr>(Result.get())) {
863 // If the list-initialization doesn't involve a constructor call, we'll get
864 // the initializer-list (with corrected type) back, but that's not what we
865 // want, since it will be treated as an initializer list in further
866 // processing. Explicitly insert a cast here.
867 InitListExpr *List = cast<InitListExpr>(Result.take());
868 Result = Owned(CXXFunctionalCastExpr::Create(Context, List->getType(),
869 Expr::getValueKindForType(TInfo->getType()),
870 TInfo, TyBeginLoc, CK_NoOp,
871 List, /*Path=*/0, RParenLoc));
872 }
873
874 // FIXME: Improve AST representation?
875 return move(Result);
876 }
877
878 /// doesUsualArrayDeleteWantSize - Answers whether the usual
879 /// operator delete[] for the given type has a size_t parameter.
doesUsualArrayDeleteWantSize(Sema & S,SourceLocation loc,QualType allocType)880 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
881 QualType allocType) {
882 const RecordType *record =
883 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
884 if (!record) return false;
885
886 // Try to find an operator delete[] in class scope.
887
888 DeclarationName deleteName =
889 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
890 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
891 S.LookupQualifiedName(ops, record->getDecl());
892
893 // We're just doing this for information.
894 ops.suppressDiagnostics();
895
896 // Very likely: there's no operator delete[].
897 if (ops.empty()) return false;
898
899 // If it's ambiguous, it should be illegal to call operator delete[]
900 // on this thing, so it doesn't matter if we allocate extra space or not.
901 if (ops.isAmbiguous()) return false;
902
903 LookupResult::Filter filter = ops.makeFilter();
904 while (filter.hasNext()) {
905 NamedDecl *del = filter.next()->getUnderlyingDecl();
906
907 // C++0x [basic.stc.dynamic.deallocation]p2:
908 // A template instance is never a usual deallocation function,
909 // regardless of its signature.
910 if (isa<FunctionTemplateDecl>(del)) {
911 filter.erase();
912 continue;
913 }
914
915 // C++0x [basic.stc.dynamic.deallocation]p2:
916 // If class T does not declare [an operator delete[] with one
917 // parameter] but does declare a member deallocation function
918 // named operator delete[] with exactly two parameters, the
919 // second of which has type std::size_t, then this function
920 // is a usual deallocation function.
921 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
922 filter.erase();
923 continue;
924 }
925 }
926 filter.done();
927
928 if (!ops.isSingleResult()) return false;
929
930 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
931 return (del->getNumParams() == 2);
932 }
933
934 /// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
935
936 /// E.g.:
937 /// @code new (memory) int[size][4] @endcode
938 /// or
939 /// @code ::new Foo(23, "hello") @endcode
940 ///
941 /// \param StartLoc The first location of the expression.
942 /// \param UseGlobal True if 'new' was prefixed with '::'.
943 /// \param PlacementLParen Opening paren of the placement arguments.
944 /// \param PlacementArgs Placement new arguments.
945 /// \param PlacementRParen Closing paren of the placement arguments.
946 /// \param TypeIdParens If the type is in parens, the source range.
947 /// \param D The type to be allocated, as well as array dimensions.
948 /// \param ConstructorLParen Opening paren of the constructor args, empty if
949 /// initializer-list syntax is used.
950 /// \param ConstructorArgs Constructor/initialization arguments.
951 /// \param ConstructorRParen Closing paren of the constructor args.
952 ExprResult
ActOnCXXNew(SourceLocation StartLoc,bool UseGlobal,SourceLocation PlacementLParen,MultiExprArg PlacementArgs,SourceLocation PlacementRParen,SourceRange TypeIdParens,Declarator & D,Expr * Initializer)953 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
954 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
955 SourceLocation PlacementRParen, SourceRange TypeIdParens,
956 Declarator &D, Expr *Initializer) {
957 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
958
959 Expr *ArraySize = 0;
960 // If the specified type is an array, unwrap it and save the expression.
961 if (D.getNumTypeObjects() > 0 &&
962 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
963 DeclaratorChunk &Chunk = D.getTypeObject(0);
964 if (TypeContainsAuto)
965 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
966 << D.getSourceRange());
967 if (Chunk.Arr.hasStatic)
968 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
969 << D.getSourceRange());
970 if (!Chunk.Arr.NumElts)
971 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
972 << D.getSourceRange());
973
974 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
975 D.DropFirstTypeObject();
976 }
977
978 // Every dimension shall be of constant size.
979 if (ArraySize) {
980 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
981 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
982 break;
983
984 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
985 if (Expr *NumElts = (Expr *)Array.NumElts) {
986 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
987 Array.NumElts = VerifyIntegerConstantExpression(NumElts, 0,
988 PDiag(diag::err_new_array_nonconst)).take();
989 if (!Array.NumElts)
990 return ExprError();
991 }
992 }
993 }
994 }
995
996 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
997 QualType AllocType = TInfo->getType();
998 if (D.isInvalidType())
999 return ExprError();
1000
1001 SourceRange DirectInitRange;
1002 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1003 DirectInitRange = List->getSourceRange();
1004
1005 return BuildCXXNew(StartLoc, UseGlobal,
1006 PlacementLParen,
1007 move(PlacementArgs),
1008 PlacementRParen,
1009 TypeIdParens,
1010 AllocType,
1011 TInfo,
1012 ArraySize,
1013 DirectInitRange,
1014 Initializer,
1015 TypeContainsAuto);
1016 }
1017
isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,Expr * Init)1018 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1019 Expr *Init) {
1020 if (!Init)
1021 return true;
1022 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1023 return PLE->getNumExprs() == 0;
1024 if (isa<ImplicitValueInitExpr>(Init))
1025 return true;
1026 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1027 return !CCE->isListInitialization() &&
1028 CCE->getConstructor()->isDefaultConstructor();
1029 else if (Style == CXXNewExpr::ListInit) {
1030 assert(isa<InitListExpr>(Init) &&
1031 "Shouldn't create list CXXConstructExprs for arrays.");
1032 return true;
1033 }
1034 return false;
1035 }
1036
1037 ExprResult
BuildCXXNew(SourceLocation StartLoc,bool UseGlobal,SourceLocation PlacementLParen,MultiExprArg PlacementArgs,SourceLocation PlacementRParen,SourceRange TypeIdParens,QualType AllocType,TypeSourceInfo * AllocTypeInfo,Expr * ArraySize,SourceRange DirectInitRange,Expr * Initializer,bool TypeMayContainAuto)1038 Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
1039 SourceLocation PlacementLParen,
1040 MultiExprArg PlacementArgs,
1041 SourceLocation PlacementRParen,
1042 SourceRange TypeIdParens,
1043 QualType AllocType,
1044 TypeSourceInfo *AllocTypeInfo,
1045 Expr *ArraySize,
1046 SourceRange DirectInitRange,
1047 Expr *Initializer,
1048 bool TypeMayContainAuto) {
1049 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1050
1051 CXXNewExpr::InitializationStyle initStyle;
1052 if (DirectInitRange.isValid()) {
1053 assert(Initializer && "Have parens but no initializer.");
1054 initStyle = CXXNewExpr::CallInit;
1055 } else if (Initializer && isa<InitListExpr>(Initializer))
1056 initStyle = CXXNewExpr::ListInit;
1057 else {
1058 // In template instantiation, the initializer could be a CXXDefaultArgExpr
1059 // unwrapped from a CXXConstructExpr that was implicitly built. There is no
1060 // particularly sane way we can handle this (especially since it can even
1061 // occur for array new), so we throw the initializer away and have it be
1062 // rebuilt.
1063 if (Initializer && isa<CXXDefaultArgExpr>(Initializer))
1064 Initializer = 0;
1065 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1066 isa<CXXConstructExpr>(Initializer)) &&
1067 "Initializer expression that cannot have been implicitly created.");
1068 initStyle = CXXNewExpr::NoInit;
1069 }
1070
1071 Expr **Inits = &Initializer;
1072 unsigned NumInits = Initializer ? 1 : 0;
1073 if (initStyle == CXXNewExpr::CallInit) {
1074 if (ParenListExpr *List = dyn_cast<ParenListExpr>(Initializer)) {
1075 Inits = List->getExprs();
1076 NumInits = List->getNumExprs();
1077 } else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Initializer)){
1078 if (!isa<CXXTemporaryObjectExpr>(CCE)) {
1079 // Can happen in template instantiation. Since this is just an implicit
1080 // construction, we just take it apart and rebuild it.
1081 Inits = CCE->getArgs();
1082 NumInits = CCE->getNumArgs();
1083 }
1084 }
1085 }
1086
1087 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1088 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
1089 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1090 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1091 << AllocType << TypeRange);
1092 if (initStyle == CXXNewExpr::ListInit)
1093 return ExprError(Diag(Inits[0]->getLocStart(),
1094 diag::err_auto_new_requires_parens)
1095 << AllocType << TypeRange);
1096 if (NumInits > 1) {
1097 Expr *FirstBad = Inits[1];
1098 return ExprError(Diag(FirstBad->getLocStart(),
1099 diag::err_auto_new_ctor_multiple_expressions)
1100 << AllocType << TypeRange);
1101 }
1102 Expr *Deduce = Inits[0];
1103 TypeSourceInfo *DeducedType = 0;
1104 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) ==
1105 DAR_Failed)
1106 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1107 << AllocType << Deduce->getType()
1108 << TypeRange << Deduce->getSourceRange());
1109 if (!DeducedType)
1110 return ExprError();
1111
1112 AllocTypeInfo = DeducedType;
1113 AllocType = AllocTypeInfo->getType();
1114 }
1115
1116 // Per C++0x [expr.new]p5, the type being constructed may be a
1117 // typedef of an array type.
1118 if (!ArraySize) {
1119 if (const ConstantArrayType *Array
1120 = Context.getAsConstantArrayType(AllocType)) {
1121 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1122 Context.getSizeType(),
1123 TypeRange.getEnd());
1124 AllocType = Array->getElementType();
1125 }
1126 }
1127
1128 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1129 return ExprError();
1130
1131 if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) {
1132 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1133 diag::warn_dangling_std_initializer_list)
1134 << /*at end of FE*/0 << Inits[0]->getSourceRange();
1135 }
1136
1137 // In ARC, infer 'retaining' for the allocated
1138 if (getLangOpts().ObjCAutoRefCount &&
1139 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1140 AllocType->isObjCLifetimeType()) {
1141 AllocType = Context.getLifetimeQualifiedType(AllocType,
1142 AllocType->getObjCARCImplicitLifetime());
1143 }
1144
1145 QualType ResultType = Context.getPointerType(AllocType);
1146
1147 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1148 // integral or enumeration type with a non-negative value."
1149 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1150 // enumeration type, or a class type for which a single non-explicit
1151 // conversion function to integral or unscoped enumeration type exists.
1152 if (ArraySize && !ArraySize->isTypeDependent()) {
1153 ExprResult ConvertedSize = ConvertToIntegralOrEnumerationType(
1154 StartLoc, ArraySize,
1155 PDiag(diag::err_array_size_not_integral) << getLangOpts().CPlusPlus0x,
1156 PDiag(diag::err_array_size_incomplete_type)
1157 << ArraySize->getSourceRange(),
1158 PDiag(diag::err_array_size_explicit_conversion),
1159 PDiag(diag::note_array_size_conversion),
1160 PDiag(diag::err_array_size_ambiguous_conversion),
1161 PDiag(diag::note_array_size_conversion),
1162 PDiag(getLangOpts().CPlusPlus0x ?
1163 diag::warn_cxx98_compat_array_size_conversion :
1164 diag::ext_array_size_conversion),
1165 /*AllowScopedEnumerations*/ false);
1166 if (ConvertedSize.isInvalid())
1167 return ExprError();
1168
1169 ArraySize = ConvertedSize.take();
1170 QualType SizeType = ArraySize->getType();
1171 if (!SizeType->isIntegralOrUnscopedEnumerationType())
1172 return ExprError();
1173
1174 // C++98 [expr.new]p7:
1175 // The expression in a direct-new-declarator shall have integral type
1176 // with a non-negative value.
1177 //
1178 // Let's see if this is a constant < 0. If so, we reject it out of
1179 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1180 // array type.
1181 //
1182 // Note: such a construct has well-defined semantics in C++11: it throws
1183 // std::bad_array_new_length.
1184 if (!ArraySize->isValueDependent()) {
1185 llvm::APSInt Value;
1186 // We've already performed any required implicit conversion to integer or
1187 // unscoped enumeration type.
1188 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1189 if (Value < llvm::APSInt(
1190 llvm::APInt::getNullValue(Value.getBitWidth()),
1191 Value.isUnsigned())) {
1192 if (getLangOpts().CPlusPlus0x)
1193 Diag(ArraySize->getLocStart(),
1194 diag::warn_typecheck_negative_array_new_size)
1195 << ArraySize->getSourceRange();
1196 else
1197 return ExprError(Diag(ArraySize->getLocStart(),
1198 diag::err_typecheck_negative_array_size)
1199 << ArraySize->getSourceRange());
1200 } else if (!AllocType->isDependentType()) {
1201 unsigned ActiveSizeBits =
1202 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1203 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1204 if (getLangOpts().CPlusPlus0x)
1205 Diag(ArraySize->getLocStart(),
1206 diag::warn_array_new_too_large)
1207 << Value.toString(10)
1208 << ArraySize->getSourceRange();
1209 else
1210 return ExprError(Diag(ArraySize->getLocStart(),
1211 diag::err_array_too_large)
1212 << Value.toString(10)
1213 << ArraySize->getSourceRange());
1214 }
1215 }
1216 } else if (TypeIdParens.isValid()) {
1217 // Can't have dynamic array size when the type-id is in parentheses.
1218 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1219 << ArraySize->getSourceRange()
1220 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1221 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1222
1223 TypeIdParens = SourceRange();
1224 }
1225 }
1226
1227 // ARC: warn about ABI issues.
1228 if (getLangOpts().ObjCAutoRefCount) {
1229 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1230 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1231 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1232 << 0 << BaseAllocType;
1233 }
1234
1235 // Note that we do *not* convert the argument in any way. It can
1236 // be signed, larger than size_t, whatever.
1237 }
1238
1239 FunctionDecl *OperatorNew = 0;
1240 FunctionDecl *OperatorDelete = 0;
1241 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1242 unsigned NumPlaceArgs = PlacementArgs.size();
1243
1244 if (!AllocType->isDependentType() &&
1245 !Expr::hasAnyTypeDependentArguments(
1246 llvm::makeArrayRef(PlaceArgs, NumPlaceArgs)) &&
1247 FindAllocationFunctions(StartLoc,
1248 SourceRange(PlacementLParen, PlacementRParen),
1249 UseGlobal, AllocType, ArraySize, PlaceArgs,
1250 NumPlaceArgs, OperatorNew, OperatorDelete))
1251 return ExprError();
1252
1253 // If this is an array allocation, compute whether the usual array
1254 // deallocation function for the type has a size_t parameter.
1255 bool UsualArrayDeleteWantsSize = false;
1256 if (ArraySize && !AllocType->isDependentType())
1257 UsualArrayDeleteWantsSize
1258 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1259
1260 SmallVector<Expr *, 8> AllPlaceArgs;
1261 if (OperatorNew) {
1262 // Add default arguments, if any.
1263 const FunctionProtoType *Proto =
1264 OperatorNew->getType()->getAs<FunctionProtoType>();
1265 VariadicCallType CallType =
1266 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
1267
1268 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
1269 Proto, 1, PlaceArgs, NumPlaceArgs,
1270 AllPlaceArgs, CallType))
1271 return ExprError();
1272
1273 NumPlaceArgs = AllPlaceArgs.size();
1274 if (NumPlaceArgs > 0)
1275 PlaceArgs = &AllPlaceArgs[0];
1276
1277 DiagnoseSentinelCalls(OperatorNew, PlacementLParen,
1278 PlaceArgs, NumPlaceArgs);
1279
1280 // FIXME: Missing call to CheckFunctionCall or equivalent
1281 }
1282
1283 // Warn if the type is over-aligned and is being allocated by global operator
1284 // new.
1285 if (NumPlaceArgs == 0 && OperatorNew &&
1286 (OperatorNew->isImplicit() ||
1287 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1288 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1289 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1290 if (Align > SuitableAlign)
1291 Diag(StartLoc, diag::warn_overaligned_type)
1292 << AllocType
1293 << unsigned(Align / Context.getCharWidth())
1294 << unsigned(SuitableAlign / Context.getCharWidth());
1295 }
1296 }
1297
1298 QualType InitType = AllocType;
1299 // Array 'new' can't have any initializers except empty parentheses.
1300 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1301 // dialect distinction.
1302 if (ResultType->isArrayType() || ArraySize) {
1303 if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1304 SourceRange InitRange(Inits[0]->getLocStart(),
1305 Inits[NumInits - 1]->getLocEnd());
1306 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1307 return ExprError();
1308 }
1309 if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1310 // We do the initialization typechecking against the array type
1311 // corresponding to the number of initializers + 1 (to also check
1312 // default-initialization).
1313 unsigned NumElements = ILE->getNumInits() + 1;
1314 InitType = Context.getConstantArrayType(AllocType,
1315 llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1316 ArrayType::Normal, 0);
1317 }
1318 }
1319
1320 if (!AllocType->isDependentType() &&
1321 !Expr::hasAnyTypeDependentArguments(
1322 llvm::makeArrayRef(Inits, NumInits))) {
1323 // C++11 [expr.new]p15:
1324 // A new-expression that creates an object of type T initializes that
1325 // object as follows:
1326 InitializationKind Kind
1327 // - If the new-initializer is omitted, the object is default-
1328 // initialized (8.5); if no initialization is performed,
1329 // the object has indeterminate value
1330 = initStyle == CXXNewExpr::NoInit
1331 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1332 // - Otherwise, the new-initializer is interpreted according to the
1333 // initialization rules of 8.5 for direct-initialization.
1334 : initStyle == CXXNewExpr::ListInit
1335 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1336 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1337 DirectInitRange.getBegin(),
1338 DirectInitRange.getEnd());
1339
1340 InitializedEntity Entity
1341 = InitializedEntity::InitializeNew(StartLoc, InitType);
1342 InitializationSequence InitSeq(*this, Entity, Kind, Inits, NumInits);
1343 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1344 MultiExprArg(Inits, NumInits));
1345 if (FullInit.isInvalid())
1346 return ExprError();
1347
1348 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1349 // we don't want the initialized object to be destructed.
1350 if (CXXBindTemporaryExpr *Binder =
1351 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1352 FullInit = Owned(Binder->getSubExpr());
1353
1354 Initializer = FullInit.take();
1355 }
1356
1357 // Mark the new and delete operators as referenced.
1358 if (OperatorNew)
1359 MarkFunctionReferenced(StartLoc, OperatorNew);
1360 if (OperatorDelete)
1361 MarkFunctionReferenced(StartLoc, OperatorDelete);
1362
1363 // C++0x [expr.new]p17:
1364 // If the new expression creates an array of objects of class type,
1365 // access and ambiguity control are done for the destructor.
1366 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1367 if (ArraySize && !BaseAllocType->isDependentType()) {
1368 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1369 if (CXXDestructorDecl *dtor = LookupDestructor(
1370 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1371 MarkFunctionReferenced(StartLoc, dtor);
1372 CheckDestructorAccess(StartLoc, dtor,
1373 PDiag(diag::err_access_dtor)
1374 << BaseAllocType);
1375 DiagnoseUseOfDecl(dtor, StartLoc);
1376 }
1377 }
1378 }
1379
1380 PlacementArgs.release();
1381
1382 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
1383 OperatorDelete,
1384 UsualArrayDeleteWantsSize,
1385 PlaceArgs, NumPlaceArgs, TypeIdParens,
1386 ArraySize, initStyle, Initializer,
1387 ResultType, AllocTypeInfo,
1388 StartLoc, DirectInitRange));
1389 }
1390
1391 /// \brief Checks that a type is suitable as the allocated type
1392 /// in a new-expression.
CheckAllocatedType(QualType AllocType,SourceLocation Loc,SourceRange R)1393 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1394 SourceRange R) {
1395 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1396 // abstract class type or array thereof.
1397 if (AllocType->isFunctionType())
1398 return Diag(Loc, diag::err_bad_new_type)
1399 << AllocType << 0 << R;
1400 else if (AllocType->isReferenceType())
1401 return Diag(Loc, diag::err_bad_new_type)
1402 << AllocType << 1 << R;
1403 else if (!AllocType->isDependentType() &&
1404 RequireCompleteType(Loc, AllocType,
1405 PDiag(diag::err_new_incomplete_type)
1406 << R))
1407 return true;
1408 else if (RequireNonAbstractType(Loc, AllocType,
1409 diag::err_allocation_of_abstract_type))
1410 return true;
1411 else if (AllocType->isVariablyModifiedType())
1412 return Diag(Loc, diag::err_variably_modified_new_type)
1413 << AllocType;
1414 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1415 return Diag(Loc, diag::err_address_space_qualified_new)
1416 << AllocType.getUnqualifiedType() << AddressSpace;
1417 else if (getLangOpts().ObjCAutoRefCount) {
1418 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1419 QualType BaseAllocType = Context.getBaseElementType(AT);
1420 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1421 BaseAllocType->isObjCLifetimeType())
1422 return Diag(Loc, diag::err_arc_new_array_without_ownership)
1423 << BaseAllocType;
1424 }
1425 }
1426
1427 return false;
1428 }
1429
1430 /// \brief Determine whether the given function is a non-placement
1431 /// deallocation function.
isNonPlacementDeallocationFunction(FunctionDecl * FD)1432 static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1433 if (FD->isInvalidDecl())
1434 return false;
1435
1436 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1437 return Method->isUsualDeallocationFunction();
1438
1439 return ((FD->getOverloadedOperator() == OO_Delete ||
1440 FD->getOverloadedOperator() == OO_Array_Delete) &&
1441 FD->getNumParams() == 1);
1442 }
1443
1444 /// FindAllocationFunctions - Finds the overloads of operator new and delete
1445 /// that are appropriate for the allocation.
FindAllocationFunctions(SourceLocation StartLoc,SourceRange Range,bool UseGlobal,QualType AllocType,bool IsArray,Expr ** PlaceArgs,unsigned NumPlaceArgs,FunctionDecl * & OperatorNew,FunctionDecl * & OperatorDelete)1446 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1447 bool UseGlobal, QualType AllocType,
1448 bool IsArray, Expr **PlaceArgs,
1449 unsigned NumPlaceArgs,
1450 FunctionDecl *&OperatorNew,
1451 FunctionDecl *&OperatorDelete) {
1452 // --- Choosing an allocation function ---
1453 // C++ 5.3.4p8 - 14 & 18
1454 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1455 // in the scope of the allocated class.
1456 // 2) If an array size is given, look for operator new[], else look for
1457 // operator new.
1458 // 3) The first argument is always size_t. Append the arguments from the
1459 // placement form.
1460
1461 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1462 // We don't care about the actual value of this argument.
1463 // FIXME: Should the Sema create the expression and embed it in the syntax
1464 // tree? Or should the consumer just recalculate the value?
1465 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1466 Context.getTargetInfo().getPointerWidth(0)),
1467 Context.getSizeType(),
1468 SourceLocation());
1469 AllocArgs[0] = &Size;
1470 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1471
1472 // C++ [expr.new]p8:
1473 // If the allocated type is a non-array type, the allocation
1474 // function's name is operator new and the deallocation function's
1475 // name is operator delete. If the allocated type is an array
1476 // type, the allocation function's name is operator new[] and the
1477 // deallocation function's name is operator delete[].
1478 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1479 IsArray ? OO_Array_New : OO_New);
1480 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1481 IsArray ? OO_Array_Delete : OO_Delete);
1482
1483 QualType AllocElemType = Context.getBaseElementType(AllocType);
1484
1485 if (AllocElemType->isRecordType() && !UseGlobal) {
1486 CXXRecordDecl *Record
1487 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1488 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1489 AllocArgs.size(), Record, /*AllowMissing=*/true,
1490 OperatorNew))
1491 return true;
1492 }
1493 if (!OperatorNew) {
1494 // Didn't find a member overload. Look for a global one.
1495 DeclareGlobalNewDelete();
1496 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1497 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1498 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1499 OperatorNew))
1500 return true;
1501 }
1502
1503 // We don't need an operator delete if we're running under
1504 // -fno-exceptions.
1505 if (!getLangOpts().Exceptions) {
1506 OperatorDelete = 0;
1507 return false;
1508 }
1509
1510 // FindAllocationOverload can change the passed in arguments, so we need to
1511 // copy them back.
1512 if (NumPlaceArgs > 0)
1513 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
1514
1515 // C++ [expr.new]p19:
1516 //
1517 // If the new-expression begins with a unary :: operator, the
1518 // deallocation function's name is looked up in the global
1519 // scope. Otherwise, if the allocated type is a class type T or an
1520 // array thereof, the deallocation function's name is looked up in
1521 // the scope of T. If this lookup fails to find the name, or if
1522 // the allocated type is not a class type or array thereof, the
1523 // deallocation function's name is looked up in the global scope.
1524 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1525 if (AllocElemType->isRecordType() && !UseGlobal) {
1526 CXXRecordDecl *RD
1527 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1528 LookupQualifiedName(FoundDelete, RD);
1529 }
1530 if (FoundDelete.isAmbiguous())
1531 return true; // FIXME: clean up expressions?
1532
1533 if (FoundDelete.empty()) {
1534 DeclareGlobalNewDelete();
1535 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1536 }
1537
1538 FoundDelete.suppressDiagnostics();
1539
1540 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1541
1542 // Whether we're looking for a placement operator delete is dictated
1543 // by whether we selected a placement operator new, not by whether
1544 // we had explicit placement arguments. This matters for things like
1545 // struct A { void *operator new(size_t, int = 0); ... };
1546 // A *a = new A()
1547 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1548
1549 if (isPlacementNew) {
1550 // C++ [expr.new]p20:
1551 // A declaration of a placement deallocation function matches the
1552 // declaration of a placement allocation function if it has the
1553 // same number of parameters and, after parameter transformations
1554 // (8.3.5), all parameter types except the first are
1555 // identical. [...]
1556 //
1557 // To perform this comparison, we compute the function type that
1558 // the deallocation function should have, and use that type both
1559 // for template argument deduction and for comparison purposes.
1560 //
1561 // FIXME: this comparison should ignore CC and the like.
1562 QualType ExpectedFunctionType;
1563 {
1564 const FunctionProtoType *Proto
1565 = OperatorNew->getType()->getAs<FunctionProtoType>();
1566
1567 SmallVector<QualType, 4> ArgTypes;
1568 ArgTypes.push_back(Context.VoidPtrTy);
1569 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1570 ArgTypes.push_back(Proto->getArgType(I));
1571
1572 FunctionProtoType::ExtProtoInfo EPI;
1573 EPI.Variadic = Proto->isVariadic();
1574
1575 ExpectedFunctionType
1576 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1577 ArgTypes.size(), EPI);
1578 }
1579
1580 for (LookupResult::iterator D = FoundDelete.begin(),
1581 DEnd = FoundDelete.end();
1582 D != DEnd; ++D) {
1583 FunctionDecl *Fn = 0;
1584 if (FunctionTemplateDecl *FnTmpl
1585 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1586 // Perform template argument deduction to try to match the
1587 // expected function type.
1588 TemplateDeductionInfo Info(Context, StartLoc);
1589 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1590 continue;
1591 } else
1592 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1593
1594 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1595 Matches.push_back(std::make_pair(D.getPair(), Fn));
1596 }
1597 } else {
1598 // C++ [expr.new]p20:
1599 // [...] Any non-placement deallocation function matches a
1600 // non-placement allocation function. [...]
1601 for (LookupResult::iterator D = FoundDelete.begin(),
1602 DEnd = FoundDelete.end();
1603 D != DEnd; ++D) {
1604 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1605 if (isNonPlacementDeallocationFunction(Fn))
1606 Matches.push_back(std::make_pair(D.getPair(), Fn));
1607 }
1608 }
1609
1610 // C++ [expr.new]p20:
1611 // [...] If the lookup finds a single matching deallocation
1612 // function, that function will be called; otherwise, no
1613 // deallocation function will be called.
1614 if (Matches.size() == 1) {
1615 OperatorDelete = Matches[0].second;
1616
1617 // C++0x [expr.new]p20:
1618 // If the lookup finds the two-parameter form of a usual
1619 // deallocation function (3.7.4.2) and that function, considered
1620 // as a placement deallocation function, would have been
1621 // selected as a match for the allocation function, the program
1622 // is ill-formed.
1623 if (NumPlaceArgs && getLangOpts().CPlusPlus0x &&
1624 isNonPlacementDeallocationFunction(OperatorDelete)) {
1625 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1626 << SourceRange(PlaceArgs[0]->getLocStart(),
1627 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1628 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1629 << DeleteName;
1630 } else {
1631 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1632 Matches[0].first);
1633 }
1634 }
1635
1636 return false;
1637 }
1638
1639 /// FindAllocationOverload - Find an fitting overload for the allocation
1640 /// function in the specified scope.
FindAllocationOverload(SourceLocation StartLoc,SourceRange Range,DeclarationName Name,Expr ** Args,unsigned NumArgs,DeclContext * Ctx,bool AllowMissing,FunctionDecl * & Operator,bool Diagnose)1641 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1642 DeclarationName Name, Expr** Args,
1643 unsigned NumArgs, DeclContext *Ctx,
1644 bool AllowMissing, FunctionDecl *&Operator,
1645 bool Diagnose) {
1646 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1647 LookupQualifiedName(R, Ctx);
1648 if (R.empty()) {
1649 if (AllowMissing || !Diagnose)
1650 return false;
1651 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1652 << Name << Range;
1653 }
1654
1655 if (R.isAmbiguous())
1656 return true;
1657
1658 R.suppressDiagnostics();
1659
1660 OverloadCandidateSet Candidates(StartLoc);
1661 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1662 Alloc != AllocEnd; ++Alloc) {
1663 // Even member operator new/delete are implicitly treated as
1664 // static, so don't use AddMemberCandidate.
1665 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1666
1667 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1668 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1669 /*ExplicitTemplateArgs=*/0,
1670 llvm::makeArrayRef(Args, NumArgs),
1671 Candidates,
1672 /*SuppressUserConversions=*/false);
1673 continue;
1674 }
1675
1676 FunctionDecl *Fn = cast<FunctionDecl>(D);
1677 AddOverloadCandidate(Fn, Alloc.getPair(),
1678 llvm::makeArrayRef(Args, NumArgs), Candidates,
1679 /*SuppressUserConversions=*/false);
1680 }
1681
1682 // Do the resolution.
1683 OverloadCandidateSet::iterator Best;
1684 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1685 case OR_Success: {
1686 // Got one!
1687 FunctionDecl *FnDecl = Best->Function;
1688 MarkFunctionReferenced(StartLoc, FnDecl);
1689 // The first argument is size_t, and the first parameter must be size_t,
1690 // too. This is checked on declaration and can be assumed. (It can't be
1691 // asserted on, though, since invalid decls are left in there.)
1692 // Watch out for variadic allocator function.
1693 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1694 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1695 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1696 FnDecl->getParamDecl(i));
1697
1698 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1699 return true;
1700
1701 ExprResult Result
1702 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
1703 if (Result.isInvalid())
1704 return true;
1705
1706 Args[i] = Result.takeAs<Expr>();
1707 }
1708
1709 Operator = FnDecl;
1710
1711 if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1712 Best->FoundDecl, Diagnose) == AR_inaccessible)
1713 return true;
1714
1715 return false;
1716 }
1717
1718 case OR_No_Viable_Function:
1719 if (Diagnose) {
1720 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1721 << Name << Range;
1722 Candidates.NoteCandidates(*this, OCD_AllCandidates,
1723 llvm::makeArrayRef(Args, NumArgs));
1724 }
1725 return true;
1726
1727 case OR_Ambiguous:
1728 if (Diagnose) {
1729 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1730 << Name << Range;
1731 Candidates.NoteCandidates(*this, OCD_ViableCandidates,
1732 llvm::makeArrayRef(Args, NumArgs));
1733 }
1734 return true;
1735
1736 case OR_Deleted: {
1737 if (Diagnose) {
1738 Diag(StartLoc, diag::err_ovl_deleted_call)
1739 << Best->Function->isDeleted()
1740 << Name
1741 << getDeletedOrUnavailableSuffix(Best->Function)
1742 << Range;
1743 Candidates.NoteCandidates(*this, OCD_AllCandidates,
1744 llvm::makeArrayRef(Args, NumArgs));
1745 }
1746 return true;
1747 }
1748 }
1749 llvm_unreachable("Unreachable, bad result from BestViableFunction");
1750 }
1751
1752
1753 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
1754 /// delete. These are:
1755 /// @code
1756 /// // C++03:
1757 /// void* operator new(std::size_t) throw(std::bad_alloc);
1758 /// void* operator new[](std::size_t) throw(std::bad_alloc);
1759 /// void operator delete(void *) throw();
1760 /// void operator delete[](void *) throw();
1761 /// // C++0x:
1762 /// void* operator new(std::size_t);
1763 /// void* operator new[](std::size_t);
1764 /// void operator delete(void *);
1765 /// void operator delete[](void *);
1766 /// @endcode
1767 /// C++0x operator delete is implicitly noexcept.
1768 /// Note that the placement and nothrow forms of new are *not* implicitly
1769 /// declared. Their use requires including \<new\>.
DeclareGlobalNewDelete()1770 void Sema::DeclareGlobalNewDelete() {
1771 if (GlobalNewDeleteDeclared)
1772 return;
1773
1774 // C++ [basic.std.dynamic]p2:
1775 // [...] The following allocation and deallocation functions (18.4) are
1776 // implicitly declared in global scope in each translation unit of a
1777 // program
1778 //
1779 // C++03:
1780 // void* operator new(std::size_t) throw(std::bad_alloc);
1781 // void* operator new[](std::size_t) throw(std::bad_alloc);
1782 // void operator delete(void*) throw();
1783 // void operator delete[](void*) throw();
1784 // C++0x:
1785 // void* operator new(std::size_t);
1786 // void* operator new[](std::size_t);
1787 // void operator delete(void*);
1788 // void operator delete[](void*);
1789 //
1790 // These implicit declarations introduce only the function names operator
1791 // new, operator new[], operator delete, operator delete[].
1792 //
1793 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1794 // "std" or "bad_alloc" as necessary to form the exception specification.
1795 // However, we do not make these implicit declarations visible to name
1796 // lookup.
1797 // Note that the C++0x versions of operator delete are deallocation functions,
1798 // and thus are implicitly noexcept.
1799 if (!StdBadAlloc && !getLangOpts().CPlusPlus0x) {
1800 // The "std::bad_alloc" class has not yet been declared, so build it
1801 // implicitly.
1802 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1803 getOrCreateStdNamespace(),
1804 SourceLocation(), SourceLocation(),
1805 &PP.getIdentifierTable().get("bad_alloc"),
1806 0);
1807 getStdBadAlloc()->setImplicit(true);
1808 }
1809
1810 GlobalNewDeleteDeclared = true;
1811
1812 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1813 QualType SizeT = Context.getSizeType();
1814 bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
1815
1816 DeclareGlobalAllocationFunction(
1817 Context.DeclarationNames.getCXXOperatorName(OO_New),
1818 VoidPtr, SizeT, AssumeSaneOperatorNew);
1819 DeclareGlobalAllocationFunction(
1820 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1821 VoidPtr, SizeT, AssumeSaneOperatorNew);
1822 DeclareGlobalAllocationFunction(
1823 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1824 Context.VoidTy, VoidPtr);
1825 DeclareGlobalAllocationFunction(
1826 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1827 Context.VoidTy, VoidPtr);
1828 }
1829
1830 /// DeclareGlobalAllocationFunction - Declares a single implicit global
1831 /// allocation function if it doesn't already exist.
DeclareGlobalAllocationFunction(DeclarationName Name,QualType Return,QualType Argument,bool AddMallocAttr)1832 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1833 QualType Return, QualType Argument,
1834 bool AddMallocAttr) {
1835 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1836
1837 // Check if this function is already declared.
1838 {
1839 DeclContext::lookup_iterator Alloc, AllocEnd;
1840 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1841 Alloc != AllocEnd; ++Alloc) {
1842 // Only look at non-template functions, as it is the predefined,
1843 // non-templated allocation function we are trying to declare here.
1844 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1845 QualType InitialParamType =
1846 Context.getCanonicalType(
1847 Func->getParamDecl(0)->getType().getUnqualifiedType());
1848 // FIXME: Do we need to check for default arguments here?
1849 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1850 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
1851 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1852 return;
1853 }
1854 }
1855 }
1856 }
1857
1858 QualType BadAllocType;
1859 bool HasBadAllocExceptionSpec
1860 = (Name.getCXXOverloadedOperator() == OO_New ||
1861 Name.getCXXOverloadedOperator() == OO_Array_New);
1862 if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus0x) {
1863 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1864 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
1865 }
1866
1867 FunctionProtoType::ExtProtoInfo EPI;
1868 if (HasBadAllocExceptionSpec) {
1869 if (!getLangOpts().CPlusPlus0x) {
1870 EPI.ExceptionSpecType = EST_Dynamic;
1871 EPI.NumExceptions = 1;
1872 EPI.Exceptions = &BadAllocType;
1873 }
1874 } else {
1875 EPI.ExceptionSpecType = getLangOpts().CPlusPlus0x ?
1876 EST_BasicNoexcept : EST_DynamicNone;
1877 }
1878
1879 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
1880 FunctionDecl *Alloc =
1881 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1882 SourceLocation(), Name,
1883 FnType, /*TInfo=*/0, SC_None,
1884 SC_None, false, true);
1885 Alloc->setImplicit();
1886
1887 if (AddMallocAttr)
1888 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1889
1890 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1891 SourceLocation(), 0,
1892 Argument, /*TInfo=*/0,
1893 SC_None, SC_None, 0);
1894 Alloc->setParams(Param);
1895
1896 // FIXME: Also add this declaration to the IdentifierResolver, but
1897 // make sure it is at the end of the chain to coincide with the
1898 // global scope.
1899 Context.getTranslationUnitDecl()->addDecl(Alloc);
1900 }
1901
FindDeallocationFunction(SourceLocation StartLoc,CXXRecordDecl * RD,DeclarationName Name,FunctionDecl * & Operator,bool Diagnose)1902 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1903 DeclarationName Name,
1904 FunctionDecl* &Operator, bool Diagnose) {
1905 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1906 // Try to find operator delete/operator delete[] in class scope.
1907 LookupQualifiedName(Found, RD);
1908
1909 if (Found.isAmbiguous())
1910 return true;
1911
1912 Found.suppressDiagnostics();
1913
1914 SmallVector<DeclAccessPair,4> Matches;
1915 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1916 F != FEnd; ++F) {
1917 NamedDecl *ND = (*F)->getUnderlyingDecl();
1918
1919 // Ignore template operator delete members from the check for a usual
1920 // deallocation function.
1921 if (isa<FunctionTemplateDecl>(ND))
1922 continue;
1923
1924 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
1925 Matches.push_back(F.getPair());
1926 }
1927
1928 // There's exactly one suitable operator; pick it.
1929 if (Matches.size() == 1) {
1930 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1931
1932 if (Operator->isDeleted()) {
1933 if (Diagnose) {
1934 Diag(StartLoc, diag::err_deleted_function_use);
1935 NoteDeletedFunction(Operator);
1936 }
1937 return true;
1938 }
1939
1940 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1941 Matches[0], Diagnose) == AR_inaccessible)
1942 return true;
1943
1944 return false;
1945
1946 // We found multiple suitable operators; complain about the ambiguity.
1947 } else if (!Matches.empty()) {
1948 if (Diagnose) {
1949 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1950 << Name << RD;
1951
1952 for (SmallVectorImpl<DeclAccessPair>::iterator
1953 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1954 Diag((*F)->getUnderlyingDecl()->getLocation(),
1955 diag::note_member_declared_here) << Name;
1956 }
1957 return true;
1958 }
1959
1960 // We did find operator delete/operator delete[] declarations, but
1961 // none of them were suitable.
1962 if (!Found.empty()) {
1963 if (Diagnose) {
1964 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1965 << Name << RD;
1966
1967 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1968 F != FEnd; ++F)
1969 Diag((*F)->getUnderlyingDecl()->getLocation(),
1970 diag::note_member_declared_here) << Name;
1971 }
1972 return true;
1973 }
1974
1975 // Look for a global declaration.
1976 DeclareGlobalNewDelete();
1977 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1978
1979 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1980 Expr* DeallocArgs[1];
1981 DeallocArgs[0] = &Null;
1982 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1983 DeallocArgs, 1, TUDecl, !Diagnose,
1984 Operator, Diagnose))
1985 return true;
1986
1987 assert(Operator && "Did not find a deallocation function!");
1988 return false;
1989 }
1990
1991 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1992 /// @code ::delete ptr; @endcode
1993 /// or
1994 /// @code delete [] ptr; @endcode
1995 ExprResult
ActOnCXXDelete(SourceLocation StartLoc,bool UseGlobal,bool ArrayForm,Expr * ExE)1996 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
1997 bool ArrayForm, Expr *ExE) {
1998 // C++ [expr.delete]p1:
1999 // The operand shall have a pointer type, or a class type having a single
2000 // conversion function to a pointer type. The result has type void.
2001 //
2002 // DR599 amends "pointer type" to "pointer to object type" in both cases.
2003
2004 ExprResult Ex = Owned(ExE);
2005 FunctionDecl *OperatorDelete = 0;
2006 bool ArrayFormAsWritten = ArrayForm;
2007 bool UsualArrayDeleteWantsSize = false;
2008
2009 if (!Ex.get()->isTypeDependent()) {
2010 // Perform lvalue-to-rvalue cast, if needed.
2011 Ex = DefaultLvalueConversion(Ex.take());
2012
2013 QualType Type = Ex.get()->getType();
2014
2015 if (const RecordType *Record = Type->getAs<RecordType>()) {
2016 if (RequireCompleteType(StartLoc, Type,
2017 PDiag(diag::err_delete_incomplete_class_type)))
2018 return ExprError();
2019
2020 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
2021
2022 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2023 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
2024 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2025 E = Conversions->end(); I != E; ++I) {
2026 NamedDecl *D = I.getDecl();
2027 if (isa<UsingShadowDecl>(D))
2028 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2029
2030 // Skip over templated conversion functions; they aren't considered.
2031 if (isa<FunctionTemplateDecl>(D))
2032 continue;
2033
2034 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
2035
2036 QualType ConvType = Conv->getConversionType().getNonReferenceType();
2037 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
2038 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
2039 ObjectPtrConversions.push_back(Conv);
2040 }
2041 if (ObjectPtrConversions.size() == 1) {
2042 // We have a single conversion to a pointer-to-object type. Perform
2043 // that conversion.
2044 // TODO: don't redo the conversion calculation.
2045 ExprResult Res =
2046 PerformImplicitConversion(Ex.get(),
2047 ObjectPtrConversions.front()->getConversionType(),
2048 AA_Converting);
2049 if (Res.isUsable()) {
2050 Ex = move(Res);
2051 Type = Ex.get()->getType();
2052 }
2053 }
2054 else if (ObjectPtrConversions.size() > 1) {
2055 Diag(StartLoc, diag::err_ambiguous_delete_operand)
2056 << Type << Ex.get()->getSourceRange();
2057 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
2058 NoteOverloadCandidate(ObjectPtrConversions[i]);
2059 return ExprError();
2060 }
2061 }
2062
2063 if (!Type->isPointerType())
2064 return ExprError(Diag(StartLoc, diag::err_delete_operand)
2065 << Type << Ex.get()->getSourceRange());
2066
2067 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
2068 QualType PointeeElem = Context.getBaseElementType(Pointee);
2069
2070 if (unsigned AddressSpace = Pointee.getAddressSpace())
2071 return Diag(Ex.get()->getLocStart(),
2072 diag::err_address_space_qualified_delete)
2073 << Pointee.getUnqualifiedType() << AddressSpace;
2074
2075 CXXRecordDecl *PointeeRD = 0;
2076 if (Pointee->isVoidType() && !isSFINAEContext()) {
2077 // The C++ standard bans deleting a pointer to a non-object type, which
2078 // effectively bans deletion of "void*". However, most compilers support
2079 // this, so we treat it as a warning unless we're in a SFINAE context.
2080 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
2081 << Type << Ex.get()->getSourceRange();
2082 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
2083 return ExprError(Diag(StartLoc, diag::err_delete_operand)
2084 << Type << Ex.get()->getSourceRange());
2085 } else if (!Pointee->isDependentType()) {
2086 if (!RequireCompleteType(StartLoc, Pointee,
2087 PDiag(diag::warn_delete_incomplete)
2088 << Ex.get()->getSourceRange())) {
2089 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2090 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2091 }
2092 }
2093
2094 // C++ [expr.delete]p2:
2095 // [Note: a pointer to a const type can be the operand of a
2096 // delete-expression; it is not necessary to cast away the constness
2097 // (5.2.11) of the pointer expression before it is used as the operand
2098 // of the delete-expression. ]
2099 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
2100 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
2101 CK_BitCast, Ex.take(), 0, VK_RValue));
2102
2103 if (Pointee->isArrayType() && !ArrayForm) {
2104 Diag(StartLoc, diag::warn_delete_array_type)
2105 << Type << Ex.get()->getSourceRange()
2106 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2107 ArrayForm = true;
2108 }
2109
2110 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2111 ArrayForm ? OO_Array_Delete : OO_Delete);
2112
2113 if (PointeeRD) {
2114 if (!UseGlobal &&
2115 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2116 OperatorDelete))
2117 return ExprError();
2118
2119 // If we're allocating an array of records, check whether the
2120 // usual operator delete[] has a size_t parameter.
2121 if (ArrayForm) {
2122 // If the user specifically asked to use the global allocator,
2123 // we'll need to do the lookup into the class.
2124 if (UseGlobal)
2125 UsualArrayDeleteWantsSize =
2126 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2127
2128 // Otherwise, the usual operator delete[] should be the
2129 // function we just found.
2130 else if (isa<CXXMethodDecl>(OperatorDelete))
2131 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2132 }
2133
2134 if (!PointeeRD->hasIrrelevantDestructor())
2135 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2136 MarkFunctionReferenced(StartLoc,
2137 const_cast<CXXDestructorDecl*>(Dtor));
2138 DiagnoseUseOfDecl(Dtor, StartLoc);
2139 }
2140
2141 // C++ [expr.delete]p3:
2142 // In the first alternative (delete object), if the static type of the
2143 // object to be deleted is different from its dynamic type, the static
2144 // type shall be a base class of the dynamic type of the object to be
2145 // deleted and the static type shall have a virtual destructor or the
2146 // behavior is undefined.
2147 //
2148 // Note: a final class cannot be derived from, no issue there
2149 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
2150 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
2151 if (dtor && !dtor->isVirtual()) {
2152 if (PointeeRD->isAbstract()) {
2153 // If the class is abstract, we warn by default, because we're
2154 // sure the code has undefined behavior.
2155 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2156 << PointeeElem;
2157 } else if (!ArrayForm) {
2158 // Otherwise, if this is not an array delete, it's a bit suspect,
2159 // but not necessarily wrong.
2160 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2161 }
2162 }
2163 }
2164
2165 } else if (getLangOpts().ObjCAutoRefCount &&
2166 PointeeElem->isObjCLifetimeType() &&
2167 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
2168 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
2169 ArrayForm) {
2170 Diag(StartLoc, diag::warn_err_new_delete_object_array)
2171 << 1 << PointeeElem;
2172 }
2173
2174 if (!OperatorDelete) {
2175 // Look for a global declaration.
2176 DeclareGlobalNewDelete();
2177 DeclContext *TUDecl = Context.getTranslationUnitDecl();
2178 Expr *Arg = Ex.get();
2179 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
2180 &Arg, 1, TUDecl, /*AllowMissing=*/false,
2181 OperatorDelete))
2182 return ExprError();
2183 }
2184
2185 MarkFunctionReferenced(StartLoc, OperatorDelete);
2186
2187 // Check access and ambiguity of operator delete and destructor.
2188 if (PointeeRD) {
2189 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2190 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
2191 PDiag(diag::err_access_dtor) << PointeeElem);
2192 }
2193 }
2194
2195 }
2196
2197 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
2198 ArrayFormAsWritten,
2199 UsualArrayDeleteWantsSize,
2200 OperatorDelete, Ex.take(), StartLoc));
2201 }
2202
2203 /// \brief Check the use of the given variable as a C++ condition in an if,
2204 /// while, do-while, or switch statement.
CheckConditionVariable(VarDecl * ConditionVar,SourceLocation StmtLoc,bool ConvertToBoolean)2205 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
2206 SourceLocation StmtLoc,
2207 bool ConvertToBoolean) {
2208 QualType T = ConditionVar->getType();
2209
2210 // C++ [stmt.select]p2:
2211 // The declarator shall not specify a function or an array.
2212 if (T->isFunctionType())
2213 return ExprError(Diag(ConditionVar->getLocation(),
2214 diag::err_invalid_use_of_function_type)
2215 << ConditionVar->getSourceRange());
2216 else if (T->isArrayType())
2217 return ExprError(Diag(ConditionVar->getLocation(),
2218 diag::err_invalid_use_of_array_type)
2219 << ConditionVar->getSourceRange());
2220
2221 ExprResult Condition =
2222 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2223 SourceLocation(),
2224 ConditionVar,
2225 /*enclosing*/ false,
2226 ConditionVar->getLocation(),
2227 ConditionVar->getType().getNonReferenceType(),
2228 VK_LValue));
2229
2230 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
2231
2232 if (ConvertToBoolean) {
2233 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2234 if (Condition.isInvalid())
2235 return ExprError();
2236 }
2237
2238 return move(Condition);
2239 }
2240
2241 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
CheckCXXBooleanCondition(Expr * CondExpr)2242 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
2243 // C++ 6.4p4:
2244 // The value of a condition that is an initialized declaration in a statement
2245 // other than a switch statement is the value of the declared variable
2246 // implicitly converted to type bool. If that conversion is ill-formed, the
2247 // program is ill-formed.
2248 // The value of a condition that is an expression is the value of the
2249 // expression, implicitly converted to bool.
2250 //
2251 return PerformContextuallyConvertToBool(CondExpr);
2252 }
2253
2254 /// Helper function to determine whether this is the (deprecated) C++
2255 /// conversion from a string literal to a pointer to non-const char or
2256 /// non-const wchar_t (for narrow and wide string literals,
2257 /// respectively).
2258 bool
IsStringLiteralToNonConstPointerConversion(Expr * From,QualType ToType)2259 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2260 // Look inside the implicit cast, if it exists.
2261 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2262 From = Cast->getSubExpr();
2263
2264 // A string literal (2.13.4) that is not a wide string literal can
2265 // be converted to an rvalue of type "pointer to char"; a wide
2266 // string literal can be converted to an rvalue of type "pointer
2267 // to wchar_t" (C++ 4.2p2).
2268 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
2269 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
2270 if (const BuiltinType *ToPointeeType
2271 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
2272 // This conversion is considered only when there is an
2273 // explicit appropriate pointer target type (C++ 4.2p2).
2274 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2275 switch (StrLit->getKind()) {
2276 case StringLiteral::UTF8:
2277 case StringLiteral::UTF16:
2278 case StringLiteral::UTF32:
2279 // We don't allow UTF literals to be implicitly converted
2280 break;
2281 case StringLiteral::Ascii:
2282 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2283 ToPointeeType->getKind() == BuiltinType::Char_S);
2284 case StringLiteral::Wide:
2285 return ToPointeeType->isWideCharType();
2286 }
2287 }
2288 }
2289
2290 return false;
2291 }
2292
BuildCXXCastArgument(Sema & S,SourceLocation CastLoc,QualType Ty,CastKind Kind,CXXMethodDecl * Method,DeclAccessPair FoundDecl,bool HadMultipleCandidates,Expr * From)2293 static ExprResult BuildCXXCastArgument(Sema &S,
2294 SourceLocation CastLoc,
2295 QualType Ty,
2296 CastKind Kind,
2297 CXXMethodDecl *Method,
2298 DeclAccessPair FoundDecl,
2299 bool HadMultipleCandidates,
2300 Expr *From) {
2301 switch (Kind) {
2302 default: llvm_unreachable("Unhandled cast kind!");
2303 case CK_ConstructorConversion: {
2304 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
2305 ASTOwningVector<Expr*> ConstructorArgs(S);
2306
2307 if (S.CompleteConstructorCall(Constructor,
2308 MultiExprArg(&From, 1),
2309 CastLoc, ConstructorArgs))
2310 return ExprError();
2311
2312 S.CheckConstructorAccess(CastLoc, Constructor,
2313 InitializedEntity::InitializeTemporary(Ty),
2314 Constructor->getAccess());
2315
2316 ExprResult Result
2317 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2318 move_arg(ConstructorArgs),
2319 HadMultipleCandidates, /*ZeroInit*/ false,
2320 CXXConstructExpr::CK_Complete, SourceRange());
2321 if (Result.isInvalid())
2322 return ExprError();
2323
2324 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2325 }
2326
2327 case CK_UserDefinedConversion: {
2328 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2329
2330 // Create an implicit call expr that calls it.
2331 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
2332 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
2333 HadMultipleCandidates);
2334 if (Result.isInvalid())
2335 return ExprError();
2336 // Record usage of conversion in an implicit cast.
2337 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2338 Result.get()->getType(),
2339 CK_UserDefinedConversion,
2340 Result.get(), 0,
2341 Result.get()->getValueKind()));
2342
2343 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2344
2345 return S.MaybeBindToTemporary(Result.get());
2346 }
2347 }
2348 }
2349
2350 /// PerformImplicitConversion - Perform an implicit conversion of the
2351 /// expression From to the type ToType using the pre-computed implicit
2352 /// conversion sequence ICS. Returns the converted
2353 /// expression. Action is the kind of conversion we're performing,
2354 /// used in the error message.
2355 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,const ImplicitConversionSequence & ICS,AssignmentAction Action,CheckedConversionKind CCK)2356 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2357 const ImplicitConversionSequence &ICS,
2358 AssignmentAction Action,
2359 CheckedConversionKind CCK) {
2360 switch (ICS.getKind()) {
2361 case ImplicitConversionSequence::StandardConversion: {
2362 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2363 Action, CCK);
2364 if (Res.isInvalid())
2365 return ExprError();
2366 From = Res.take();
2367 break;
2368 }
2369
2370 case ImplicitConversionSequence::UserDefinedConversion: {
2371
2372 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
2373 CastKind CastKind;
2374 QualType BeforeToType;
2375 assert(FD && "FIXME: aggregate initialization from init list");
2376 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
2377 CastKind = CK_UserDefinedConversion;
2378
2379 // If the user-defined conversion is specified by a conversion function,
2380 // the initial standard conversion sequence converts the source type to
2381 // the implicit object parameter of the conversion function.
2382 BeforeToType = Context.getTagDeclType(Conv->getParent());
2383 } else {
2384 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
2385 CastKind = CK_ConstructorConversion;
2386 // Do no conversion if dealing with ... for the first conversion.
2387 if (!ICS.UserDefined.EllipsisConversion) {
2388 // If the user-defined conversion is specified by a constructor, the
2389 // initial standard conversion sequence converts the source type to the
2390 // type required by the argument of the constructor
2391 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2392 }
2393 }
2394 // Watch out for elipsis conversion.
2395 if (!ICS.UserDefined.EllipsisConversion) {
2396 ExprResult Res =
2397 PerformImplicitConversion(From, BeforeToType,
2398 ICS.UserDefined.Before, AA_Converting,
2399 CCK);
2400 if (Res.isInvalid())
2401 return ExprError();
2402 From = Res.take();
2403 }
2404
2405 ExprResult CastArg
2406 = BuildCXXCastArgument(*this,
2407 From->getLocStart(),
2408 ToType.getNonReferenceType(),
2409 CastKind, cast<CXXMethodDecl>(FD),
2410 ICS.UserDefined.FoundConversionFunction,
2411 ICS.UserDefined.HadMultipleCandidates,
2412 From);
2413
2414 if (CastArg.isInvalid())
2415 return ExprError();
2416
2417 From = CastArg.take();
2418
2419 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2420 AA_Converting, CCK);
2421 }
2422
2423 case ImplicitConversionSequence::AmbiguousConversion:
2424 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
2425 PDiag(diag::err_typecheck_ambiguous_condition)
2426 << From->getSourceRange());
2427 return ExprError();
2428
2429 case ImplicitConversionSequence::EllipsisConversion:
2430 llvm_unreachable("Cannot perform an ellipsis conversion");
2431
2432 case ImplicitConversionSequence::BadConversion:
2433 return ExprError();
2434 }
2435
2436 // Everything went well.
2437 return Owned(From);
2438 }
2439
2440 /// PerformImplicitConversion - Perform an implicit conversion of the
2441 /// expression From to the type ToType by following the standard
2442 /// conversion sequence SCS. Returns the converted
2443 /// expression. Flavor is the context in which we're performing this
2444 /// conversion, for use in error messages.
2445 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,const StandardConversionSequence & SCS,AssignmentAction Action,CheckedConversionKind CCK)2446 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2447 const StandardConversionSequence& SCS,
2448 AssignmentAction Action,
2449 CheckedConversionKind CCK) {
2450 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2451
2452 // Overall FIXME: we are recomputing too many types here and doing far too
2453 // much extra work. What this means is that we need to keep track of more
2454 // information that is computed when we try the implicit conversion initially,
2455 // so that we don't need to recompute anything here.
2456 QualType FromType = From->getType();
2457
2458 if (SCS.CopyConstructor) {
2459 // FIXME: When can ToType be a reference type?
2460 assert(!ToType->isReferenceType());
2461 if (SCS.Second == ICK_Derived_To_Base) {
2462 ASTOwningVector<Expr*> ConstructorArgs(*this);
2463 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
2464 MultiExprArg(*this, &From, 1),
2465 /*FIXME:ConstructLoc*/SourceLocation(),
2466 ConstructorArgs))
2467 return ExprError();
2468 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2469 ToType, SCS.CopyConstructor,
2470 move_arg(ConstructorArgs),
2471 /*HadMultipleCandidates*/ false,
2472 /*ZeroInit*/ false,
2473 CXXConstructExpr::CK_Complete,
2474 SourceRange());
2475 }
2476 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2477 ToType, SCS.CopyConstructor,
2478 MultiExprArg(*this, &From, 1),
2479 /*HadMultipleCandidates*/ false,
2480 /*ZeroInit*/ false,
2481 CXXConstructExpr::CK_Complete,
2482 SourceRange());
2483 }
2484
2485 // Resolve overloaded function references.
2486 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2487 DeclAccessPair Found;
2488 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2489 true, Found);
2490 if (!Fn)
2491 return ExprError();
2492
2493 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
2494 return ExprError();
2495
2496 From = FixOverloadedFunctionReference(From, Found, Fn);
2497 FromType = From->getType();
2498 }
2499
2500 // Perform the first implicit conversion.
2501 switch (SCS.First) {
2502 case ICK_Identity:
2503 // Nothing to do.
2504 break;
2505
2506 case ICK_Lvalue_To_Rvalue: {
2507 assert(From->getObjectKind() != OK_ObjCProperty);
2508 FromType = FromType.getUnqualifiedType();
2509 ExprResult FromRes = DefaultLvalueConversion(From);
2510 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2511 From = FromRes.take();
2512 break;
2513 }
2514
2515 case ICK_Array_To_Pointer:
2516 FromType = Context.getArrayDecayedType(FromType);
2517 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2518 VK_RValue, /*BasePath=*/0, CCK).take();
2519 break;
2520
2521 case ICK_Function_To_Pointer:
2522 FromType = Context.getPointerType(FromType);
2523 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2524 VK_RValue, /*BasePath=*/0, CCK).take();
2525 break;
2526
2527 default:
2528 llvm_unreachable("Improper first standard conversion");
2529 }
2530
2531 // Perform the second implicit conversion
2532 switch (SCS.Second) {
2533 case ICK_Identity:
2534 // If both sides are functions (or pointers/references to them), there could
2535 // be incompatible exception declarations.
2536 if (CheckExceptionSpecCompatibility(From, ToType))
2537 return ExprError();
2538 // Nothing else to do.
2539 break;
2540
2541 case ICK_NoReturn_Adjustment:
2542 // If both sides are functions (or pointers/references to them), there could
2543 // be incompatible exception declarations.
2544 if (CheckExceptionSpecCompatibility(From, ToType))
2545 return ExprError();
2546
2547 From = ImpCastExprToType(From, ToType, CK_NoOp,
2548 VK_RValue, /*BasePath=*/0, CCK).take();
2549 break;
2550
2551 case ICK_Integral_Promotion:
2552 case ICK_Integral_Conversion:
2553 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2554 VK_RValue, /*BasePath=*/0, CCK).take();
2555 break;
2556
2557 case ICK_Floating_Promotion:
2558 case ICK_Floating_Conversion:
2559 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2560 VK_RValue, /*BasePath=*/0, CCK).take();
2561 break;
2562
2563 case ICK_Complex_Promotion:
2564 case ICK_Complex_Conversion: {
2565 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2566 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2567 CastKind CK;
2568 if (FromEl->isRealFloatingType()) {
2569 if (ToEl->isRealFloatingType())
2570 CK = CK_FloatingComplexCast;
2571 else
2572 CK = CK_FloatingComplexToIntegralComplex;
2573 } else if (ToEl->isRealFloatingType()) {
2574 CK = CK_IntegralComplexToFloatingComplex;
2575 } else {
2576 CK = CK_IntegralComplexCast;
2577 }
2578 From = ImpCastExprToType(From, ToType, CK,
2579 VK_RValue, /*BasePath=*/0, CCK).take();
2580 break;
2581 }
2582
2583 case ICK_Floating_Integral:
2584 if (ToType->isRealFloatingType())
2585 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2586 VK_RValue, /*BasePath=*/0, CCK).take();
2587 else
2588 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2589 VK_RValue, /*BasePath=*/0, CCK).take();
2590 break;
2591
2592 case ICK_Compatible_Conversion:
2593 From = ImpCastExprToType(From, ToType, CK_NoOp,
2594 VK_RValue, /*BasePath=*/0, CCK).take();
2595 break;
2596
2597 case ICK_Writeback_Conversion:
2598 case ICK_Pointer_Conversion: {
2599 if (SCS.IncompatibleObjC && Action != AA_Casting) {
2600 // Diagnose incompatible Objective-C conversions
2601 if (Action == AA_Initializing || Action == AA_Assigning)
2602 Diag(From->getLocStart(),
2603 diag::ext_typecheck_convert_incompatible_pointer)
2604 << ToType << From->getType() << Action
2605 << From->getSourceRange() << 0;
2606 else
2607 Diag(From->getLocStart(),
2608 diag::ext_typecheck_convert_incompatible_pointer)
2609 << From->getType() << ToType << Action
2610 << From->getSourceRange() << 0;
2611
2612 if (From->getType()->isObjCObjectPointerType() &&
2613 ToType->isObjCObjectPointerType())
2614 EmitRelatedResultTypeNote(From);
2615 }
2616 else if (getLangOpts().ObjCAutoRefCount &&
2617 !CheckObjCARCUnavailableWeakConversion(ToType,
2618 From->getType())) {
2619 if (Action == AA_Initializing)
2620 Diag(From->getLocStart(),
2621 diag::err_arc_weak_unavailable_assign);
2622 else
2623 Diag(From->getLocStart(),
2624 diag::err_arc_convesion_of_weak_unavailable)
2625 << (Action == AA_Casting) << From->getType() << ToType
2626 << From->getSourceRange();
2627 }
2628
2629 CastKind Kind = CK_Invalid;
2630 CXXCastPath BasePath;
2631 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
2632 return ExprError();
2633
2634 // Make sure we extend blocks if necessary.
2635 // FIXME: doing this here is really ugly.
2636 if (Kind == CK_BlockPointerToObjCPointerCast) {
2637 ExprResult E = From;
2638 (void) PrepareCastToObjCObjectPointer(E);
2639 From = E.take();
2640 }
2641
2642 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2643 .take();
2644 break;
2645 }
2646
2647 case ICK_Pointer_Member: {
2648 CastKind Kind = CK_Invalid;
2649 CXXCastPath BasePath;
2650 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
2651 return ExprError();
2652 if (CheckExceptionSpecCompatibility(From, ToType))
2653 return ExprError();
2654 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2655 .take();
2656 break;
2657 }
2658
2659 case ICK_Boolean_Conversion:
2660 // Perform half-to-boolean conversion via float.
2661 if (From->getType()->isHalfType()) {
2662 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2663 FromType = Context.FloatTy;
2664 }
2665
2666 From = ImpCastExprToType(From, Context.BoolTy,
2667 ScalarTypeToBooleanCastKind(FromType),
2668 VK_RValue, /*BasePath=*/0, CCK).take();
2669 break;
2670
2671 case ICK_Derived_To_Base: {
2672 CXXCastPath BasePath;
2673 if (CheckDerivedToBaseConversion(From->getType(),
2674 ToType.getNonReferenceType(),
2675 From->getLocStart(),
2676 From->getSourceRange(),
2677 &BasePath,
2678 CStyle))
2679 return ExprError();
2680
2681 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2682 CK_DerivedToBase, From->getValueKind(),
2683 &BasePath, CCK).take();
2684 break;
2685 }
2686
2687 case ICK_Vector_Conversion:
2688 From = ImpCastExprToType(From, ToType, CK_BitCast,
2689 VK_RValue, /*BasePath=*/0, CCK).take();
2690 break;
2691
2692 case ICK_Vector_Splat:
2693 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2694 VK_RValue, /*BasePath=*/0, CCK).take();
2695 break;
2696
2697 case ICK_Complex_Real:
2698 // Case 1. x -> _Complex y
2699 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2700 QualType ElType = ToComplex->getElementType();
2701 bool isFloatingComplex = ElType->isRealFloatingType();
2702
2703 // x -> y
2704 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2705 // do nothing
2706 } else if (From->getType()->isRealFloatingType()) {
2707 From = ImpCastExprToType(From, ElType,
2708 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
2709 } else {
2710 assert(From->getType()->isIntegerType());
2711 From = ImpCastExprToType(From, ElType,
2712 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
2713 }
2714 // y -> _Complex y
2715 From = ImpCastExprToType(From, ToType,
2716 isFloatingComplex ? CK_FloatingRealToComplex
2717 : CK_IntegralRealToComplex).take();
2718
2719 // Case 2. _Complex x -> y
2720 } else {
2721 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2722 assert(FromComplex);
2723
2724 QualType ElType = FromComplex->getElementType();
2725 bool isFloatingComplex = ElType->isRealFloatingType();
2726
2727 // _Complex x -> x
2728 From = ImpCastExprToType(From, ElType,
2729 isFloatingComplex ? CK_FloatingComplexToReal
2730 : CK_IntegralComplexToReal,
2731 VK_RValue, /*BasePath=*/0, CCK).take();
2732
2733 // x -> y
2734 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2735 // do nothing
2736 } else if (ToType->isRealFloatingType()) {
2737 From = ImpCastExprToType(From, ToType,
2738 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2739 VK_RValue, /*BasePath=*/0, CCK).take();
2740 } else {
2741 assert(ToType->isIntegerType());
2742 From = ImpCastExprToType(From, ToType,
2743 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2744 VK_RValue, /*BasePath=*/0, CCK).take();
2745 }
2746 }
2747 break;
2748
2749 case ICK_Block_Pointer_Conversion: {
2750 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2751 VK_RValue, /*BasePath=*/0, CCK).take();
2752 break;
2753 }
2754
2755 case ICK_TransparentUnionConversion: {
2756 ExprResult FromRes = Owned(From);
2757 Sema::AssignConvertType ConvTy =
2758 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2759 if (FromRes.isInvalid())
2760 return ExprError();
2761 From = FromRes.take();
2762 assert ((ConvTy == Sema::Compatible) &&
2763 "Improper transparent union conversion");
2764 (void)ConvTy;
2765 break;
2766 }
2767
2768 case ICK_Lvalue_To_Rvalue:
2769 case ICK_Array_To_Pointer:
2770 case ICK_Function_To_Pointer:
2771 case ICK_Qualification:
2772 case ICK_Num_Conversion_Kinds:
2773 llvm_unreachable("Improper second standard conversion");
2774 }
2775
2776 switch (SCS.Third) {
2777 case ICK_Identity:
2778 // Nothing to do.
2779 break;
2780
2781 case ICK_Qualification: {
2782 // The qualification keeps the category of the inner expression, unless the
2783 // target type isn't a reference.
2784 ExprValueKind VK = ToType->isReferenceType() ?
2785 From->getValueKind() : VK_RValue;
2786 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2787 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
2788
2789 if (SCS.DeprecatedStringLiteralToCharPtr &&
2790 !getLangOpts().WritableStrings)
2791 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2792 << ToType.getNonReferenceType();
2793
2794 break;
2795 }
2796
2797 default:
2798 llvm_unreachable("Improper third standard conversion");
2799 }
2800
2801 // If this conversion sequence involved a scalar -> atomic conversion, perform
2802 // that conversion now.
2803 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>())
2804 if (Context.hasSameType(ToAtomic->getValueType(), From->getType()))
2805 From = ImpCastExprToType(From, ToType, CK_NonAtomicToAtomic, VK_RValue, 0,
2806 CCK).take();
2807
2808 return Owned(From);
2809 }
2810
ActOnUnaryTypeTrait(UnaryTypeTrait UTT,SourceLocation KWLoc,ParsedType Ty,SourceLocation RParen)2811 ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
2812 SourceLocation KWLoc,
2813 ParsedType Ty,
2814 SourceLocation RParen) {
2815 TypeSourceInfo *TSInfo;
2816 QualType T = GetTypeFromParser(Ty, &TSInfo);
2817
2818 if (!TSInfo)
2819 TSInfo = Context.getTrivialTypeSourceInfo(T);
2820 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
2821 }
2822
2823 /// \brief Check the completeness of a type in a unary type trait.
2824 ///
2825 /// If the particular type trait requires a complete type, tries to complete
2826 /// it. If completing the type fails, a diagnostic is emitted and false
2827 /// returned. If completing the type succeeds or no completion was required,
2828 /// returns true.
CheckUnaryTypeTraitTypeCompleteness(Sema & S,UnaryTypeTrait UTT,SourceLocation Loc,QualType ArgTy)2829 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2830 UnaryTypeTrait UTT,
2831 SourceLocation Loc,
2832 QualType ArgTy) {
2833 // C++0x [meta.unary.prop]p3:
2834 // For all of the class templates X declared in this Clause, instantiating
2835 // that template with a template argument that is a class template
2836 // specialization may result in the implicit instantiation of the template
2837 // argument if and only if the semantics of X require that the argument
2838 // must be a complete type.
2839 // We apply this rule to all the type trait expressions used to implement
2840 // these class templates. We also try to follow any GCC documented behavior
2841 // in these expressions to ensure portability of standard libraries.
2842 switch (UTT) {
2843 // is_complete_type somewhat obviously cannot require a complete type.
2844 case UTT_IsCompleteType:
2845 // Fall-through
2846
2847 // These traits are modeled on the type predicates in C++0x
2848 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2849 // requiring a complete type, as whether or not they return true cannot be
2850 // impacted by the completeness of the type.
2851 case UTT_IsVoid:
2852 case UTT_IsIntegral:
2853 case UTT_IsFloatingPoint:
2854 case UTT_IsArray:
2855 case UTT_IsPointer:
2856 case UTT_IsLvalueReference:
2857 case UTT_IsRvalueReference:
2858 case UTT_IsMemberFunctionPointer:
2859 case UTT_IsMemberObjectPointer:
2860 case UTT_IsEnum:
2861 case UTT_IsUnion:
2862 case UTT_IsClass:
2863 case UTT_IsFunction:
2864 case UTT_IsReference:
2865 case UTT_IsArithmetic:
2866 case UTT_IsFundamental:
2867 case UTT_IsObject:
2868 case UTT_IsScalar:
2869 case UTT_IsCompound:
2870 case UTT_IsMemberPointer:
2871 // Fall-through
2872
2873 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2874 // which requires some of its traits to have the complete type. However,
2875 // the completeness of the type cannot impact these traits' semantics, and
2876 // so they don't require it. This matches the comments on these traits in
2877 // Table 49.
2878 case UTT_IsConst:
2879 case UTT_IsVolatile:
2880 case UTT_IsSigned:
2881 case UTT_IsUnsigned:
2882 return true;
2883
2884 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
2885 // applied to a complete type.
2886 case UTT_IsTrivial:
2887 case UTT_IsTriviallyCopyable:
2888 case UTT_IsStandardLayout:
2889 case UTT_IsPOD:
2890 case UTT_IsLiteral:
2891 case UTT_IsEmpty:
2892 case UTT_IsPolymorphic:
2893 case UTT_IsAbstract:
2894 // Fall-through
2895
2896 // These traits require a complete type.
2897 case UTT_IsFinal:
2898
2899 // These trait expressions are designed to help implement predicates in
2900 // [meta.unary.prop] despite not being named the same. They are specified
2901 // by both GCC and the Embarcadero C++ compiler, and require the complete
2902 // type due to the overarching C++0x type predicates being implemented
2903 // requiring the complete type.
2904 case UTT_HasNothrowAssign:
2905 case UTT_HasNothrowConstructor:
2906 case UTT_HasNothrowCopy:
2907 case UTT_HasTrivialAssign:
2908 case UTT_HasTrivialDefaultConstructor:
2909 case UTT_HasTrivialCopy:
2910 case UTT_HasTrivialDestructor:
2911 case UTT_HasVirtualDestructor:
2912 // Arrays of unknown bound are expressly allowed.
2913 QualType ElTy = ArgTy;
2914 if (ArgTy->isIncompleteArrayType())
2915 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2916
2917 // The void type is expressly allowed.
2918 if (ElTy->isVoidType())
2919 return true;
2920
2921 return !S.RequireCompleteType(
2922 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
2923 }
2924 llvm_unreachable("Type trait not handled by switch");
2925 }
2926
EvaluateUnaryTypeTrait(Sema & Self,UnaryTypeTrait UTT,SourceLocation KeyLoc,QualType T)2927 static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2928 SourceLocation KeyLoc, QualType T) {
2929 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
2930
2931 ASTContext &C = Self.Context;
2932 switch(UTT) {
2933 // Type trait expressions corresponding to the primary type category
2934 // predicates in C++0x [meta.unary.cat].
2935 case UTT_IsVoid:
2936 return T->isVoidType();
2937 case UTT_IsIntegral:
2938 return T->isIntegralType(C);
2939 case UTT_IsFloatingPoint:
2940 return T->isFloatingType();
2941 case UTT_IsArray:
2942 return T->isArrayType();
2943 case UTT_IsPointer:
2944 return T->isPointerType();
2945 case UTT_IsLvalueReference:
2946 return T->isLValueReferenceType();
2947 case UTT_IsRvalueReference:
2948 return T->isRValueReferenceType();
2949 case UTT_IsMemberFunctionPointer:
2950 return T->isMemberFunctionPointerType();
2951 case UTT_IsMemberObjectPointer:
2952 return T->isMemberDataPointerType();
2953 case UTT_IsEnum:
2954 return T->isEnumeralType();
2955 case UTT_IsUnion:
2956 return T->isUnionType();
2957 case UTT_IsClass:
2958 return T->isClassType() || T->isStructureType();
2959 case UTT_IsFunction:
2960 return T->isFunctionType();
2961
2962 // Type trait expressions which correspond to the convenient composition
2963 // predicates in C++0x [meta.unary.comp].
2964 case UTT_IsReference:
2965 return T->isReferenceType();
2966 case UTT_IsArithmetic:
2967 return T->isArithmeticType() && !T->isEnumeralType();
2968 case UTT_IsFundamental:
2969 return T->isFundamentalType();
2970 case UTT_IsObject:
2971 return T->isObjectType();
2972 case UTT_IsScalar:
2973 // Note: semantic analysis depends on Objective-C lifetime types to be
2974 // considered scalar types. However, such types do not actually behave
2975 // like scalar types at run time (since they may require retain/release
2976 // operations), so we report them as non-scalar.
2977 if (T->isObjCLifetimeType()) {
2978 switch (T.getObjCLifetime()) {
2979 case Qualifiers::OCL_None:
2980 case Qualifiers::OCL_ExplicitNone:
2981 return true;
2982
2983 case Qualifiers::OCL_Strong:
2984 case Qualifiers::OCL_Weak:
2985 case Qualifiers::OCL_Autoreleasing:
2986 return false;
2987 }
2988 }
2989
2990 return T->isScalarType();
2991 case UTT_IsCompound:
2992 return T->isCompoundType();
2993 case UTT_IsMemberPointer:
2994 return T->isMemberPointerType();
2995
2996 // Type trait expressions which correspond to the type property predicates
2997 // in C++0x [meta.unary.prop].
2998 case UTT_IsConst:
2999 return T.isConstQualified();
3000 case UTT_IsVolatile:
3001 return T.isVolatileQualified();
3002 case UTT_IsTrivial:
3003 return T.isTrivialType(Self.Context);
3004 case UTT_IsTriviallyCopyable:
3005 return T.isTriviallyCopyableType(Self.Context);
3006 case UTT_IsStandardLayout:
3007 return T->isStandardLayoutType();
3008 case UTT_IsPOD:
3009 return T.isPODType(Self.Context);
3010 case UTT_IsLiteral:
3011 return T->isLiteralType();
3012 case UTT_IsEmpty:
3013 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3014 return !RD->isUnion() && RD->isEmpty();
3015 return false;
3016 case UTT_IsPolymorphic:
3017 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3018 return RD->isPolymorphic();
3019 return false;
3020 case UTT_IsAbstract:
3021 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3022 return RD->isAbstract();
3023 return false;
3024 case UTT_IsFinal:
3025 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3026 return RD->hasAttr<FinalAttr>();
3027 return false;
3028 case UTT_IsSigned:
3029 return T->isSignedIntegerType();
3030 case UTT_IsUnsigned:
3031 return T->isUnsignedIntegerType();
3032
3033 // Type trait expressions which query classes regarding their construction,
3034 // destruction, and copying. Rather than being based directly on the
3035 // related type predicates in the standard, they are specified by both
3036 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3037 // specifications.
3038 //
3039 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3040 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3041 case UTT_HasTrivialDefaultConstructor:
3042 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3043 // If __is_pod (type) is true then the trait is true, else if type is
3044 // a cv class or union type (or array thereof) with a trivial default
3045 // constructor ([class.ctor]) then the trait is true, else it is false.
3046 if (T.isPODType(Self.Context))
3047 return true;
3048 if (const RecordType *RT =
3049 C.getBaseElementType(T)->getAs<RecordType>())
3050 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
3051 return false;
3052 case UTT_HasTrivialCopy:
3053 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3054 // If __is_pod (type) is true or type is a reference type then
3055 // the trait is true, else if type is a cv class or union type
3056 // with a trivial copy constructor ([class.copy]) then the trait
3057 // is true, else it is false.
3058 if (T.isPODType(Self.Context) || T->isReferenceType())
3059 return true;
3060 if (const RecordType *RT = T->getAs<RecordType>())
3061 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
3062 return false;
3063 case UTT_HasTrivialAssign:
3064 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3065 // If type is const qualified or is a reference type then the
3066 // trait is false. Otherwise if __is_pod (type) is true then the
3067 // trait is true, else if type is a cv class or union type with
3068 // a trivial copy assignment ([class.copy]) then the trait is
3069 // true, else it is false.
3070 // Note: the const and reference restrictions are interesting,
3071 // given that const and reference members don't prevent a class
3072 // from having a trivial copy assignment operator (but do cause
3073 // errors if the copy assignment operator is actually used, q.v.
3074 // [class.copy]p12).
3075
3076 if (C.getBaseElementType(T).isConstQualified())
3077 return false;
3078 if (T.isPODType(Self.Context))
3079 return true;
3080 if (const RecordType *RT = T->getAs<RecordType>())
3081 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
3082 return false;
3083 case UTT_HasTrivialDestructor:
3084 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3085 // If __is_pod (type) is true or type is a reference type
3086 // then the trait is true, else if type is a cv class or union
3087 // type (or array thereof) with a trivial destructor
3088 // ([class.dtor]) then the trait is true, else it is
3089 // false.
3090 if (T.isPODType(Self.Context) || T->isReferenceType())
3091 return true;
3092
3093 // Objective-C++ ARC: autorelease types don't require destruction.
3094 if (T->isObjCLifetimeType() &&
3095 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3096 return true;
3097
3098 if (const RecordType *RT =
3099 C.getBaseElementType(T)->getAs<RecordType>())
3100 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
3101 return false;
3102 // TODO: Propagate nothrowness for implicitly declared special members.
3103 case UTT_HasNothrowAssign:
3104 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3105 // If type is const qualified or is a reference type then the
3106 // trait is false. Otherwise if __has_trivial_assign (type)
3107 // is true then the trait is true, else if type is a cv class
3108 // or union type with copy assignment operators that are known
3109 // not to throw an exception then the trait is true, else it is
3110 // false.
3111 if (C.getBaseElementType(T).isConstQualified())
3112 return false;
3113 if (T->isReferenceType())
3114 return false;
3115 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
3116 return true;
3117 if (const RecordType *RT = T->getAs<RecordType>()) {
3118 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
3119 if (RD->hasTrivialCopyAssignment())
3120 return true;
3121
3122 bool FoundAssign = false;
3123 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
3124 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
3125 Sema::LookupOrdinaryName);
3126 if (Self.LookupQualifiedName(Res, RD)) {
3127 Res.suppressDiagnostics();
3128 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3129 Op != OpEnd; ++Op) {
3130 if (isa<FunctionTemplateDecl>(*Op))
3131 continue;
3132
3133 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3134 if (Operator->isCopyAssignmentOperator()) {
3135 FoundAssign = true;
3136 const FunctionProtoType *CPT
3137 = Operator->getType()->getAs<FunctionProtoType>();
3138 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3139 if (!CPT)
3140 return false;
3141 if (CPT->getExceptionSpecType() == EST_Delayed)
3142 return false;
3143 if (!CPT->isNothrow(Self.Context))
3144 return false;
3145 }
3146 }
3147 }
3148
3149 return FoundAssign;
3150 }
3151 return false;
3152 case UTT_HasNothrowCopy:
3153 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3154 // If __has_trivial_copy (type) is true then the trait is true, else
3155 // if type is a cv class or union type with copy constructors that are
3156 // known not to throw an exception then the trait is true, else it is
3157 // false.
3158 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
3159 return true;
3160 if (const RecordType *RT = T->getAs<RecordType>()) {
3161 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3162 if (RD->hasTrivialCopyConstructor())
3163 return true;
3164
3165 bool FoundConstructor = false;
3166 unsigned FoundTQs;
3167 DeclContext::lookup_const_iterator Con, ConEnd;
3168 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3169 Con != ConEnd; ++Con) {
3170 // A template constructor is never a copy constructor.
3171 // FIXME: However, it may actually be selected at the actual overload
3172 // resolution point.
3173 if (isa<FunctionTemplateDecl>(*Con))
3174 continue;
3175 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3176 if (Constructor->isCopyConstructor(FoundTQs)) {
3177 FoundConstructor = true;
3178 const FunctionProtoType *CPT
3179 = Constructor->getType()->getAs<FunctionProtoType>();
3180 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3181 if (!CPT)
3182 return false;
3183 if (CPT->getExceptionSpecType() == EST_Delayed)
3184 return false;
3185 // FIXME: check whether evaluating default arguments can throw.
3186 // For now, we'll be conservative and assume that they can throw.
3187 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3188 return false;
3189 }
3190 }
3191
3192 return FoundConstructor;
3193 }
3194 return false;
3195 case UTT_HasNothrowConstructor:
3196 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3197 // If __has_trivial_constructor (type) is true then the trait is
3198 // true, else if type is a cv class or union type (or array
3199 // thereof) with a default constructor that is known not to
3200 // throw an exception then the trait is true, else it is false.
3201 if (T.isPODType(C) || T->isObjCLifetimeType())
3202 return true;
3203 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3204 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3205 if (RD->hasTrivialDefaultConstructor())
3206 return true;
3207
3208 DeclContext::lookup_const_iterator Con, ConEnd;
3209 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3210 Con != ConEnd; ++Con) {
3211 // FIXME: In C++0x, a constructor template can be a default constructor.
3212 if (isa<FunctionTemplateDecl>(*Con))
3213 continue;
3214 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3215 if (Constructor->isDefaultConstructor()) {
3216 const FunctionProtoType *CPT
3217 = Constructor->getType()->getAs<FunctionProtoType>();
3218 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3219 if (!CPT)
3220 return false;
3221 if (CPT->getExceptionSpecType() == EST_Delayed)
3222 return false;
3223 // TODO: check whether evaluating default arguments can throw.
3224 // For now, we'll be conservative and assume that they can throw.
3225 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
3226 }
3227 }
3228 }
3229 return false;
3230 case UTT_HasVirtualDestructor:
3231 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3232 // If type is a class type with a virtual destructor ([class.dtor])
3233 // then the trait is true, else it is false.
3234 if (const RecordType *Record = T->getAs<RecordType>()) {
3235 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
3236 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
3237 return Destructor->isVirtual();
3238 }
3239 return false;
3240
3241 // These type trait expressions are modeled on the specifications for the
3242 // Embarcadero C++0x type trait functions:
3243 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3244 case UTT_IsCompleteType:
3245 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3246 // Returns True if and only if T is a complete type at the point of the
3247 // function call.
3248 return !T->isIncompleteType();
3249 }
3250 llvm_unreachable("Type trait not covered by switch");
3251 }
3252
BuildUnaryTypeTrait(UnaryTypeTrait UTT,SourceLocation KWLoc,TypeSourceInfo * TSInfo,SourceLocation RParen)3253 ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
3254 SourceLocation KWLoc,
3255 TypeSourceInfo *TSInfo,
3256 SourceLocation RParen) {
3257 QualType T = TSInfo->getType();
3258 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3259 return ExprError();
3260
3261 bool Value = false;
3262 if (!T->isDependentType())
3263 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
3264
3265 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
3266 RParen, Context.BoolTy));
3267 }
3268
ActOnBinaryTypeTrait(BinaryTypeTrait BTT,SourceLocation KWLoc,ParsedType LhsTy,ParsedType RhsTy,SourceLocation RParen)3269 ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3270 SourceLocation KWLoc,
3271 ParsedType LhsTy,
3272 ParsedType RhsTy,
3273 SourceLocation RParen) {
3274 TypeSourceInfo *LhsTSInfo;
3275 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3276 if (!LhsTSInfo)
3277 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3278
3279 TypeSourceInfo *RhsTSInfo;
3280 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3281 if (!RhsTSInfo)
3282 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3283
3284 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3285 }
3286
evaluateTypeTrait(Sema & S,TypeTrait Kind,SourceLocation KWLoc,ArrayRef<TypeSourceInfo * > Args,SourceLocation RParenLoc)3287 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3288 ArrayRef<TypeSourceInfo *> Args,
3289 SourceLocation RParenLoc) {
3290 switch (Kind) {
3291 case clang::TT_IsTriviallyConstructible: {
3292 // C++11 [meta.unary.prop]:
3293 // is_trivially_constructible is defined as:
3294 //
3295 // is_constructible<T, Args...>::value is true and the variable
3296 // definition for is_constructible, as defined below, is known to call no
3297 // operation that is not trivial.
3298 //
3299 // The predicate condition for a template specialization
3300 // is_constructible<T, Args...> shall be satisfied if and only if the
3301 // following variable definition would be well-formed for some invented
3302 // variable t:
3303 //
3304 // T t(create<Args>()...);
3305 if (Args.empty()) {
3306 S.Diag(KWLoc, diag::err_type_trait_arity)
3307 << 1 << 1 << 1 << (int)Args.size();
3308 return false;
3309 }
3310
3311 bool SawVoid = false;
3312 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3313 if (Args[I]->getType()->isVoidType()) {
3314 SawVoid = true;
3315 continue;
3316 }
3317
3318 if (!Args[I]->getType()->isIncompleteType() &&
3319 S.RequireCompleteType(KWLoc, Args[I]->getType(),
3320 diag::err_incomplete_type_used_in_type_trait_expr))
3321 return false;
3322 }
3323
3324 // If any argument was 'void', of course it won't type-check.
3325 if (SawVoid)
3326 return false;
3327
3328 llvm::SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3329 llvm::SmallVector<Expr *, 2> ArgExprs;
3330 ArgExprs.reserve(Args.size() - 1);
3331 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3332 QualType T = Args[I]->getType();
3333 if (T->isObjectType() || T->isFunctionType())
3334 T = S.Context.getRValueReferenceType(T);
3335 OpaqueArgExprs.push_back(
3336 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
3337 T.getNonLValueExprType(S.Context),
3338 Expr::getValueKindForType(T)));
3339 ArgExprs.push_back(&OpaqueArgExprs.back());
3340 }
3341
3342 // Perform the initialization in an unevaluated context within a SFINAE
3343 // trap at translation unit scope.
3344 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3345 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3346 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3347 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3348 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3349 RParenLoc));
3350 InitializationSequence Init(S, To, InitKind,
3351 ArgExprs.begin(), ArgExprs.size());
3352 if (Init.Failed())
3353 return false;
3354
3355 ExprResult Result = Init.Perform(S, To, InitKind,
3356 MultiExprArg(ArgExprs.data(),
3357 ArgExprs.size()));
3358 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3359 return false;
3360
3361 // The initialization succeeded; not make sure there are no non-trivial
3362 // calls.
3363 return !Result.get()->hasNonTrivialCall(S.Context);
3364 }
3365 }
3366
3367 return false;
3368 }
3369
BuildTypeTrait(TypeTrait Kind,SourceLocation KWLoc,ArrayRef<TypeSourceInfo * > Args,SourceLocation RParenLoc)3370 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3371 ArrayRef<TypeSourceInfo *> Args,
3372 SourceLocation RParenLoc) {
3373 bool Dependent = false;
3374 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3375 if (Args[I]->getType()->isDependentType()) {
3376 Dependent = true;
3377 break;
3378 }
3379 }
3380
3381 bool Value = false;
3382 if (!Dependent)
3383 Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3384
3385 return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind,
3386 Args, RParenLoc, Value);
3387 }
3388
ActOnTypeTrait(TypeTrait Kind,SourceLocation KWLoc,ArrayRef<ParsedType> Args,SourceLocation RParenLoc)3389 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3390 ArrayRef<ParsedType> Args,
3391 SourceLocation RParenLoc) {
3392 llvm::SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
3393 ConvertedArgs.reserve(Args.size());
3394
3395 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3396 TypeSourceInfo *TInfo;
3397 QualType T = GetTypeFromParser(Args[I], &TInfo);
3398 if (!TInfo)
3399 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3400
3401 ConvertedArgs.push_back(TInfo);
3402 }
3403
3404 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3405 }
3406
EvaluateBinaryTypeTrait(Sema & Self,BinaryTypeTrait BTT,QualType LhsT,QualType RhsT,SourceLocation KeyLoc)3407 static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3408 QualType LhsT, QualType RhsT,
3409 SourceLocation KeyLoc) {
3410 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3411 "Cannot evaluate traits of dependent types");
3412
3413 switch(BTT) {
3414 case BTT_IsBaseOf: {
3415 // C++0x [meta.rel]p2
3416 // Base is a base class of Derived without regard to cv-qualifiers or
3417 // Base and Derived are not unions and name the same class type without
3418 // regard to cv-qualifiers.
3419
3420 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3421 if (!lhsRecord) return false;
3422
3423 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3424 if (!rhsRecord) return false;
3425
3426 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3427 == (lhsRecord == rhsRecord));
3428
3429 if (lhsRecord == rhsRecord)
3430 return !lhsRecord->getDecl()->isUnion();
3431
3432 // C++0x [meta.rel]p2:
3433 // If Base and Derived are class types and are different types
3434 // (ignoring possible cv-qualifiers) then Derived shall be a
3435 // complete type.
3436 if (Self.RequireCompleteType(KeyLoc, RhsT,
3437 diag::err_incomplete_type_used_in_type_trait_expr))
3438 return false;
3439
3440 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3441 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3442 }
3443 case BTT_IsSame:
3444 return Self.Context.hasSameType(LhsT, RhsT);
3445 case BTT_TypeCompatible:
3446 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3447 RhsT.getUnqualifiedType());
3448 case BTT_IsConvertible:
3449 case BTT_IsConvertibleTo: {
3450 // C++0x [meta.rel]p4:
3451 // Given the following function prototype:
3452 //
3453 // template <class T>
3454 // typename add_rvalue_reference<T>::type create();
3455 //
3456 // the predicate condition for a template specialization
3457 // is_convertible<From, To> shall be satisfied if and only if
3458 // the return expression in the following code would be
3459 // well-formed, including any implicit conversions to the return
3460 // type of the function:
3461 //
3462 // To test() {
3463 // return create<From>();
3464 // }
3465 //
3466 // Access checking is performed as if in a context unrelated to To and
3467 // From. Only the validity of the immediate context of the expression
3468 // of the return-statement (including conversions to the return type)
3469 // is considered.
3470 //
3471 // We model the initialization as a copy-initialization of a temporary
3472 // of the appropriate type, which for this expression is identical to the
3473 // return statement (since NRVO doesn't apply).
3474 if (LhsT->isObjectType() || LhsT->isFunctionType())
3475 LhsT = Self.Context.getRValueReferenceType(LhsT);
3476
3477 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
3478 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3479 Expr::getValueKindForType(LhsT));
3480 Expr *FromPtr = &From;
3481 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3482 SourceLocation()));
3483
3484 // Perform the initialization in an unevaluated context within a SFINAE
3485 // trap at translation unit scope.
3486 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3487 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3488 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3489 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
3490 if (Init.Failed())
3491 return false;
3492
3493 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3494 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3495 }
3496
3497 case BTT_IsTriviallyAssignable: {
3498 // C++11 [meta.unary.prop]p3:
3499 // is_trivially_assignable is defined as:
3500 // is_assignable<T, U>::value is true and the assignment, as defined by
3501 // is_assignable, is known to call no operation that is not trivial
3502 //
3503 // is_assignable is defined as:
3504 // The expression declval<T>() = declval<U>() is well-formed when
3505 // treated as an unevaluated operand (Clause 5).
3506 //
3507 // For both, T and U shall be complete types, (possibly cv-qualified)
3508 // void, or arrays of unknown bound.
3509 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3510 Self.RequireCompleteType(KeyLoc, LhsT,
3511 diag::err_incomplete_type_used_in_type_trait_expr))
3512 return false;
3513 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3514 Self.RequireCompleteType(KeyLoc, RhsT,
3515 diag::err_incomplete_type_used_in_type_trait_expr))
3516 return false;
3517
3518 // cv void is never assignable.
3519 if (LhsT->isVoidType() || RhsT->isVoidType())
3520 return false;
3521
3522 // Build expressions that emulate the effect of declval<T>() and
3523 // declval<U>().
3524 if (LhsT->isObjectType() || LhsT->isFunctionType())
3525 LhsT = Self.Context.getRValueReferenceType(LhsT);
3526 if (RhsT->isObjectType() || RhsT->isFunctionType())
3527 RhsT = Self.Context.getRValueReferenceType(RhsT);
3528 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3529 Expr::getValueKindForType(LhsT));
3530 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3531 Expr::getValueKindForType(RhsT));
3532
3533 // Attempt the assignment in an unevaluated context within a SFINAE
3534 // trap at translation unit scope.
3535 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3536 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3537 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3538 ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs);
3539 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3540 return false;
3541
3542 return !Result.get()->hasNonTrivialCall(Self.Context);
3543 }
3544 }
3545 llvm_unreachable("Unknown type trait or not implemented");
3546 }
3547
BuildBinaryTypeTrait(BinaryTypeTrait BTT,SourceLocation KWLoc,TypeSourceInfo * LhsTSInfo,TypeSourceInfo * RhsTSInfo,SourceLocation RParen)3548 ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3549 SourceLocation KWLoc,
3550 TypeSourceInfo *LhsTSInfo,
3551 TypeSourceInfo *RhsTSInfo,
3552 SourceLocation RParen) {
3553 QualType LhsT = LhsTSInfo->getType();
3554 QualType RhsT = RhsTSInfo->getType();
3555
3556 if (BTT == BTT_TypeCompatible) {
3557 if (getLangOpts().CPlusPlus) {
3558 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3559 << SourceRange(KWLoc, RParen);
3560 return ExprError();
3561 }
3562 }
3563
3564 bool Value = false;
3565 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3566 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3567
3568 // Select trait result type.
3569 QualType ResultType;
3570 switch (BTT) {
3571 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
3572 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3573 case BTT_IsSame: ResultType = Context.BoolTy; break;
3574 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
3575 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
3576 case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy;
3577 }
3578
3579 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3580 RhsTSInfo, Value, RParen,
3581 ResultType));
3582 }
3583
ActOnArrayTypeTrait(ArrayTypeTrait ATT,SourceLocation KWLoc,ParsedType Ty,Expr * DimExpr,SourceLocation RParen)3584 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3585 SourceLocation KWLoc,
3586 ParsedType Ty,
3587 Expr* DimExpr,
3588 SourceLocation RParen) {
3589 TypeSourceInfo *TSInfo;
3590 QualType T = GetTypeFromParser(Ty, &TSInfo);
3591 if (!TSInfo)
3592 TSInfo = Context.getTrivialTypeSourceInfo(T);
3593
3594 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3595 }
3596
EvaluateArrayTypeTrait(Sema & Self,ArrayTypeTrait ATT,QualType T,Expr * DimExpr,SourceLocation KeyLoc)3597 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3598 QualType T, Expr *DimExpr,
3599 SourceLocation KeyLoc) {
3600 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
3601
3602 switch(ATT) {
3603 case ATT_ArrayRank:
3604 if (T->isArrayType()) {
3605 unsigned Dim = 0;
3606 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3607 ++Dim;
3608 T = AT->getElementType();
3609 }
3610 return Dim;
3611 }
3612 return 0;
3613
3614 case ATT_ArrayExtent: {
3615 llvm::APSInt Value;
3616 uint64_t Dim;
3617 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
3618 Self.PDiag(diag::err_dimension_expr_not_constant_integer),
3619 false).isInvalid())
3620 return 0;
3621 if (Value.isSigned() && Value.isNegative()) {
3622 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
3623 << DimExpr->getSourceRange();
3624 return 0;
3625 }
3626 Dim = Value.getLimitedValue();
3627
3628 if (T->isArrayType()) {
3629 unsigned D = 0;
3630 bool Matched = false;
3631 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3632 if (Dim == D) {
3633 Matched = true;
3634 break;
3635 }
3636 ++D;
3637 T = AT->getElementType();
3638 }
3639
3640 if (Matched && T->isArrayType()) {
3641 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3642 return CAT->getSize().getLimitedValue();
3643 }
3644 }
3645 return 0;
3646 }
3647 }
3648 llvm_unreachable("Unknown type trait or not implemented");
3649 }
3650
BuildArrayTypeTrait(ArrayTypeTrait ATT,SourceLocation KWLoc,TypeSourceInfo * TSInfo,Expr * DimExpr,SourceLocation RParen)3651 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3652 SourceLocation KWLoc,
3653 TypeSourceInfo *TSInfo,
3654 Expr* DimExpr,
3655 SourceLocation RParen) {
3656 QualType T = TSInfo->getType();
3657
3658 // FIXME: This should likely be tracked as an APInt to remove any host
3659 // assumptions about the width of size_t on the target.
3660 uint64_t Value = 0;
3661 if (!T->isDependentType())
3662 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3663
3664 // While the specification for these traits from the Embarcadero C++
3665 // compiler's documentation says the return type is 'unsigned int', Clang
3666 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3667 // compiler, there is no difference. On several other platforms this is an
3668 // important distinction.
3669 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
3670 DimExpr, RParen,
3671 Context.getSizeType()));
3672 }
3673
ActOnExpressionTrait(ExpressionTrait ET,SourceLocation KWLoc,Expr * Queried,SourceLocation RParen)3674 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
3675 SourceLocation KWLoc,
3676 Expr *Queried,
3677 SourceLocation RParen) {
3678 // If error parsing the expression, ignore.
3679 if (!Queried)
3680 return ExprError();
3681
3682 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
3683
3684 return move(Result);
3685 }
3686
EvaluateExpressionTrait(ExpressionTrait ET,Expr * E)3687 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3688 switch (ET) {
3689 case ET_IsLValueExpr: return E->isLValue();
3690 case ET_IsRValueExpr: return E->isRValue();
3691 }
3692 llvm_unreachable("Expression trait not covered by switch");
3693 }
3694
BuildExpressionTrait(ExpressionTrait ET,SourceLocation KWLoc,Expr * Queried,SourceLocation RParen)3695 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
3696 SourceLocation KWLoc,
3697 Expr *Queried,
3698 SourceLocation RParen) {
3699 if (Queried->isTypeDependent()) {
3700 // Delay type-checking for type-dependent expressions.
3701 } else if (Queried->getType()->isPlaceholderType()) {
3702 ExprResult PE = CheckPlaceholderExpr(Queried);
3703 if (PE.isInvalid()) return ExprError();
3704 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3705 }
3706
3707 bool Value = EvaluateExpressionTrait(ET, Queried);
3708
3709 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3710 RParen, Context.BoolTy));
3711 }
3712
CheckPointerToMemberOperands(ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,SourceLocation Loc,bool isIndirect)3713 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
3714 ExprValueKind &VK,
3715 SourceLocation Loc,
3716 bool isIndirect) {
3717 assert(!LHS.get()->getType()->isPlaceholderType() &&
3718 !RHS.get()->getType()->isPlaceholderType() &&
3719 "placeholders should have been weeded out by now");
3720
3721 // The LHS undergoes lvalue conversions if this is ->*.
3722 if (isIndirect) {
3723 LHS = DefaultLvalueConversion(LHS.take());
3724 if (LHS.isInvalid()) return QualType();
3725 }
3726
3727 // The RHS always undergoes lvalue conversions.
3728 RHS = DefaultLvalueConversion(RHS.take());
3729 if (RHS.isInvalid()) return QualType();
3730
3731 const char *OpSpelling = isIndirect ? "->*" : ".*";
3732 // C++ 5.5p2
3733 // The binary operator .* [p3: ->*] binds its second operand, which shall
3734 // be of type "pointer to member of T" (where T is a completely-defined
3735 // class type) [...]
3736 QualType RHSType = RHS.get()->getType();
3737 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
3738 if (!MemPtr) {
3739 Diag(Loc, diag::err_bad_memptr_rhs)
3740 << OpSpelling << RHSType << RHS.get()->getSourceRange();
3741 return QualType();
3742 }
3743
3744 QualType Class(MemPtr->getClass(), 0);
3745
3746 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3747 // member pointer points must be completely-defined. However, there is no
3748 // reason for this semantic distinction, and the rule is not enforced by
3749 // other compilers. Therefore, we do not check this property, as it is
3750 // likely to be considered a defect.
3751
3752 // C++ 5.5p2
3753 // [...] to its first operand, which shall be of class T or of a class of
3754 // which T is an unambiguous and accessible base class. [p3: a pointer to
3755 // such a class]
3756 QualType LHSType = LHS.get()->getType();
3757 if (isIndirect) {
3758 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3759 LHSType = Ptr->getPointeeType();
3760 else {
3761 Diag(Loc, diag::err_bad_memptr_lhs)
3762 << OpSpelling << 1 << LHSType
3763 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
3764 return QualType();
3765 }
3766 }
3767
3768 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
3769 // If we want to check the hierarchy, we need a complete type.
3770 if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
3771 << OpSpelling << (int)isIndirect)) {
3772 return QualType();
3773 }
3774 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3775 /*DetectVirtual=*/false);
3776 // FIXME: Would it be useful to print full ambiguity paths, or is that
3777 // overkill?
3778 if (!IsDerivedFrom(LHSType, Class, Paths) ||
3779 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3780 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
3781 << (int)isIndirect << LHS.get()->getType();
3782 return QualType();
3783 }
3784 // Cast LHS to type of use.
3785 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
3786 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
3787
3788 CXXCastPath BasePath;
3789 BuildBasePathArray(Paths, BasePath);
3790 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3791 &BasePath);
3792 }
3793
3794 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
3795 // Diagnose use of pointer-to-member type which when used as
3796 // the functional cast in a pointer-to-member expression.
3797 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3798 return QualType();
3799 }
3800
3801 // C++ 5.5p2
3802 // The result is an object or a function of the type specified by the
3803 // second operand.
3804 // The cv qualifiers are the union of those in the pointer and the left side,
3805 // in accordance with 5.5p5 and 5.2.5.
3806 QualType Result = MemPtr->getPointeeType();
3807 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
3808
3809 // C++0x [expr.mptr.oper]p6:
3810 // In a .* expression whose object expression is an rvalue, the program is
3811 // ill-formed if the second operand is a pointer to member function with
3812 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3813 // expression is an lvalue, the program is ill-formed if the second operand
3814 // is a pointer to member function with ref-qualifier &&.
3815 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3816 switch (Proto->getRefQualifier()) {
3817 case RQ_None:
3818 // Do nothing
3819 break;
3820
3821 case RQ_LValue:
3822 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
3823 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
3824 << RHSType << 1 << LHS.get()->getSourceRange();
3825 break;
3826
3827 case RQ_RValue:
3828 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
3829 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
3830 << RHSType << 0 << LHS.get()->getSourceRange();
3831 break;
3832 }
3833 }
3834
3835 // C++ [expr.mptr.oper]p6:
3836 // The result of a .* expression whose second operand is a pointer
3837 // to a data member is of the same value category as its
3838 // first operand. The result of a .* expression whose second
3839 // operand is a pointer to a member function is a prvalue. The
3840 // result of an ->* expression is an lvalue if its second operand
3841 // is a pointer to data member and a prvalue otherwise.
3842 if (Result->isFunctionType()) {
3843 VK = VK_RValue;
3844 return Context.BoundMemberTy;
3845 } else if (isIndirect) {
3846 VK = VK_LValue;
3847 } else {
3848 VK = LHS.get()->getValueKind();
3849 }
3850
3851 return Result;
3852 }
3853
3854 /// \brief Try to convert a type to another according to C++0x 5.16p3.
3855 ///
3856 /// This is part of the parameter validation for the ? operator. If either
3857 /// value operand is a class type, the two operands are attempted to be
3858 /// converted to each other. This function does the conversion in one direction.
3859 /// It returns true if the program is ill-formed and has already been diagnosed
3860 /// as such.
TryClassUnification(Sema & Self,Expr * From,Expr * To,SourceLocation QuestionLoc,bool & HaveConversion,QualType & ToType)3861 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3862 SourceLocation QuestionLoc,
3863 bool &HaveConversion,
3864 QualType &ToType) {
3865 HaveConversion = false;
3866 ToType = To->getType();
3867
3868 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
3869 SourceLocation());
3870 // C++0x 5.16p3
3871 // The process for determining whether an operand expression E1 of type T1
3872 // can be converted to match an operand expression E2 of type T2 is defined
3873 // as follows:
3874 // -- If E2 is an lvalue:
3875 bool ToIsLvalue = To->isLValue();
3876 if (ToIsLvalue) {
3877 // E1 can be converted to match E2 if E1 can be implicitly converted to
3878 // type "lvalue reference to T2", subject to the constraint that in the
3879 // conversion the reference must bind directly to E1.
3880 QualType T = Self.Context.getLValueReferenceType(ToType);
3881 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
3882
3883 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3884 if (InitSeq.isDirectReferenceBinding()) {
3885 ToType = T;
3886 HaveConversion = true;
3887 return false;
3888 }
3889
3890 if (InitSeq.isAmbiguous())
3891 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3892 }
3893
3894 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3895 // -- if E1 and E2 have class type, and the underlying class types are
3896 // the same or one is a base class of the other:
3897 QualType FTy = From->getType();
3898 QualType TTy = To->getType();
3899 const RecordType *FRec = FTy->getAs<RecordType>();
3900 const RecordType *TRec = TTy->getAs<RecordType>();
3901 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
3902 Self.IsDerivedFrom(FTy, TTy);
3903 if (FRec && TRec &&
3904 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
3905 // E1 can be converted to match E2 if the class of T2 is the
3906 // same type as, or a base class of, the class of T1, and
3907 // [cv2 > cv1].
3908 if (FRec == TRec || FDerivedFromT) {
3909 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
3910 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3911 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3912 if (InitSeq) {
3913 HaveConversion = true;
3914 return false;
3915 }
3916
3917 if (InitSeq.isAmbiguous())
3918 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3919 }
3920 }
3921
3922 return false;
3923 }
3924
3925 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3926 // implicitly converted to the type that expression E2 would have
3927 // if E2 were converted to an rvalue (or the type it has, if E2 is
3928 // an rvalue).
3929 //
3930 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3931 // to the array-to-pointer or function-to-pointer conversions.
3932 if (!TTy->getAs<TagType>())
3933 TTy = TTy.getUnqualifiedType();
3934
3935 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3936 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3937 HaveConversion = !InitSeq.Failed();
3938 ToType = TTy;
3939 if (InitSeq.isAmbiguous())
3940 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3941
3942 return false;
3943 }
3944
3945 /// \brief Try to find a common type for two according to C++0x 5.16p5.
3946 ///
3947 /// This is part of the parameter validation for the ? operator. If either
3948 /// value operand is a class type, overload resolution is used to find a
3949 /// conversion to a common type.
FindConditionalOverload(Sema & Self,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)3950 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
3951 SourceLocation QuestionLoc) {
3952 Expr *Args[2] = { LHS.get(), RHS.get() };
3953 OverloadCandidateSet CandidateSet(QuestionLoc);
3954 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3955 CandidateSet);
3956
3957 OverloadCandidateSet::iterator Best;
3958 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
3959 case OR_Success: {
3960 // We found a match. Perform the conversions on the arguments and move on.
3961 ExprResult LHSRes =
3962 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3963 Best->Conversions[0], Sema::AA_Converting);
3964 if (LHSRes.isInvalid())
3965 break;
3966 LHS = move(LHSRes);
3967
3968 ExprResult RHSRes =
3969 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3970 Best->Conversions[1], Sema::AA_Converting);
3971 if (RHSRes.isInvalid())
3972 break;
3973 RHS = move(RHSRes);
3974 if (Best->Function)
3975 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
3976 return false;
3977 }
3978
3979 case OR_No_Viable_Function:
3980
3981 // Emit a better diagnostic if one of the expressions is a null pointer
3982 // constant and the other is a pointer type. In this case, the user most
3983 // likely forgot to take the address of the other expression.
3984 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
3985 return true;
3986
3987 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3988 << LHS.get()->getType() << RHS.get()->getType()
3989 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3990 return true;
3991
3992 case OR_Ambiguous:
3993 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
3994 << LHS.get()->getType() << RHS.get()->getType()
3995 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3996 // FIXME: Print the possible common types by printing the return types of
3997 // the viable candidates.
3998 break;
3999
4000 case OR_Deleted:
4001 llvm_unreachable("Conditional operator has only built-in overloads");
4002 }
4003 return true;
4004 }
4005
4006 /// \brief Perform an "extended" implicit conversion as returned by
4007 /// TryClassUnification.
ConvertForConditional(Sema & Self,ExprResult & E,QualType T)4008 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
4009 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
4010 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
4011 SourceLocation());
4012 Expr *Arg = E.take();
4013 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
4014 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
4015 if (Result.isInvalid())
4016 return true;
4017
4018 E = Result;
4019 return false;
4020 }
4021
4022 /// \brief Check the operands of ?: under C++ semantics.
4023 ///
4024 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4025 /// extension. In this case, LHS == Cond. (But they're not aliases.)
CXXCheckConditionalOperands(ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation QuestionLoc)4026 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
4027 ExprValueKind &VK, ExprObjectKind &OK,
4028 SourceLocation QuestionLoc) {
4029 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4030 // interface pointers.
4031
4032 // C++0x 5.16p1
4033 // The first expression is contextually converted to bool.
4034 if (!Cond.get()->isTypeDependent()) {
4035 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
4036 if (CondRes.isInvalid())
4037 return QualType();
4038 Cond = move(CondRes);
4039 }
4040
4041 // Assume r-value.
4042 VK = VK_RValue;
4043 OK = OK_Ordinary;
4044
4045 // Either of the arguments dependent?
4046 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
4047 return Context.DependentTy;
4048
4049 // C++0x 5.16p2
4050 // If either the second or the third operand has type (cv) void, ...
4051 QualType LTy = LHS.get()->getType();
4052 QualType RTy = RHS.get()->getType();
4053 bool LVoid = LTy->isVoidType();
4054 bool RVoid = RTy->isVoidType();
4055 if (LVoid || RVoid) {
4056 // ... then the [l2r] conversions are performed on the second and third
4057 // operands ...
4058 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4059 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4060 if (LHS.isInvalid() || RHS.isInvalid())
4061 return QualType();
4062 LTy = LHS.get()->getType();
4063 RTy = RHS.get()->getType();
4064
4065 // ... and one of the following shall hold:
4066 // -- The second or the third operand (but not both) is a throw-
4067 // expression; the result is of the type of the other and is an rvalue.
4068 bool LThrow = isa<CXXThrowExpr>(LHS.get());
4069 bool RThrow = isa<CXXThrowExpr>(RHS.get());
4070 if (LThrow && !RThrow)
4071 return RTy;
4072 if (RThrow && !LThrow)
4073 return LTy;
4074
4075 // -- Both the second and third operands have type void; the result is of
4076 // type void and is an rvalue.
4077 if (LVoid && RVoid)
4078 return Context.VoidTy;
4079
4080 // Neither holds, error.
4081 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4082 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
4083 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4084 return QualType();
4085 }
4086
4087 // Neither is void.
4088
4089 // C++0x 5.16p3
4090 // Otherwise, if the second and third operand have different types, and
4091 // either has (cv) class type, and attempt is made to convert each of those
4092 // operands to the other.
4093 if (!Context.hasSameType(LTy, RTy) &&
4094 (LTy->isRecordType() || RTy->isRecordType())) {
4095 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
4096 // These return true if a single direction is already ambiguous.
4097 QualType L2RType, R2LType;
4098 bool HaveL2R, HaveR2L;
4099 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
4100 return QualType();
4101 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
4102 return QualType();
4103
4104 // If both can be converted, [...] the program is ill-formed.
4105 if (HaveL2R && HaveR2L) {
4106 Diag(QuestionLoc, diag::err_conditional_ambiguous)
4107 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4108 return QualType();
4109 }
4110
4111 // If exactly one conversion is possible, that conversion is applied to
4112 // the chosen operand and the converted operands are used in place of the
4113 // original operands for the remainder of this section.
4114 if (HaveL2R) {
4115 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
4116 return QualType();
4117 LTy = LHS.get()->getType();
4118 } else if (HaveR2L) {
4119 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
4120 return QualType();
4121 RTy = RHS.get()->getType();
4122 }
4123 }
4124
4125 // C++0x 5.16p4
4126 // If the second and third operands are glvalues of the same value
4127 // category and have the same type, the result is of that type and
4128 // value category and it is a bit-field if the second or the third
4129 // operand is a bit-field, or if both are bit-fields.
4130 // We only extend this to bitfields, not to the crazy other kinds of
4131 // l-values.
4132 bool Same = Context.hasSameType(LTy, RTy);
4133 if (Same &&
4134 LHS.get()->isGLValue() &&
4135 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
4136 LHS.get()->isOrdinaryOrBitFieldObject() &&
4137 RHS.get()->isOrdinaryOrBitFieldObject()) {
4138 VK = LHS.get()->getValueKind();
4139 if (LHS.get()->getObjectKind() == OK_BitField ||
4140 RHS.get()->getObjectKind() == OK_BitField)
4141 OK = OK_BitField;
4142 return LTy;
4143 }
4144
4145 // C++0x 5.16p5
4146 // Otherwise, the result is an rvalue. If the second and third operands
4147 // do not have the same type, and either has (cv) class type, ...
4148 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4149 // ... overload resolution is used to determine the conversions (if any)
4150 // to be applied to the operands. If the overload resolution fails, the
4151 // program is ill-formed.
4152 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4153 return QualType();
4154 }
4155
4156 // C++0x 5.16p6
4157 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
4158 // conversions are performed on the second and third operands.
4159 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4160 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4161 if (LHS.isInvalid() || RHS.isInvalid())
4162 return QualType();
4163 LTy = LHS.get()->getType();
4164 RTy = RHS.get()->getType();
4165
4166 // After those conversions, one of the following shall hold:
4167 // -- The second and third operands have the same type; the result
4168 // is of that type. If the operands have class type, the result
4169 // is a prvalue temporary of the result type, which is
4170 // copy-initialized from either the second operand or the third
4171 // operand depending on the value of the first operand.
4172 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4173 if (LTy->isRecordType()) {
4174 // The operands have class type. Make a temporary copy.
4175 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
4176 ExprResult LHSCopy = PerformCopyInitialization(Entity,
4177 SourceLocation(),
4178 LHS);
4179 if (LHSCopy.isInvalid())
4180 return QualType();
4181
4182 ExprResult RHSCopy = PerformCopyInitialization(Entity,
4183 SourceLocation(),
4184 RHS);
4185 if (RHSCopy.isInvalid())
4186 return QualType();
4187
4188 LHS = LHSCopy;
4189 RHS = RHSCopy;
4190 }
4191
4192 return LTy;
4193 }
4194
4195 // Extension: conditional operator involving vector types.
4196 if (LTy->isVectorType() || RTy->isVectorType())
4197 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4198
4199 // -- The second and third operands have arithmetic or enumeration type;
4200 // the usual arithmetic conversions are performed to bring them to a
4201 // common type, and the result is of that type.
4202 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4203 UsualArithmeticConversions(LHS, RHS);
4204 if (LHS.isInvalid() || RHS.isInvalid())
4205 return QualType();
4206 return LHS.get()->getType();
4207 }
4208
4209 // -- The second and third operands have pointer type, or one has pointer
4210 // type and the other is a null pointer constant; pointer conversions
4211 // and qualification conversions are performed to bring them to their
4212 // composite pointer type. The result is of the composite pointer type.
4213 // -- The second and third operands have pointer to member type, or one has
4214 // pointer to member type and the other is a null pointer constant;
4215 // pointer to member conversions and qualification conversions are
4216 // performed to bring them to a common type, whose cv-qualification
4217 // shall match the cv-qualification of either the second or the third
4218 // operand. The result is of the common type.
4219 bool NonStandardCompositeType = false;
4220 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
4221 isSFINAEContext()? 0 : &NonStandardCompositeType);
4222 if (!Composite.isNull()) {
4223 if (NonStandardCompositeType)
4224 Diag(QuestionLoc,
4225 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4226 << LTy << RTy << Composite
4227 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4228
4229 return Composite;
4230 }
4231
4232 // Similarly, attempt to find composite type of two objective-c pointers.
4233 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4234 if (!Composite.isNull())
4235 return Composite;
4236
4237 // Check if we are using a null with a non-pointer type.
4238 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4239 return QualType();
4240
4241 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4242 << LHS.get()->getType() << RHS.get()->getType()
4243 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4244 return QualType();
4245 }
4246
4247 /// \brief Find a merged pointer type and convert the two expressions to it.
4248 ///
4249 /// This finds the composite pointer type (or member pointer type) for @p E1
4250 /// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
4251 /// type and returns it.
4252 /// It does not emit diagnostics.
4253 ///
4254 /// \param Loc The location of the operator requiring these two expressions to
4255 /// be converted to the composite pointer type.
4256 ///
4257 /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4258 /// a non-standard (but still sane) composite type to which both expressions
4259 /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4260 /// will be set true.
FindCompositePointerType(SourceLocation Loc,Expr * & E1,Expr * & E2,bool * NonStandardCompositeType)4261 QualType Sema::FindCompositePointerType(SourceLocation Loc,
4262 Expr *&E1, Expr *&E2,
4263 bool *NonStandardCompositeType) {
4264 if (NonStandardCompositeType)
4265 *NonStandardCompositeType = false;
4266
4267 assert(getLangOpts().CPlusPlus && "This function assumes C++");
4268 QualType T1 = E1->getType(), T2 = E2->getType();
4269
4270 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4271 !T2->isAnyPointerType() && !T2->isMemberPointerType())
4272 return QualType();
4273
4274 // C++0x 5.9p2
4275 // Pointer conversions and qualification conversions are performed on
4276 // pointer operands to bring them to their composite pointer type. If
4277 // one operand is a null pointer constant, the composite pointer type is
4278 // the type of the other operand.
4279 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4280 if (T2->isMemberPointerType())
4281 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
4282 else
4283 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
4284 return T2;
4285 }
4286 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4287 if (T1->isMemberPointerType())
4288 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
4289 else
4290 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
4291 return T1;
4292 }
4293
4294 // Now both have to be pointers or member pointers.
4295 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4296 (!T2->isPointerType() && !T2->isMemberPointerType()))
4297 return QualType();
4298
4299 // Otherwise, of one of the operands has type "pointer to cv1 void," then
4300 // the other has type "pointer to cv2 T" and the composite pointer type is
4301 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4302 // Otherwise, the composite pointer type is a pointer type similar to the
4303 // type of one of the operands, with a cv-qualification signature that is
4304 // the union of the cv-qualification signatures of the operand types.
4305 // In practice, the first part here is redundant; it's subsumed by the second.
4306 // What we do here is, we build the two possible composite types, and try the
4307 // conversions in both directions. If only one works, or if the two composite
4308 // types are the same, we have succeeded.
4309 // FIXME: extended qualifiers?
4310 typedef SmallVector<unsigned, 4> QualifierVector;
4311 QualifierVector QualifierUnion;
4312 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
4313 ContainingClassVector;
4314 ContainingClassVector MemberOfClass;
4315 QualType Composite1 = Context.getCanonicalType(T1),
4316 Composite2 = Context.getCanonicalType(T2);
4317 unsigned NeedConstBefore = 0;
4318 do {
4319 const PointerType *Ptr1, *Ptr2;
4320 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4321 (Ptr2 = Composite2->getAs<PointerType>())) {
4322 Composite1 = Ptr1->getPointeeType();
4323 Composite2 = Ptr2->getPointeeType();
4324
4325 // If we're allowed to create a non-standard composite type, keep track
4326 // of where we need to fill in additional 'const' qualifiers.
4327 if (NonStandardCompositeType &&
4328 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4329 NeedConstBefore = QualifierUnion.size();
4330
4331 QualifierUnion.push_back(
4332 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4333 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
4334 continue;
4335 }
4336
4337 const MemberPointerType *MemPtr1, *MemPtr2;
4338 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4339 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4340 Composite1 = MemPtr1->getPointeeType();
4341 Composite2 = MemPtr2->getPointeeType();
4342
4343 // If we're allowed to create a non-standard composite type, keep track
4344 // of where we need to fill in additional 'const' qualifiers.
4345 if (NonStandardCompositeType &&
4346 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4347 NeedConstBefore = QualifierUnion.size();
4348
4349 QualifierUnion.push_back(
4350 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4351 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4352 MemPtr2->getClass()));
4353 continue;
4354 }
4355
4356 // FIXME: block pointer types?
4357
4358 // Cannot unwrap any more types.
4359 break;
4360 } while (true);
4361
4362 if (NeedConstBefore && NonStandardCompositeType) {
4363 // Extension: Add 'const' to qualifiers that come before the first qualifier
4364 // mismatch, so that our (non-standard!) composite type meets the
4365 // requirements of C++ [conv.qual]p4 bullet 3.
4366 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4367 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4368 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4369 *NonStandardCompositeType = true;
4370 }
4371 }
4372 }
4373
4374 // Rewrap the composites as pointers or member pointers with the union CVRs.
4375 ContainingClassVector::reverse_iterator MOC
4376 = MemberOfClass.rbegin();
4377 for (QualifierVector::reverse_iterator
4378 I = QualifierUnion.rbegin(),
4379 E = QualifierUnion.rend();
4380 I != E; (void)++I, ++MOC) {
4381 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
4382 if (MOC->first && MOC->second) {
4383 // Rebuild member pointer type
4384 Composite1 = Context.getMemberPointerType(
4385 Context.getQualifiedType(Composite1, Quals),
4386 MOC->first);
4387 Composite2 = Context.getMemberPointerType(
4388 Context.getQualifiedType(Composite2, Quals),
4389 MOC->second);
4390 } else {
4391 // Rebuild pointer type
4392 Composite1
4393 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4394 Composite2
4395 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
4396 }
4397 }
4398
4399 // Try to convert to the first composite pointer type.
4400 InitializedEntity Entity1
4401 = InitializedEntity::InitializeTemporary(Composite1);
4402 InitializationKind Kind
4403 = InitializationKind::CreateCopy(Loc, SourceLocation());
4404 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4405 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
4406
4407 if (E1ToC1 && E2ToC1) {
4408 // Conversion to Composite1 is viable.
4409 if (!Context.hasSameType(Composite1, Composite2)) {
4410 // Composite2 is a different type from Composite1. Check whether
4411 // Composite2 is also viable.
4412 InitializedEntity Entity2
4413 = InitializedEntity::InitializeTemporary(Composite2);
4414 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4415 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4416 if (E1ToC2 && E2ToC2) {
4417 // Both Composite1 and Composite2 are viable and are different;
4418 // this is an ambiguity.
4419 return QualType();
4420 }
4421 }
4422
4423 // Convert E1 to Composite1
4424 ExprResult E1Result
4425 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
4426 if (E1Result.isInvalid())
4427 return QualType();
4428 E1 = E1Result.takeAs<Expr>();
4429
4430 // Convert E2 to Composite1
4431 ExprResult E2Result
4432 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
4433 if (E2Result.isInvalid())
4434 return QualType();
4435 E2 = E2Result.takeAs<Expr>();
4436
4437 return Composite1;
4438 }
4439
4440 // Check whether Composite2 is viable.
4441 InitializedEntity Entity2
4442 = InitializedEntity::InitializeTemporary(Composite2);
4443 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4444 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4445 if (!E1ToC2 || !E2ToC2)
4446 return QualType();
4447
4448 // Convert E1 to Composite2
4449 ExprResult E1Result
4450 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
4451 if (E1Result.isInvalid())
4452 return QualType();
4453 E1 = E1Result.takeAs<Expr>();
4454
4455 // Convert E2 to Composite2
4456 ExprResult E2Result
4457 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
4458 if (E2Result.isInvalid())
4459 return QualType();
4460 E2 = E2Result.takeAs<Expr>();
4461
4462 return Composite2;
4463 }
4464
MaybeBindToTemporary(Expr * E)4465 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
4466 if (!E)
4467 return ExprError();
4468
4469 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4470
4471 // If the result is a glvalue, we shouldn't bind it.
4472 if (!E->isRValue())
4473 return Owned(E);
4474
4475 // In ARC, calls that return a retainable type can return retained,
4476 // in which case we have to insert a consuming cast.
4477 if (getLangOpts().ObjCAutoRefCount &&
4478 E->getType()->isObjCRetainableType()) {
4479
4480 bool ReturnsRetained;
4481
4482 // For actual calls, we compute this by examining the type of the
4483 // called value.
4484 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4485 Expr *Callee = Call->getCallee()->IgnoreParens();
4486 QualType T = Callee->getType();
4487
4488 if (T == Context.BoundMemberTy) {
4489 // Handle pointer-to-members.
4490 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4491 T = BinOp->getRHS()->getType();
4492 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4493 T = Mem->getMemberDecl()->getType();
4494 }
4495
4496 if (const PointerType *Ptr = T->getAs<PointerType>())
4497 T = Ptr->getPointeeType();
4498 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4499 T = Ptr->getPointeeType();
4500 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4501 T = MemPtr->getPointeeType();
4502
4503 const FunctionType *FTy = T->getAs<FunctionType>();
4504 assert(FTy && "call to value not of function type?");
4505 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4506
4507 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4508 // type always produce a +1 object.
4509 } else if (isa<StmtExpr>(E)) {
4510 ReturnsRetained = true;
4511
4512 // We hit this case with the lambda conversion-to-block optimization;
4513 // we don't want any extra casts here.
4514 } else if (isa<CastExpr>(E) &&
4515 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
4516 return Owned(E);
4517
4518 // For message sends and property references, we try to find an
4519 // actual method. FIXME: we should infer retention by selector in
4520 // cases where we don't have an actual method.
4521 } else {
4522 ObjCMethodDecl *D = 0;
4523 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4524 D = Send->getMethodDecl();
4525 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
4526 D = BoxedExpr->getBoxingMethod();
4527 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
4528 D = ArrayLit->getArrayWithObjectsMethod();
4529 } else if (ObjCDictionaryLiteral *DictLit
4530 = dyn_cast<ObjCDictionaryLiteral>(E)) {
4531 D = DictLit->getDictWithObjectsMethod();
4532 }
4533
4534 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
4535
4536 // Don't do reclaims on performSelector calls; despite their
4537 // return type, the invoked method doesn't necessarily actually
4538 // return an object.
4539 if (!ReturnsRetained &&
4540 D && D->getMethodFamily() == OMF_performSelector)
4541 return Owned(E);
4542 }
4543
4544 // Don't reclaim an object of Class type.
4545 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4546 return Owned(E);
4547
4548 ExprNeedsCleanups = true;
4549
4550 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4551 : CK_ARCReclaimReturnedObject);
4552 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4553 VK_RValue));
4554 }
4555
4556 if (!getLangOpts().CPlusPlus)
4557 return Owned(E);
4558
4559 // Search for the base element type (cf. ASTContext::getBaseElementType) with
4560 // a fast path for the common case that the type is directly a RecordType.
4561 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4562 const RecordType *RT = 0;
4563 while (!RT) {
4564 switch (T->getTypeClass()) {
4565 case Type::Record:
4566 RT = cast<RecordType>(T);
4567 break;
4568 case Type::ConstantArray:
4569 case Type::IncompleteArray:
4570 case Type::VariableArray:
4571 case Type::DependentSizedArray:
4572 T = cast<ArrayType>(T)->getElementType().getTypePtr();
4573 break;
4574 default:
4575 return Owned(E);
4576 }
4577 }
4578
4579 // That should be enough to guarantee that this type is complete, if we're
4580 // not processing a decltype expression.
4581 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4582 if (RD->isInvalidDecl() || RD->isDependentContext())
4583 return Owned(E);
4584
4585 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
4586 CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD);
4587
4588 if (Destructor) {
4589 MarkFunctionReferenced(E->getExprLoc(), Destructor);
4590 CheckDestructorAccess(E->getExprLoc(), Destructor,
4591 PDiag(diag::err_access_dtor_temp)
4592 << E->getType());
4593 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
4594
4595 // If destructor is trivial, we can avoid the extra copy.
4596 if (Destructor->isTrivial())
4597 return Owned(E);
4598
4599 // We need a cleanup, but we don't need to remember the temporary.
4600 ExprNeedsCleanups = true;
4601 }
4602
4603 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4604 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
4605
4606 if (IsDecltype)
4607 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
4608
4609 return Owned(Bind);
4610 }
4611
4612 ExprResult
MaybeCreateExprWithCleanups(ExprResult SubExpr)4613 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
4614 if (SubExpr.isInvalid())
4615 return ExprError();
4616
4617 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
4618 }
4619
MaybeCreateExprWithCleanups(Expr * SubExpr)4620 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4621 assert(SubExpr && "sub expression can't be null!");
4622
4623 CleanupVarDeclMarking();
4624
4625 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4626 assert(ExprCleanupObjects.size() >= FirstCleanup);
4627 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4628 if (!ExprNeedsCleanups)
4629 return SubExpr;
4630
4631 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4632 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4633 ExprCleanupObjects.size() - FirstCleanup);
4634
4635 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4636 DiscardCleanupsInEvaluationContext();
4637
4638 return E;
4639 }
4640
MaybeCreateStmtWithCleanups(Stmt * SubStmt)4641 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
4642 assert(SubStmt && "sub statement can't be null!");
4643
4644 CleanupVarDeclMarking();
4645
4646 if (!ExprNeedsCleanups)
4647 return SubStmt;
4648
4649 // FIXME: In order to attach the temporaries, wrap the statement into
4650 // a StmtExpr; currently this is only used for asm statements.
4651 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4652 // a new AsmStmtWithTemporaries.
4653 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4654 SourceLocation(),
4655 SourceLocation());
4656 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4657 SourceLocation());
4658 return MaybeCreateExprWithCleanups(E);
4659 }
4660
4661 /// Process the expression contained within a decltype. For such expressions,
4662 /// certain semantic checks on temporaries are delayed until this point, and
4663 /// are omitted for the 'topmost' call in the decltype expression. If the
4664 /// topmost call bound a temporary, strip that temporary off the expression.
ActOnDecltypeExpression(Expr * E)4665 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
4666 ExpressionEvaluationContextRecord &Rec = ExprEvalContexts.back();
4667 assert(Rec.IsDecltype && "not in a decltype expression");
4668
4669 // C++11 [expr.call]p11:
4670 // If a function call is a prvalue of object type,
4671 // -- if the function call is either
4672 // -- the operand of a decltype-specifier, or
4673 // -- the right operand of a comma operator that is the operand of a
4674 // decltype-specifier,
4675 // a temporary object is not introduced for the prvalue.
4676
4677 // Recursively rebuild ParenExprs and comma expressions to strip out the
4678 // outermost CXXBindTemporaryExpr, if any.
4679 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4680 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
4681 if (SubExpr.isInvalid())
4682 return ExprError();
4683 if (SubExpr.get() == PE->getSubExpr())
4684 return Owned(E);
4685 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take());
4686 }
4687 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4688 if (BO->getOpcode() == BO_Comma) {
4689 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
4690 if (RHS.isInvalid())
4691 return ExprError();
4692 if (RHS.get() == BO->getRHS())
4693 return Owned(E);
4694 return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(),
4695 BO_Comma, BO->getType(),
4696 BO->getValueKind(),
4697 BO->getObjectKind(),
4698 BO->getOperatorLoc()));
4699 }
4700 }
4701
4702 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
4703 if (TopBind)
4704 E = TopBind->getSubExpr();
4705
4706 // Disable the special decltype handling now.
4707 Rec.IsDecltype = false;
4708
4709 // Perform the semantic checks we delayed until this point.
4710 CallExpr *TopCall = dyn_cast<CallExpr>(E);
4711 for (unsigned I = 0, N = Rec.DelayedDecltypeCalls.size(); I != N; ++I) {
4712 CallExpr *Call = Rec.DelayedDecltypeCalls[I];
4713 if (Call == TopCall)
4714 continue;
4715
4716 if (CheckCallReturnType(Call->getCallReturnType(),
4717 Call->getLocStart(),
4718 Call, Call->getDirectCallee()))
4719 return ExprError();
4720 }
4721
4722 // Now all relevant types are complete, check the destructors are accessible
4723 // and non-deleted, and annotate them on the temporaries.
4724 for (unsigned I = 0, N = Rec.DelayedDecltypeBinds.size(); I != N; ++I) {
4725 CXXBindTemporaryExpr *Bind = Rec.DelayedDecltypeBinds[I];
4726 if (Bind == TopBind)
4727 continue;
4728
4729 CXXTemporary *Temp = Bind->getTemporary();
4730
4731 CXXRecordDecl *RD =
4732 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
4733 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4734 Temp->setDestructor(Destructor);
4735
4736 MarkFunctionReferenced(E->getExprLoc(), Destructor);
4737 CheckDestructorAccess(E->getExprLoc(), Destructor,
4738 PDiag(diag::err_access_dtor_temp)
4739 << E->getType());
4740 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
4741
4742 // We need a cleanup, but we don't need to remember the temporary.
4743 ExprNeedsCleanups = true;
4744 }
4745
4746 // Possibly strip off the top CXXBindTemporaryExpr.
4747 return Owned(E);
4748 }
4749
4750 ExprResult
ActOnStartCXXMemberReference(Scope * S,Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,ParsedType & ObjectType,bool & MayBePseudoDestructor)4751 Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
4752 tok::TokenKind OpKind, ParsedType &ObjectType,
4753 bool &MayBePseudoDestructor) {
4754 // Since this might be a postfix expression, get rid of ParenListExprs.
4755 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
4756 if (Result.isInvalid()) return ExprError();
4757 Base = Result.get();
4758
4759 Result = CheckPlaceholderExpr(Base);
4760 if (Result.isInvalid()) return ExprError();
4761 Base = Result.take();
4762
4763 QualType BaseType = Base->getType();
4764 MayBePseudoDestructor = false;
4765 if (BaseType->isDependentType()) {
4766 // If we have a pointer to a dependent type and are using the -> operator,
4767 // the object type is the type that the pointer points to. We might still
4768 // have enough information about that type to do something useful.
4769 if (OpKind == tok::arrow)
4770 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4771 BaseType = Ptr->getPointeeType();
4772
4773 ObjectType = ParsedType::make(BaseType);
4774 MayBePseudoDestructor = true;
4775 return Owned(Base);
4776 }
4777
4778 // C++ [over.match.oper]p8:
4779 // [...] When operator->returns, the operator-> is applied to the value
4780 // returned, with the original second operand.
4781 if (OpKind == tok::arrow) {
4782 // The set of types we've considered so far.
4783 llvm::SmallPtrSet<CanQualType,8> CTypes;
4784 SmallVector<SourceLocation, 8> Locations;
4785 CTypes.insert(Context.getCanonicalType(BaseType));
4786
4787 while (BaseType->isRecordType()) {
4788 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4789 if (Result.isInvalid())
4790 return ExprError();
4791 Base = Result.get();
4792 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
4793 Locations.push_back(OpCall->getDirectCallee()->getLocation());
4794 BaseType = Base->getType();
4795 CanQualType CBaseType = Context.getCanonicalType(BaseType);
4796 if (!CTypes.insert(CBaseType)) {
4797 Diag(OpLoc, diag::err_operator_arrow_circular);
4798 for (unsigned i = 0; i < Locations.size(); i++)
4799 Diag(Locations[i], diag::note_declared_at);
4800 return ExprError();
4801 }
4802 }
4803
4804 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
4805 BaseType = BaseType->getPointeeType();
4806 }
4807
4808 // Objective-C properties allow "." access on Objective-C pointer types,
4809 // so adjust the base type to the object type itself.
4810 if (BaseType->isObjCObjectPointerType())
4811 BaseType = BaseType->getPointeeType();
4812
4813 // C++ [basic.lookup.classref]p2:
4814 // [...] If the type of the object expression is of pointer to scalar
4815 // type, the unqualified-id is looked up in the context of the complete
4816 // postfix-expression.
4817 //
4818 // This also indicates that we could be parsing a pseudo-destructor-name.
4819 // Note that Objective-C class and object types can be pseudo-destructor
4820 // expressions or normal member (ivar or property) access expressions.
4821 if (BaseType->isObjCObjectOrInterfaceType()) {
4822 MayBePseudoDestructor = true;
4823 } else if (!BaseType->isRecordType()) {
4824 ObjectType = ParsedType();
4825 MayBePseudoDestructor = true;
4826 return Owned(Base);
4827 }
4828
4829 // The object type must be complete (or dependent), or
4830 // C++11 [expr.prim.general]p3:
4831 // Unlike the object expression in other contexts, *this is not required to
4832 // be of complete type for purposes of class member access (5.2.5) outside
4833 // the member function body.
4834 if (!BaseType->isDependentType() &&
4835 !isThisOutsideMemberFunctionBody(BaseType) &&
4836 RequireCompleteType(OpLoc, BaseType,
4837 PDiag(diag::err_incomplete_member_access)))
4838 return ExprError();
4839
4840 // C++ [basic.lookup.classref]p2:
4841 // If the id-expression in a class member access (5.2.5) is an
4842 // unqualified-id, and the type of the object expression is of a class
4843 // type C (or of pointer to a class type C), the unqualified-id is looked
4844 // up in the scope of class C. [...]
4845 ObjectType = ParsedType::make(BaseType);
4846 return move(Base);
4847 }
4848
DiagnoseDtorReference(SourceLocation NameLoc,Expr * MemExpr)4849 ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
4850 Expr *MemExpr) {
4851 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
4852 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4853 << isa<CXXPseudoDestructorExpr>(MemExpr)
4854 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
4855
4856 return ActOnCallExpr(/*Scope*/ 0,
4857 MemExpr,
4858 /*LPLoc*/ ExpectedLParenLoc,
4859 MultiExprArg(),
4860 /*RPLoc*/ ExpectedLParenLoc);
4861 }
4862
CheckArrow(Sema & S,QualType & ObjectType,Expr * & Base,tok::TokenKind & OpKind,SourceLocation OpLoc)4863 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
4864 tok::TokenKind& OpKind, SourceLocation OpLoc) {
4865 if (Base->hasPlaceholderType()) {
4866 ExprResult result = S.CheckPlaceholderExpr(Base);
4867 if (result.isInvalid()) return true;
4868 Base = result.take();
4869 }
4870 ObjectType = Base->getType();
4871
4872 // C++ [expr.pseudo]p2:
4873 // The left-hand side of the dot operator shall be of scalar type. The
4874 // left-hand side of the arrow operator shall be of pointer to scalar type.
4875 // This scalar type is the object type.
4876 // Note that this is rather different from the normal handling for the
4877 // arrow operator.
4878 if (OpKind == tok::arrow) {
4879 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4880 ObjectType = Ptr->getPointeeType();
4881 } else if (!Base->isTypeDependent()) {
4882 // The user wrote "p->" when she probably meant "p."; fix it.
4883 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4884 << ObjectType << true
4885 << FixItHint::CreateReplacement(OpLoc, ".");
4886 if (S.isSFINAEContext())
4887 return true;
4888
4889 OpKind = tok::period;
4890 }
4891 }
4892
4893 return false;
4894 }
4895
BuildPseudoDestructorExpr(Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,const CXXScopeSpec & SS,TypeSourceInfo * ScopeTypeInfo,SourceLocation CCLoc,SourceLocation TildeLoc,PseudoDestructorTypeStorage Destructed,bool HasTrailingLParen)4896 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
4897 SourceLocation OpLoc,
4898 tok::TokenKind OpKind,
4899 const CXXScopeSpec &SS,
4900 TypeSourceInfo *ScopeTypeInfo,
4901 SourceLocation CCLoc,
4902 SourceLocation TildeLoc,
4903 PseudoDestructorTypeStorage Destructed,
4904 bool HasTrailingLParen) {
4905 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
4906
4907 QualType ObjectType;
4908 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4909 return ExprError();
4910
4911 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
4912 if (getLangOpts().MicrosoftMode && ObjectType->isVoidType())
4913 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
4914 else
4915 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
4916 << ObjectType << Base->getSourceRange();
4917 return ExprError();
4918 }
4919
4920 // C++ [expr.pseudo]p2:
4921 // [...] The cv-unqualified versions of the object type and of the type
4922 // designated by the pseudo-destructor-name shall be the same type.
4923 if (DestructedTypeInfo) {
4924 QualType DestructedType = DestructedTypeInfo->getType();
4925 SourceLocation DestructedTypeStart
4926 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
4927 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4928 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4929 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4930 << ObjectType << DestructedType << Base->getSourceRange()
4931 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4932
4933 // Recover by setting the destructed type to the object type.
4934 DestructedType = ObjectType;
4935 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4936 DestructedTypeStart);
4937 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4938 } else if (DestructedType.getObjCLifetime() !=
4939 ObjectType.getObjCLifetime()) {
4940
4941 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4942 // Okay: just pretend that the user provided the correctly-qualified
4943 // type.
4944 } else {
4945 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4946 << ObjectType << DestructedType << Base->getSourceRange()
4947 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4948 }
4949
4950 // Recover by setting the destructed type to the object type.
4951 DestructedType = ObjectType;
4952 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4953 DestructedTypeStart);
4954 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4955 }
4956 }
4957 }
4958
4959 // C++ [expr.pseudo]p2:
4960 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4961 // form
4962 //
4963 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
4964 //
4965 // shall designate the same scalar type.
4966 if (ScopeTypeInfo) {
4967 QualType ScopeType = ScopeTypeInfo->getType();
4968 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
4969 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
4970
4971 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
4972 diag::err_pseudo_dtor_type_mismatch)
4973 << ObjectType << ScopeType << Base->getSourceRange()
4974 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
4975
4976 ScopeType = QualType();
4977 ScopeTypeInfo = 0;
4978 }
4979 }
4980
4981 Expr *Result
4982 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4983 OpKind == tok::arrow, OpLoc,
4984 SS.getWithLocInContext(Context),
4985 ScopeTypeInfo,
4986 CCLoc,
4987 TildeLoc,
4988 Destructed);
4989
4990 if (HasTrailingLParen)
4991 return Owned(Result);
4992
4993 return DiagnoseDtorReference(Destructed.getLocation(), Result);
4994 }
4995
ActOnPseudoDestructorExpr(Scope * S,Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,CXXScopeSpec & SS,UnqualifiedId & FirstTypeName,SourceLocation CCLoc,SourceLocation TildeLoc,UnqualifiedId & SecondTypeName,bool HasTrailingLParen)4996 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4997 SourceLocation OpLoc,
4998 tok::TokenKind OpKind,
4999 CXXScopeSpec &SS,
5000 UnqualifiedId &FirstTypeName,
5001 SourceLocation CCLoc,
5002 SourceLocation TildeLoc,
5003 UnqualifiedId &SecondTypeName,
5004 bool HasTrailingLParen) {
5005 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5006 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5007 "Invalid first type name in pseudo-destructor");
5008 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5009 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5010 "Invalid second type name in pseudo-destructor");
5011
5012 QualType ObjectType;
5013 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5014 return ExprError();
5015
5016 // Compute the object type that we should use for name lookup purposes. Only
5017 // record types and dependent types matter.
5018 ParsedType ObjectTypePtrForLookup;
5019 if (!SS.isSet()) {
5020 if (ObjectType->isRecordType())
5021 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
5022 else if (ObjectType->isDependentType())
5023 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
5024 }
5025
5026 // Convert the name of the type being destructed (following the ~) into a
5027 // type (with source-location information).
5028 QualType DestructedType;
5029 TypeSourceInfo *DestructedTypeInfo = 0;
5030 PseudoDestructorTypeStorage Destructed;
5031 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
5032 ParsedType T = getTypeName(*SecondTypeName.Identifier,
5033 SecondTypeName.StartLocation,
5034 S, &SS, true, false, ObjectTypePtrForLookup);
5035 if (!T &&
5036 ((SS.isSet() && !computeDeclContext(SS, false)) ||
5037 (!SS.isSet() && ObjectType->isDependentType()))) {
5038 // The name of the type being destroyed is a dependent name, and we
5039 // couldn't find anything useful in scope. Just store the identifier and
5040 // it's location, and we'll perform (qualified) name lookup again at
5041 // template instantiation time.
5042 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
5043 SecondTypeName.StartLocation);
5044 } else if (!T) {
5045 Diag(SecondTypeName.StartLocation,
5046 diag::err_pseudo_dtor_destructor_non_type)
5047 << SecondTypeName.Identifier << ObjectType;
5048 if (isSFINAEContext())
5049 return ExprError();
5050
5051 // Recover by assuming we had the right type all along.
5052 DestructedType = ObjectType;
5053 } else
5054 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
5055 } else {
5056 // Resolve the template-id to a type.
5057 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
5058 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5059 TemplateId->getTemplateArgs(),
5060 TemplateId->NumArgs);
5061 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
5062 TemplateId->TemplateKWLoc,
5063 TemplateId->Template,
5064 TemplateId->TemplateNameLoc,
5065 TemplateId->LAngleLoc,
5066 TemplateArgsPtr,
5067 TemplateId->RAngleLoc);
5068 if (T.isInvalid() || !T.get()) {
5069 // Recover by assuming we had the right type all along.
5070 DestructedType = ObjectType;
5071 } else
5072 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
5073 }
5074
5075 // If we've performed some kind of recovery, (re-)build the type source
5076 // information.
5077 if (!DestructedType.isNull()) {
5078 if (!DestructedTypeInfo)
5079 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
5080 SecondTypeName.StartLocation);
5081 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5082 }
5083
5084 // Convert the name of the scope type (the type prior to '::') into a type.
5085 TypeSourceInfo *ScopeTypeInfo = 0;
5086 QualType ScopeType;
5087 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5088 FirstTypeName.Identifier) {
5089 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
5090 ParsedType T = getTypeName(*FirstTypeName.Identifier,
5091 FirstTypeName.StartLocation,
5092 S, &SS, true, false, ObjectTypePtrForLookup);
5093 if (!T) {
5094 Diag(FirstTypeName.StartLocation,
5095 diag::err_pseudo_dtor_destructor_non_type)
5096 << FirstTypeName.Identifier << ObjectType;
5097
5098 if (isSFINAEContext())
5099 return ExprError();
5100
5101 // Just drop this type. It's unnecessary anyway.
5102 ScopeType = QualType();
5103 } else
5104 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
5105 } else {
5106 // Resolve the template-id to a type.
5107 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
5108 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5109 TemplateId->getTemplateArgs(),
5110 TemplateId->NumArgs);
5111 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
5112 TemplateId->TemplateKWLoc,
5113 TemplateId->Template,
5114 TemplateId->TemplateNameLoc,
5115 TemplateId->LAngleLoc,
5116 TemplateArgsPtr,
5117 TemplateId->RAngleLoc);
5118 if (T.isInvalid() || !T.get()) {
5119 // Recover by dropping this type.
5120 ScopeType = QualType();
5121 } else
5122 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
5123 }
5124 }
5125
5126 if (!ScopeType.isNull() && !ScopeTypeInfo)
5127 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5128 FirstTypeName.StartLocation);
5129
5130
5131 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
5132 ScopeTypeInfo, CCLoc, TildeLoc,
5133 Destructed, HasTrailingLParen);
5134 }
5135
ActOnPseudoDestructorExpr(Scope * S,Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,SourceLocation TildeLoc,const DeclSpec & DS,bool HasTrailingLParen)5136 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5137 SourceLocation OpLoc,
5138 tok::TokenKind OpKind,
5139 SourceLocation TildeLoc,
5140 const DeclSpec& DS,
5141 bool HasTrailingLParen) {
5142 QualType ObjectType;
5143 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5144 return ExprError();
5145
5146 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5147
5148 TypeLocBuilder TLB;
5149 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5150 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5151 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5152 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5153
5154 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
5155 0, SourceLocation(), TildeLoc,
5156 Destructed, HasTrailingLParen);
5157 }
5158
BuildCXXMemberCallExpr(Expr * E,NamedDecl * FoundDecl,CXXConversionDecl * Method,bool HadMultipleCandidates)5159 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
5160 CXXConversionDecl *Method,
5161 bool HadMultipleCandidates) {
5162 if (Method->getParent()->isLambda() &&
5163 Method->getConversionType()->isBlockPointerType()) {
5164 // This is a lambda coversion to block pointer; check if the argument
5165 // is a LambdaExpr.
5166 Expr *SubE = E;
5167 CastExpr *CE = dyn_cast<CastExpr>(SubE);
5168 if (CE && CE->getCastKind() == CK_NoOp)
5169 SubE = CE->getSubExpr();
5170 SubE = SubE->IgnoreParens();
5171 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
5172 SubE = BE->getSubExpr();
5173 if (isa<LambdaExpr>(SubE)) {
5174 // For the conversion to block pointer on a lambda expression, we
5175 // construct a special BlockLiteral instead; this doesn't really make
5176 // a difference in ARC, but outside of ARC the resulting block literal
5177 // follows the normal lifetime rules for block literals instead of being
5178 // autoreleased.
5179 DiagnosticErrorTrap Trap(Diags);
5180 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
5181 E->getExprLoc(),
5182 Method, E);
5183 if (Exp.isInvalid())
5184 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
5185 return Exp;
5186 }
5187 }
5188
5189
5190 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
5191 FoundDecl, Method);
5192 if (Exp.isInvalid())
5193 return true;
5194
5195 MemberExpr *ME =
5196 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
5197 SourceLocation(), Context.BoundMemberTy,
5198 VK_RValue, OK_Ordinary);
5199 if (HadMultipleCandidates)
5200 ME->setHadMultipleCandidates(true);
5201
5202 QualType ResultType = Method->getResultType();
5203 ExprValueKind VK = Expr::getValueKindForType(ResultType);
5204 ResultType = ResultType.getNonLValueExprType(Context);
5205
5206 MarkFunctionReferenced(Exp.get()->getLocStart(), Method);
5207 CXXMemberCallExpr *CE =
5208 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
5209 Exp.get()->getLocEnd());
5210 return CE;
5211 }
5212
BuildCXXNoexceptExpr(SourceLocation KeyLoc,Expr * Operand,SourceLocation RParen)5213 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5214 SourceLocation RParen) {
5215 CanThrowResult CanThrow = canThrow(Operand);
5216 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
5217 CanThrow, KeyLoc, RParen));
5218 }
5219
ActOnNoexceptExpr(SourceLocation KeyLoc,SourceLocation,Expr * Operand,SourceLocation RParen)5220 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5221 Expr *Operand, SourceLocation RParen) {
5222 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
5223 }
5224
5225 /// Perform the conversions required for an expression used in a
5226 /// context that ignores the result.
IgnoredValueConversions(Expr * E)5227 ExprResult Sema::IgnoredValueConversions(Expr *E) {
5228 if (E->hasPlaceholderType()) {
5229 ExprResult result = CheckPlaceholderExpr(E);
5230 if (result.isInvalid()) return Owned(E);
5231 E = result.take();
5232 }
5233
5234 // C99 6.3.2.1:
5235 // [Except in specific positions,] an lvalue that does not have
5236 // array type is converted to the value stored in the
5237 // designated object (and is no longer an lvalue).
5238 if (E->isRValue()) {
5239 // In C, function designators (i.e. expressions of function type)
5240 // are r-values, but we still want to do function-to-pointer decay
5241 // on them. This is both technically correct and convenient for
5242 // some clients.
5243 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
5244 return DefaultFunctionArrayConversion(E);
5245
5246 return Owned(E);
5247 }
5248
5249 // Otherwise, this rule does not apply in C++, at least not for the moment.
5250 if (getLangOpts().CPlusPlus) return Owned(E);
5251
5252 // GCC seems to also exclude expressions of incomplete enum type.
5253 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5254 if (!T->getDecl()->isComplete()) {
5255 // FIXME: stupid workaround for a codegen bug!
5256 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
5257 return Owned(E);
5258 }
5259 }
5260
5261 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5262 if (Res.isInvalid())
5263 return Owned(E);
5264 E = Res.take();
5265
5266 if (!E->getType()->isVoidType())
5267 RequireCompleteType(E->getExprLoc(), E->getType(),
5268 diag::err_incomplete_type);
5269 return Owned(E);
5270 }
5271
ActOnFinishFullExpr(Expr * FE)5272 ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
5273 ExprResult FullExpr = Owned(FE);
5274
5275 if (!FullExpr.get())
5276 return ExprError();
5277
5278 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
5279 return ExprError();
5280
5281 // Top-level message sends default to 'id' when we're in a debugger.
5282 if (getLangOpts().DebuggerCastResultToId &&
5283 FullExpr.get()->getType() == Context.UnknownAnyTy &&
5284 isa<ObjCMessageExpr>(FullExpr.get())) {
5285 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
5286 if (FullExpr.isInvalid())
5287 return ExprError();
5288 }
5289
5290 FullExpr = CheckPlaceholderExpr(FullExpr.take());
5291 if (FullExpr.isInvalid())
5292 return ExprError();
5293
5294 FullExpr = IgnoredValueConversions(FullExpr.take());
5295 if (FullExpr.isInvalid())
5296 return ExprError();
5297
5298 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
5299 return MaybeCreateExprWithCleanups(FullExpr);
5300 }
5301
ActOnFinishFullStmt(Stmt * FullStmt)5302 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
5303 if (!FullStmt) return StmtError();
5304
5305 return MaybeCreateStmtWithCleanups(FullStmt);
5306 }
5307
5308 Sema::IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope * S,CXXScopeSpec & SS,const DeclarationNameInfo & TargetNameInfo)5309 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
5310 CXXScopeSpec &SS,
5311 const DeclarationNameInfo &TargetNameInfo) {
5312 DeclarationName TargetName = TargetNameInfo.getName();
5313 if (!TargetName)
5314 return IER_DoesNotExist;
5315
5316 // If the name itself is dependent, then the result is dependent.
5317 if (TargetName.isDependentName())
5318 return IER_Dependent;
5319
5320 // Do the redeclaration lookup in the current scope.
5321 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
5322 Sema::NotForRedeclaration);
5323 LookupParsedName(R, S, &SS);
5324 R.suppressDiagnostics();
5325
5326 switch (R.getResultKind()) {
5327 case LookupResult::Found:
5328 case LookupResult::FoundOverloaded:
5329 case LookupResult::FoundUnresolvedValue:
5330 case LookupResult::Ambiguous:
5331 return IER_Exists;
5332
5333 case LookupResult::NotFound:
5334 return IER_DoesNotExist;
5335
5336 case LookupResult::NotFoundInCurrentInstantiation:
5337 return IER_Dependent;
5338 }
5339
5340 llvm_unreachable("Invalid LookupResult Kind!");
5341 }
5342
5343 Sema::IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope * S,SourceLocation KeywordLoc,bool IsIfExists,CXXScopeSpec & SS,UnqualifiedId & Name)5344 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5345 bool IsIfExists, CXXScopeSpec &SS,
5346 UnqualifiedId &Name) {
5347 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5348
5349 // Check for unexpanded parameter packs.
5350 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5351 collectUnexpandedParameterPacks(SS, Unexpanded);
5352 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
5353 if (!Unexpanded.empty()) {
5354 DiagnoseUnexpandedParameterPacks(KeywordLoc,
5355 IsIfExists? UPPC_IfExists
5356 : UPPC_IfNotExists,
5357 Unexpanded);
5358 return IER_Error;
5359 }
5360
5361 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
5362 }
5363