clang 17.0.0git
SemaExpr.cpp
Go to the documentation of this file.
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TreeTransform.h"
14#include "UsedDeclVisitor.h"
17#include "clang/AST/ASTLambda.h"
20#include "clang/AST/DeclObjC.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
41#include "clang/Sema/DeclSpec.h"
46#include "clang/Sema/Lookup.h"
47#include "clang/Sema/Overload.h"
49#include "clang/Sema/Scope.h"
53#include "clang/Sema/Template.h"
54#include "llvm/ADT/STLExtras.h"
55#include "llvm/ADT/StringExtras.h"
56#include "llvm/Support/Casting.h"
57#include "llvm/Support/ConvertUTF.h"
58#include "llvm/Support/SaveAndRestore.h"
59#include "llvm/Support/TypeSize.h"
60#include <optional>
61
62using namespace clang;
63using namespace sema;
64
65/// Determine whether the use of this declaration is valid, without
66/// emitting diagnostics.
67bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
68 // See if this is an auto-typed variable whose initializer we are parsing.
69 if (ParsingInitForAutoVars.count(D))
70 return false;
71
72 // See if this is a deleted function.
73 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
74 if (FD->isDeleted())
75 return false;
76
77 // If the function has a deduced return type, and we can't deduce it,
78 // then we can't use it either.
79 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
80 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
81 return false;
82
83 // See if this is an aligned allocation/deallocation function that is
84 // unavailable.
85 if (TreatUnavailableAsInvalid &&
87 return false;
88 }
89
90 // See if this function is unavailable.
91 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
92 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
93 return false;
94
95 if (isa<UnresolvedUsingIfExistsDecl>(D))
96 return false;
97
98 return true;
99}
100
102 // Warn if this is used but marked unused.
103 if (const auto *A = D->getAttr<UnusedAttr>()) {
104 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
105 // should diagnose them.
106 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
107 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
108 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
109 if (DC && !DC->hasAttr<UnusedAttr>())
110 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
111 }
112 }
113}
114
115/// Emit a note explaining that this function is deleted.
117 assert(Decl && Decl->isDeleted());
118
119 if (Decl->isDefaulted()) {
120 // If the method was explicitly defaulted, point at that declaration.
121 if (!Decl->isImplicit())
122 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
123
124 // Try to diagnose why this special member function was implicitly
125 // deleted. This might fail, if that reason no longer applies.
127 return;
128 }
129
130 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
131 if (Ctor && Ctor->isInheritingConstructor())
133
134 Diag(Decl->getLocation(), diag::note_availability_specified_here)
135 << Decl << 1;
136}
137
138/// Determine whether a FunctionDecl was ever declared with an
139/// explicit storage class.
141 for (auto *I : D->redecls()) {
142 if (I->getStorageClass() != SC_None)
143 return true;
144 }
145 return false;
146}
147
148/// Check whether we're in an extern inline function and referring to a
149/// variable or function with internal linkage (C11 6.7.4p3).
150///
151/// This is only a warning because we used to silently accept this code, but
152/// in many cases it will not behave correctly. This is not enabled in C++ mode
153/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
154/// and so while there may still be user mistakes, most of the time we can't
155/// prove that there are errors.
157 const NamedDecl *D,
158 SourceLocation Loc) {
159 // This is disabled under C++; there are too many ways for this to fire in
160 // contexts where the warning is a false positive, or where it is technically
161 // correct but benign.
162 if (S.getLangOpts().CPlusPlus)
163 return;
164
165 // Check if this is an inlined function or method.
166 FunctionDecl *Current = S.getCurFunctionDecl();
167 if (!Current)
168 return;
169 if (!Current->isInlined())
170 return;
171 if (!Current->isExternallyVisible())
172 return;
173
174 // Check if the decl has internal linkage.
176 return;
177
178 // Downgrade from ExtWarn to Extension if
179 // (1) the supposedly external inline function is in the main file,
180 // and probably won't be included anywhere else.
181 // (2) the thing we're referencing is a pure function.
182 // (3) the thing we're referencing is another inline function.
183 // This last can give us false negatives, but it's better than warning on
184 // wrappers for simple C library functions.
185 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
186 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
187 if (!DowngradeWarning && UsedFn)
188 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
189
190 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
191 : diag::ext_internal_in_extern_inline)
192 << /*IsVar=*/!UsedFn << D;
193
195
196 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
197 << D;
198}
199
201 const FunctionDecl *First = Cur->getFirstDecl();
202
203 // Suggest "static" on the function, if possible.
205 SourceLocation DeclBegin = First->getSourceRange().getBegin();
206 Diag(DeclBegin, diag::note_convert_inline_to_static)
207 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
208 }
209}
210
211/// Determine whether the use of this declaration is valid, and
212/// emit any corresponding diagnostics.
213///
214/// This routine diagnoses various problems with referencing
215/// declarations that can occur when using a declaration. For example,
216/// it might warn if a deprecated or unavailable declaration is being
217/// used, or produce an error (and return true) if a C++0x deleted
218/// function is being used.
219///
220/// \returns true if there was an error (this declaration cannot be
221/// referenced), false otherwise.
222///
224 const ObjCInterfaceDecl *UnknownObjCClass,
225 bool ObjCPropertyAccess,
226 bool AvoidPartialAvailabilityChecks,
227 ObjCInterfaceDecl *ClassReceiver,
228 bool SkipTrailingRequiresClause) {
229 SourceLocation Loc = Locs.front();
230 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
231 // If there were any diagnostics suppressed by template argument deduction,
232 // emit them now.
233 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
234 if (Pos != SuppressedDiagnostics.end()) {
235 for (const PartialDiagnosticAt &Suppressed : Pos->second)
236 Diag(Suppressed.first, Suppressed.second);
237
238 // Clear out the list of suppressed diagnostics, so that we don't emit
239 // them again for this specialization. However, we don't obsolete this
240 // entry from the table, because we want to avoid ever emitting these
241 // diagnostics again.
242 Pos->second.clear();
243 }
244
245 // C++ [basic.start.main]p3:
246 // The function 'main' shall not be used within a program.
247 if (cast<FunctionDecl>(D)->isMain())
248 Diag(Loc, diag::ext_main_used);
249
250 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
251 }
252
253 // See if this is an auto-typed variable whose initializer we are parsing.
254 if (ParsingInitForAutoVars.count(D)) {
255 if (isa<BindingDecl>(D)) {
256 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
257 << D->getDeclName();
258 } else {
259 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
260 << D->getDeclName() << cast<VarDecl>(D)->getType();
261 }
262 return true;
263 }
264
265 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
266 // See if this is a deleted function.
267 if (FD->isDeleted()) {
268 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
269 if (Ctor && Ctor->isInheritingConstructor())
270 Diag(Loc, diag::err_deleted_inherited_ctor_use)
271 << Ctor->getParent()
272 << Ctor->getInheritedConstructor().getConstructor()->getParent();
273 else
274 Diag(Loc, diag::err_deleted_function_use);
276 return true;
277 }
278
279 // [expr.prim.id]p4
280 // A program that refers explicitly or implicitly to a function with a
281 // trailing requires-clause whose constraint-expression is not satisfied,
282 // other than to declare it, is ill-formed. [...]
283 //
284 // See if this is a function with constraints that need to be satisfied.
285 // Check this before deducing the return type, as it might instantiate the
286 // definition.
287 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
288 ConstraintSatisfaction Satisfaction;
289 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
290 /*ForOverloadResolution*/ true))
291 // A diagnostic will have already been generated (non-constant
292 // constraint expression, for example)
293 return true;
294 if (!Satisfaction.IsSatisfied) {
295 Diag(Loc,
296 diag::err_reference_to_function_with_unsatisfied_constraints)
297 << D;
298 DiagnoseUnsatisfiedConstraint(Satisfaction);
299 return true;
300 }
301 }
302
303 // If the function has a deduced return type, and we can't deduce it,
304 // then we can't use it either.
305 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
306 DeduceReturnType(FD, Loc))
307 return true;
308
309 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
310 return true;
311
312 }
313
314 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
315 // Lambdas are only default-constructible or assignable in C++2a onwards.
316 if (MD->getParent()->isLambda() &&
317 ((isa<CXXConstructorDecl>(MD) &&
318 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
319 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
320 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
321 << !isa<CXXConstructorDecl>(MD);
322 }
323 }
324
325 auto getReferencedObjCProp = [](const NamedDecl *D) ->
326 const ObjCPropertyDecl * {
327 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
328 return MD->findPropertyDecl();
329 return nullptr;
330 };
331 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
332 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
333 return true;
334 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
335 return true;
336 }
337
338 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
339 // Only the variables omp_in and omp_out are allowed in the combiner.
340 // Only the variables omp_priv and omp_orig are allowed in the
341 // initializer-clause.
342 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
343 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
344 isa<VarDecl>(D)) {
345 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
347 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348 return true;
349 }
350
351 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
352 // List-items in map clauses on this construct may only refer to the declared
353 // variable var and entities that could be referenced by a procedure defined
354 // at the same location.
355 // [OpenMP 5.2] Also allow iterator declared variables.
356 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
357 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
358 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
360 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
361 return true;
362 }
363
364 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
365 Diag(Loc, diag::err_use_of_empty_using_if_exists);
366 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
367 return true;
368 }
369
370 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
371 AvoidPartialAvailabilityChecks, ClassReceiver);
372
373 DiagnoseUnusedOfDecl(*this, D, Loc);
374
376
377 if (auto *VD = dyn_cast<ValueDecl>(D))
378 checkTypeSupport(VD->getType(), Loc, VD);
379
380 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
382 if (const auto *VD = dyn_cast<VarDecl>(D))
383 if (VD->getTLSKind() != VarDecl::TLS_None)
384 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
385 }
386
387 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
389 // C++ [expr.prim.req.nested] p3
390 // A local parameter shall only appear as an unevaluated operand
391 // (Clause 8) within the constraint-expression.
392 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
393 << D;
394 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
395 return true;
396 }
397
398 return false;
399}
400
401/// DiagnoseSentinelCalls - This routine checks whether a call or
402/// message-send is to a declaration with the sentinel attribute, and
403/// if so, it checks that the requirements of the sentinel are
404/// satisfied.
406 ArrayRef<Expr *> Args) {
407 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
408 if (!attr)
409 return;
410
411 // The number of formal parameters of the declaration.
412 unsigned numFormalParams;
413
414 // The kind of declaration. This is also an index into a %select in
415 // the diagnostic.
416 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
417
418 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
419 numFormalParams = MD->param_size();
420 calleeType = CT_Method;
421 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
422 numFormalParams = FD->param_size();
423 calleeType = CT_Function;
424 } else if (isa<VarDecl>(D)) {
425 QualType type = cast<ValueDecl>(D)->getType();
426 const FunctionType *fn = nullptr;
427 if (const PointerType *ptr = type->getAs<PointerType>()) {
428 fn = ptr->getPointeeType()->getAs<FunctionType>();
429 if (!fn) return;
430 calleeType = CT_Function;
431 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
432 fn = ptr->getPointeeType()->castAs<FunctionType>();
433 calleeType = CT_Block;
434 } else {
435 return;
436 }
437
438 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
439 numFormalParams = proto->getNumParams();
440 } else {
441 numFormalParams = 0;
442 }
443 } else {
444 return;
445 }
446
447 // "nullPos" is the number of formal parameters at the end which
448 // effectively count as part of the variadic arguments. This is
449 // useful if you would prefer to not have *any* formal parameters,
450 // but the language forces you to have at least one.
451 unsigned nullPos = attr->getNullPos();
452 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
453 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
454
455 // The number of arguments which should follow the sentinel.
456 unsigned numArgsAfterSentinel = attr->getSentinel();
457
458 // If there aren't enough arguments for all the formal parameters,
459 // the sentinel, and the args after the sentinel, complain.
460 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
461 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
462 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
463 return;
464 }
465
466 // Otherwise, find the sentinel expression.
467 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
468 if (!sentinelExpr) return;
469 if (sentinelExpr->isValueDependent()) return;
470 if (Context.isSentinelNullExpr(sentinelExpr)) return;
471
472 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
473 // or 'NULL' if those are actually defined in the context. Only use
474 // 'nil' for ObjC methods, where it's much more likely that the
475 // variadic arguments form a list of object pointers.
476 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
477 std::string NullValue;
478 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
479 NullValue = "nil";
480 else if (getLangOpts().CPlusPlus11)
481 NullValue = "nullptr";
482 else if (PP.isMacroDefined("NULL"))
483 NullValue = "NULL";
484 else
485 NullValue = "(void*) 0";
486
487 if (MissingNilLoc.isInvalid())
488 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
489 else
490 Diag(MissingNilLoc, diag::warn_missing_sentinel)
491 << int(calleeType)
492 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
493 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
494}
495
497 return E ? E->getSourceRange() : SourceRange();
498}
499
500//===----------------------------------------------------------------------===//
501// Standard Promotions and Conversions
502//===----------------------------------------------------------------------===//
503
504/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
506 // Handle any placeholder expressions which made it here.
507 if (E->hasPlaceholderType()) {
509 if (result.isInvalid()) return ExprError();
510 E = result.get();
511 }
512
513 QualType Ty = E->getType();
514 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
515
516 if (Ty->isFunctionType()) {
517 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
518 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
520 return ExprError();
521
523 CK_FunctionToPointerDecay).get();
524 } else if (Ty->isArrayType()) {
525 // In C90 mode, arrays only promote to pointers if the array expression is
526 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
527 // type 'array of type' is converted to an expression that has type 'pointer
528 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
529 // that has type 'array of type' ...". The relevant change is "an lvalue"
530 // (C90) to "an expression" (C99).
531 //
532 // C++ 4.2p1:
533 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
534 // T" can be converted to an rvalue of type "pointer to T".
535 //
536 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
538 CK_ArrayToPointerDecay);
539 if (Res.isInvalid())
540 return ExprError();
541 E = Res.get();
542 }
543 }
544 return E;
545}
546
548 // Check to see if we are dereferencing a null pointer. If so,
549 // and if not volatile-qualified, this is undefined behavior that the
550 // optimizer will delete, so warn about it. People sometimes try to use this
551 // to get a deterministic trap and are surprised by clang's behavior. This
552 // only handles the pattern "*null", which is a very syntactic check.
553 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
554 if (UO && UO->getOpcode() == UO_Deref &&
555 UO->getSubExpr()->getType()->isPointerType()) {
556 const LangAS AS =
557 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
558 if ((!isTargetAddressSpace(AS) ||
559 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
560 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
562 !UO->getType().isVolatileQualified()) {
563 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
564 S.PDiag(diag::warn_indirection_through_null)
565 << UO->getSubExpr()->getSourceRange());
566 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
567 S.PDiag(diag::note_indirection_through_null));
568 }
569 }
570}
571
572static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
573 SourceLocation AssignLoc,
574 const Expr* RHS) {
575 const ObjCIvarDecl *IV = OIRE->getDecl();
576 if (!IV)
577 return;
578
579 DeclarationName MemberName = IV->getDeclName();
581 if (!Member || !Member->isStr("isa"))
582 return;
583
584 const Expr *Base = OIRE->getBase();
585 QualType BaseType = Base->getType();
586 if (OIRE->isArrow())
587 BaseType = BaseType->getPointeeType();
588 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
589 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
590 ObjCInterfaceDecl *ClassDeclared = nullptr;
591 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
592 if (!ClassDeclared->getSuperClass()
593 && (*ClassDeclared->ivar_begin()) == IV) {
594 if (RHS) {
595 NamedDecl *ObjectSetClass =
597 &S.Context.Idents.get("object_setClass"),
599 if (ObjectSetClass) {
600 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
601 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
603 "object_setClass(")
605 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
606 << FixItHint::CreateInsertion(RHSLocEnd, ")");
607 }
608 else
609 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
610 } else {
611 NamedDecl *ObjectGetClass =
613 &S.Context.Idents.get("object_getClass"),
615 if (ObjectGetClass)
616 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
618 "object_getClass(")
620 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
621 else
622 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
623 }
624 S.Diag(IV->getLocation(), diag::note_ivar_decl);
625 }
626 }
627}
628
630 // Handle any placeholder expressions which made it here.
631 if (E->hasPlaceholderType()) {
633 if (result.isInvalid()) return ExprError();
634 E = result.get();
635 }
636
637 // C++ [conv.lval]p1:
638 // A glvalue of a non-function, non-array type T can be
639 // converted to a prvalue.
640 if (!E->isGLValue()) return E;
641
642 QualType T = E->getType();
643 assert(!T.isNull() && "r-value conversion on typeless expression?");
644
645 // lvalue-to-rvalue conversion cannot be applied to function or array types.
646 if (T->isFunctionType() || T->isArrayType())
647 return E;
648
649 // We don't want to throw lvalue-to-rvalue casts on top of
650 // expressions of certain types in C++.
651 if (getLangOpts().CPlusPlus &&
652 (E->getType() == Context.OverloadTy ||
653 T->isDependentType() ||
654 T->isRecordType()))
655 return E;
656
657 // The C standard is actually really unclear on this point, and
658 // DR106 tells us what the result should be but not why. It's
659 // generally best to say that void types just doesn't undergo
660 // lvalue-to-rvalue at all. Note that expressions of unqualified
661 // 'void' type are never l-values, but qualified void can be.
662 if (T->isVoidType())
663 return E;
664
665 // OpenCL usually rejects direct accesses to values of 'half' type.
666 if (getLangOpts().OpenCL &&
667 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
668 T->isHalfType()) {
669 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
670 << 0 << T;
671 return ExprError();
672 }
673
675 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
676 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
677 &Context.Idents.get("object_getClass"),
679 if (ObjectGetClass)
680 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
681 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
683 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
684 else
685 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
686 }
687 else if (const ObjCIvarRefExpr *OIRE =
688 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
689 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
690
691 // C++ [conv.lval]p1:
692 // [...] If T is a non-class type, the type of the prvalue is the
693 // cv-unqualified version of T. Otherwise, the type of the
694 // rvalue is T.
695 //
696 // C99 6.3.2.1p2:
697 // If the lvalue has qualified type, the value has the unqualified
698 // version of the type of the lvalue; otherwise, the value has the
699 // type of the lvalue.
700 if (T.hasQualifiers())
701 T = T.getUnqualifiedType();
702
703 // Under the MS ABI, lock down the inheritance model now.
704 if (T->isMemberPointerType() &&
706 (void)isCompleteType(E->getExprLoc(), T);
707
709 if (Res.isInvalid())
710 return Res;
711 E = Res.get();
712
713 // Loading a __weak object implicitly retains the value, so we need a cleanup to
714 // balance that.
717
720
721 // C++ [conv.lval]p3:
722 // If T is cv std::nullptr_t, the result is a null pointer constant.
723 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
724 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
726
727 // C11 6.3.2.1p2:
728 // ... if the lvalue has atomic type, the value has the non-atomic version
729 // of the type of the lvalue ...
730 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
731 T = Atomic->getValueType().getUnqualifiedType();
732 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
733 nullptr, VK_PRValue, FPOptionsOverride());
734 }
735
736 return Res;
737}
738
741 if (Res.isInvalid())
742 return ExprError();
743 Res = DefaultLvalueConversion(Res.get());
744 if (Res.isInvalid())
745 return ExprError();
746 return Res;
747}
748
749/// CallExprUnaryConversions - a special case of an unary conversion
750/// performed on a function designator of a call expression.
752 QualType Ty = E->getType();
753 ExprResult Res = E;
754 // Only do implicit cast for a function type, but not for a pointer
755 // to function type.
756 if (Ty->isFunctionType()) {
758 CK_FunctionToPointerDecay);
759 if (Res.isInvalid())
760 return ExprError();
761 }
762 Res = DefaultLvalueConversion(Res.get());
763 if (Res.isInvalid())
764 return ExprError();
765 return Res.get();
766}
767
768/// UsualUnaryConversions - Performs various conversions that are common to most
769/// operators (C99 6.3). The conversions of array and function types are
770/// sometimes suppressed. For example, the array->pointer conversion doesn't
771/// apply if the array is an argument to the sizeof or address (&) operators.
772/// In these instances, this routine should *not* be called.
774 // First, convert to an r-value.
776 if (Res.isInvalid())
777 return ExprError();
778 E = Res.get();
779
780 QualType Ty = E->getType();
781 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
782
783 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
784 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
785 (getLangOpts().getFPEvalMethod() !=
788 switch (EvalMethod) {
789 default:
790 llvm_unreachable("Unrecognized float evaluation method");
791 break;
793 llvm_unreachable("Float evaluation method should be set by now");
794 break;
797 // Widen the expression to double.
798 return Ty->isComplexType()
801 CK_FloatingComplexCast)
802 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
803 break;
806 // Widen the expression to long double.
807 return Ty->isComplexType()
810 CK_FloatingComplexCast)
812 CK_FloatingCast);
813 break;
814 }
815 }
816
817 // Half FP have to be promoted to float unless it is natively supported
818 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
819 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
820
821 // Try to perform integral promotions if the object has a theoretically
822 // promotable type.
824 // C99 6.3.1.1p2:
825 //
826 // The following may be used in an expression wherever an int or
827 // unsigned int may be used:
828 // - an object or expression with an integer type whose integer
829 // conversion rank is less than or equal to the rank of int
830 // and unsigned int.
831 // - A bit-field of type _Bool, int, signed int, or unsigned int.
832 //
833 // If an int can represent all values of the original type, the
834 // value is converted to an int; otherwise, it is converted to an
835 // unsigned int. These are called the integer promotions. All
836 // other types are unchanged by the integer promotions.
837
839 if (!PTy.isNull()) {
840 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
841 return E;
842 }
845 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
846 return E;
847 }
848 }
849 return E;
850}
851
852/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
853/// do not have a prototype. Arguments that have type float or __fp16
854/// are promoted to double. All other argument types are converted by
855/// UsualUnaryConversions().
857 QualType Ty = E->getType();
858 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
859
861 if (Res.isInvalid())
862 return ExprError();
863 E = Res.get();
864
865 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
866 // promote to double.
867 // Note that default argument promotion applies only to float (and
868 // half/fp16); it does not apply to _Float16.
869 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
870 if (BTy && (BTy->getKind() == BuiltinType::Half ||
871 BTy->getKind() == BuiltinType::Float)) {
872 if (getLangOpts().OpenCL &&
873 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
874 if (BTy->getKind() == BuiltinType::Half) {
875 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
876 }
877 } else {
878 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
879 }
880 }
881 if (BTy &&
882 getLangOpts().getExtendIntArgs() ==
887 E = (Ty->isUnsignedIntegerType())
888 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
889 .get()
890 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
892 "Unexpected typesize for LongLongTy");
893 }
894
895 // C++ performs lvalue-to-rvalue conversion as a default argument
896 // promotion, even on class types, but note:
897 // C++11 [conv.lval]p2:
898 // When an lvalue-to-rvalue conversion occurs in an unevaluated
899 // operand or a subexpression thereof the value contained in the
900 // referenced object is not accessed. Otherwise, if the glvalue
901 // has a class type, the conversion copy-initializes a temporary
902 // of type T from the glvalue and the result of the conversion
903 // is a prvalue for the temporary.
904 // FIXME: add some way to gate this entire thing for correctness in
905 // potentially potentially evaluated contexts.
909 E->getExprLoc(), E);
910 if (Temp.isInvalid())
911 return ExprError();
912 E = Temp.get();
913 }
914
915 return E;
916}
917
918/// Determine the degree of POD-ness for an expression.
919/// Incomplete types are considered POD, since this check can be performed
920/// when we're in an unevaluated context.
922 if (Ty->isIncompleteType()) {
923 // C++11 [expr.call]p7:
924 // After these conversions, if the argument does not have arithmetic,
925 // enumeration, pointer, pointer to member, or class type, the program
926 // is ill-formed.
927 //
928 // Since we've already performed array-to-pointer and function-to-pointer
929 // decay, the only such type in C++ is cv void. This also handles
930 // initializer lists as variadic arguments.
931 if (Ty->isVoidType())
932 return VAK_Invalid;
933
934 if (Ty->isObjCObjectType())
935 return VAK_Invalid;
936 return VAK_Valid;
937 }
938
940 return VAK_Invalid;
941
942 if (Context.getTargetInfo().getTriple().isWasm() &&
944 return VAK_Invalid;
945 }
946
947 if (Ty.isCXX98PODType(Context))
948 return VAK_Valid;
949
950 // C++11 [expr.call]p7:
951 // Passing a potentially-evaluated argument of class type (Clause 9)
952 // having a non-trivial copy constructor, a non-trivial move constructor,
953 // or a non-trivial destructor, with no corresponding parameter,
954 // is conditionally-supported with implementation-defined semantics.
956 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
957 if (!Record->hasNonTrivialCopyConstructor() &&
958 !Record->hasNonTrivialMoveConstructor() &&
959 !Record->hasNonTrivialDestructor())
960 return VAK_ValidInCXX11;
961
962 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
963 return VAK_Valid;
964
965 if (Ty->isObjCObjectType())
966 return VAK_Invalid;
967
968 if (getLangOpts().MSVCCompat)
969 return VAK_MSVCUndefined;
970
971 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
972 // permitted to reject them. We should consider doing so.
973 return VAK_Undefined;
974}
975
977 // Don't allow one to pass an Objective-C interface to a vararg.
978 const QualType &Ty = E->getType();
980
981 // Complain about passing non-POD types through varargs.
982 switch (VAK) {
983 case VAK_ValidInCXX11:
985 E->getBeginLoc(), nullptr,
986 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
987 [[fallthrough]];
988 case VAK_Valid:
989 if (Ty->isRecordType()) {
990 // This is unlikely to be what the user intended. If the class has a
991 // 'c_str' member function, the user probably meant to call that.
992 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
993 PDiag(diag::warn_pass_class_arg_to_vararg)
994 << Ty << CT << hasCStrMethod(E) << ".c_str()");
995 }
996 break;
997
998 case VAK_Undefined:
1000 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1001 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1002 << getLangOpts().CPlusPlus11 << Ty << CT);
1003 break;
1004
1005 case VAK_Invalid:
1007 Diag(E->getBeginLoc(),
1008 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1009 << Ty << CT;
1010 else if (Ty->isObjCObjectType())
1011 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1012 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1013 << Ty << CT);
1014 else
1015 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1016 << isa<InitListExpr>(E) << Ty << CT;
1017 break;
1018 }
1019}
1020
1021/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1022/// will create a trap if the resulting type is not a POD type.
1024 FunctionDecl *FDecl) {
1025 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1026 // Strip the unbridged-cast placeholder expression off, if applicable.
1027 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1028 (CT == VariadicMethod ||
1029 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1030 E = stripARCUnbridgedCast(E);
1031
1032 // Otherwise, do normal placeholder checking.
1033 } else {
1034 ExprResult ExprRes = CheckPlaceholderExpr(E);
1035 if (ExprRes.isInvalid())
1036 return ExprError();
1037 E = ExprRes.get();
1038 }
1039 }
1040
1042 if (ExprRes.isInvalid())
1043 return ExprError();
1044
1045 // Copy blocks to the heap.
1046 if (ExprRes.get()->getType()->isBlockPointerType())
1047 maybeExtendBlockObject(ExprRes);
1048
1049 E = ExprRes.get();
1050
1051 // Diagnostics regarding non-POD argument types are
1052 // emitted along with format string checking in Sema::CheckFunctionCall().
1054 // Turn this into a trap.
1055 CXXScopeSpec SS;
1056 SourceLocation TemplateKWLoc;
1057 UnqualifiedId Name;
1058 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1059 E->getBeginLoc());
1060 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1061 /*HasTrailingLParen=*/true,
1062 /*IsAddressOfOperand=*/false);
1063 if (TrapFn.isInvalid())
1064 return ExprError();
1065
1066 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1067 std::nullopt, E->getEndLoc());
1068 if (Call.isInvalid())
1069 return ExprError();
1070
1071 ExprResult Comma =
1072 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1073 if (Comma.isInvalid())
1074 return ExprError();
1075 return Comma.get();
1076 }
1077
1078 if (!getLangOpts().CPlusPlus &&
1080 diag::err_call_incomplete_argument))
1081 return ExprError();
1082
1083 return E;
1084}
1085
1086/// Converts an integer to complex float type. Helper function of
1087/// UsualArithmeticConversions()
1088///
1089/// \return false if the integer expression is an integer type and is
1090/// successfully converted to the complex type.
1092 ExprResult &ComplexExpr,
1093 QualType IntTy,
1094 QualType ComplexTy,
1095 bool SkipCast) {
1096 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1097 if (SkipCast) return false;
1098 if (IntTy->isIntegerType()) {
1099 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1100 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1101 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1102 CK_FloatingRealToComplex);
1103 } else {
1104 assert(IntTy->isComplexIntegerType());
1105 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1106 CK_IntegralComplexToFloatingComplex);
1107 }
1108 return false;
1109}
1110
1111// This handles complex/complex, complex/float, or float/complex.
1112// When both operands are complex, the shorter operand is converted to the
1113// type of the longer, and that is the type of the result. This corresponds
1114// to what is done when combining two real floating-point operands.
1115// The fun begins when size promotion occur across type domains.
1116// From H&S 6.3.4: When one operand is complex and the other is a real
1117// floating-point type, the less precise type is converted, within it's
1118// real or complex domain, to the precision of the other type. For example,
1119// when combining a "long double" with a "double _Complex", the
1120// "double _Complex" is promoted to "long double _Complex".
1122 QualType ShorterType,
1123 QualType LongerType,
1124 bool PromotePrecision) {
1125 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1127 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1128
1129 if (PromotePrecision) {
1130 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1131 Shorter =
1132 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1133 } else {
1134 if (LongerIsComplex)
1135 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1136 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1137 }
1138 }
1139 return Result;
1140}
1141
1142/// Handle arithmetic conversion with complex types. Helper function of
1143/// UsualArithmeticConversions()
1145 ExprResult &RHS, QualType LHSType,
1146 QualType RHSType, bool IsCompAssign) {
1147 // if we have an integer operand, the result is the complex type.
1148 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1149 /*SkipCast=*/false))
1150 return LHSType;
1151 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1152 /*SkipCast=*/IsCompAssign))
1153 return RHSType;
1154
1155 // Compute the rank of the two types, regardless of whether they are complex.
1156 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1157 if (Order < 0)
1158 // Promote the precision of the LHS if not an assignment.
1159 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1160 /*PromotePrecision=*/!IsCompAssign);
1161 // Promote the precision of the RHS unless it is already the same as the LHS.
1162 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1163 /*PromotePrecision=*/Order > 0);
1164}
1165
1166/// Handle arithmetic conversion from integer to float. Helper function
1167/// of UsualArithmeticConversions()
1169 ExprResult &IntExpr,
1170 QualType FloatTy, QualType IntTy,
1171 bool ConvertFloat, bool ConvertInt) {
1172 if (IntTy->isIntegerType()) {
1173 if (ConvertInt)
1174 // Convert intExpr to the lhs floating point type.
1175 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1176 CK_IntegralToFloating);
1177 return FloatTy;
1178 }
1179
1180 // Convert both sides to the appropriate complex float.
1181 assert(IntTy->isComplexIntegerType());
1182 QualType result = S.Context.getComplexType(FloatTy);
1183
1184 // _Complex int -> _Complex float
1185 if (ConvertInt)
1186 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1187 CK_IntegralComplexToFloatingComplex);
1188
1189 // float -> _Complex float
1190 if (ConvertFloat)
1191 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1192 CK_FloatingRealToComplex);
1193
1194 return result;
1195}
1196
1197/// Handle arithmethic conversion with floating point types. Helper
1198/// function of UsualArithmeticConversions()
1200 ExprResult &RHS, QualType LHSType,
1201 QualType RHSType, bool IsCompAssign) {
1202 bool LHSFloat = LHSType->isRealFloatingType();
1203 bool RHSFloat = RHSType->isRealFloatingType();
1204
1205 // N1169 4.1.4: If one of the operands has a floating type and the other
1206 // operand has a fixed-point type, the fixed-point operand
1207 // is converted to the floating type [...]
1208 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1209 if (LHSFloat)
1210 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1211 else if (!IsCompAssign)
1212 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1213 return LHSFloat ? LHSType : RHSType;
1214 }
1215
1216 // If we have two real floating types, convert the smaller operand
1217 // to the bigger result.
1218 if (LHSFloat && RHSFloat) {
1219 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1220 if (order > 0) {
1221 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1222 return LHSType;
1223 }
1224
1225 assert(order < 0 && "illegal float comparison");
1226 if (!IsCompAssign)
1227 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1228 return RHSType;
1229 }
1230
1231 if (LHSFloat) {
1232 // Half FP has to be promoted to float unless it is natively supported
1233 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1234 LHSType = S.Context.FloatTy;
1235
1236 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1237 /*ConvertFloat=*/!IsCompAssign,
1238 /*ConvertInt=*/ true);
1239 }
1240 assert(RHSFloat);
1241 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1242 /*ConvertFloat=*/ true,
1243 /*ConvertInt=*/!IsCompAssign);
1244}
1245
1246/// Diagnose attempts to convert between __float128, __ibm128 and
1247/// long double if there is no support for such conversion.
1248/// Helper function of UsualArithmeticConversions().
1249static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1250 QualType RHSType) {
1251 // No issue if either is not a floating point type.
1252 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1253 return false;
1254
1255 // No issue if both have the same 128-bit float semantics.
1256 auto *LHSComplex = LHSType->getAs<ComplexType>();
1257 auto *RHSComplex = RHSType->getAs<ComplexType>();
1258
1259 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1260 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1261
1262 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1263 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1264
1265 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1266 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1267 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1268 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1269 return false;
1270
1271 return true;
1272}
1273
1274typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1275
1276namespace {
1277/// These helper callbacks are placed in an anonymous namespace to
1278/// permit their use as function template parameters.
1279ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1280 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1281}
1282
1283ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1284 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1285 CK_IntegralComplexCast);
1286}
1287}
1288
1289/// Handle integer arithmetic conversions. Helper function of
1290/// UsualArithmeticConversions()
1291template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1293 ExprResult &RHS, QualType LHSType,
1294 QualType RHSType, bool IsCompAssign) {
1295 // The rules for this case are in C99 6.3.1.8
1296 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1297 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1298 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1299 if (LHSSigned == RHSSigned) {
1300 // Same signedness; use the higher-ranked type
1301 if (order >= 0) {
1302 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1303 return LHSType;
1304 } else if (!IsCompAssign)
1305 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1306 return RHSType;
1307 } else if (order != (LHSSigned ? 1 : -1)) {
1308 // The unsigned type has greater than or equal rank to the
1309 // signed type, so use the unsigned type
1310 if (RHSSigned) {
1311 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1312 return LHSType;
1313 } else if (!IsCompAssign)
1314 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1315 return RHSType;
1316 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1317 // The two types are different widths; if we are here, that
1318 // means the signed type is larger than the unsigned type, so
1319 // use the signed type.
1320 if (LHSSigned) {
1321 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1322 return LHSType;
1323 } else if (!IsCompAssign)
1324 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1325 return RHSType;
1326 } else {
1327 // The signed type is higher-ranked than the unsigned type,
1328 // but isn't actually any bigger (like unsigned int and long
1329 // on most 32-bit systems). Use the unsigned type corresponding
1330 // to the signed type.
1331 QualType result =
1332 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1333 RHS = (*doRHSCast)(S, RHS.get(), result);
1334 if (!IsCompAssign)
1335 LHS = (*doLHSCast)(S, LHS.get(), result);
1336 return result;
1337 }
1338}
1339
1340/// Handle conversions with GCC complex int extension. Helper function
1341/// of UsualArithmeticConversions()
1343 ExprResult &RHS, QualType LHSType,
1344 QualType RHSType,
1345 bool IsCompAssign) {
1346 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1347 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1348
1349 if (LHSComplexInt && RHSComplexInt) {
1350 QualType LHSEltType = LHSComplexInt->getElementType();
1351 QualType RHSEltType = RHSComplexInt->getElementType();
1352 QualType ScalarType =
1353 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1354 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1355
1356 return S.Context.getComplexType(ScalarType);
1357 }
1358
1359 if (LHSComplexInt) {
1360 QualType LHSEltType = LHSComplexInt->getElementType();
1361 QualType ScalarType =
1362 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1363 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1365 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1366 CK_IntegralRealToComplex);
1367
1368 return ComplexType;
1369 }
1370
1371 assert(RHSComplexInt);
1372
1373 QualType RHSEltType = RHSComplexInt->getElementType();
1374 QualType ScalarType =
1375 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1376 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1378
1379 if (!IsCompAssign)
1380 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1381 CK_IntegralRealToComplex);
1382 return ComplexType;
1383}
1384
1385/// Return the rank of a given fixed point or integer type. The value itself
1386/// doesn't matter, but the values must be increasing with proper increasing
1387/// rank as described in N1169 4.1.1.
1388static unsigned GetFixedPointRank(QualType Ty) {
1389 const auto *BTy = Ty->getAs<BuiltinType>();
1390 assert(BTy && "Expected a builtin type.");
1391
1392 switch (BTy->getKind()) {
1393 case BuiltinType::ShortFract:
1394 case BuiltinType::UShortFract:
1395 case BuiltinType::SatShortFract:
1396 case BuiltinType::SatUShortFract:
1397 return 1;
1398 case BuiltinType::Fract:
1399 case BuiltinType::UFract:
1400 case BuiltinType::SatFract:
1401 case BuiltinType::SatUFract:
1402 return 2;
1403 case BuiltinType::LongFract:
1404 case BuiltinType::ULongFract:
1405 case BuiltinType::SatLongFract:
1406 case BuiltinType::SatULongFract:
1407 return 3;
1408 case BuiltinType::ShortAccum:
1409 case BuiltinType::UShortAccum:
1410 case BuiltinType::SatShortAccum:
1411 case BuiltinType::SatUShortAccum:
1412 return 4;
1413 case BuiltinType::Accum:
1414 case BuiltinType::UAccum:
1415 case BuiltinType::SatAccum:
1416 case BuiltinType::SatUAccum:
1417 return 5;
1418 case BuiltinType::LongAccum:
1419 case BuiltinType::ULongAccum:
1420 case BuiltinType::SatLongAccum:
1421 case BuiltinType::SatULongAccum:
1422 return 6;
1423 default:
1424 if (BTy->isInteger())
1425 return 0;
1426 llvm_unreachable("Unexpected fixed point or integer type");
1427 }
1428}
1429
1430/// handleFixedPointConversion - Fixed point operations between fixed
1431/// point types and integers or other fixed point types do not fall under
1432/// usual arithmetic conversion since these conversions could result in loss
1433/// of precsision (N1169 4.1.4). These operations should be calculated with
1434/// the full precision of their result type (N1169 4.1.6.2.1).
1436 QualType RHSTy) {
1437 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1438 "Expected at least one of the operands to be a fixed point type");
1439 assert((LHSTy->isFixedPointOrIntegerType() ||
1440 RHSTy->isFixedPointOrIntegerType()) &&
1441 "Special fixed point arithmetic operation conversions are only "
1442 "applied to ints or other fixed point types");
1443
1444 // If one operand has signed fixed-point type and the other operand has
1445 // unsigned fixed-point type, then the unsigned fixed-point operand is
1446 // converted to its corresponding signed fixed-point type and the resulting
1447 // type is the type of the converted operand.
1448 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1450 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1452
1453 // The result type is the type with the highest rank, whereby a fixed-point
1454 // conversion rank is always greater than an integer conversion rank; if the
1455 // type of either of the operands is a saturating fixedpoint type, the result
1456 // type shall be the saturating fixed-point type corresponding to the type
1457 // with the highest rank; the resulting value is converted (taking into
1458 // account rounding and overflow) to the precision of the resulting type.
1459 // Same ranks between signed and unsigned types are resolved earlier, so both
1460 // types are either signed or both unsigned at this point.
1461 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1462 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1463
1464 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1465
1467 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1468
1469 return ResultTy;
1470}
1471
1472/// Check that the usual arithmetic conversions can be performed on this pair of
1473/// expressions that might be of enumeration type.
1475 SourceLocation Loc,
1476 Sema::ArithConvKind ACK) {
1477 // C++2a [expr.arith.conv]p1:
1478 // If one operand is of enumeration type and the other operand is of a
1479 // different enumeration type or a floating-point type, this behavior is
1480 // deprecated ([depr.arith.conv.enum]).
1481 //
1482 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1483 // Eventually we will presumably reject these cases (in C++23 onwards?).
1484 QualType L = LHS->getType(), R = RHS->getType();
1485 bool LEnum = L->isUnscopedEnumerationType(),
1486 REnum = R->isUnscopedEnumerationType();
1487 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1488 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1489 (REnum && L->isFloatingType())) {
1490 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1491 ? diag::warn_arith_conv_enum_float_cxx20
1492 : diag::warn_arith_conv_enum_float)
1493 << LHS->getSourceRange() << RHS->getSourceRange()
1494 << (int)ACK << LEnum << L << R;
1495 } else if (!IsCompAssign && LEnum && REnum &&
1497 unsigned DiagID;
1498 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1499 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1500 // If either enumeration type is unnamed, it's less likely that the
1501 // user cares about this, but this situation is still deprecated in
1502 // C++2a. Use a different warning group.
1503 DiagID = S.getLangOpts().CPlusPlus20
1504 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1505 : diag::warn_arith_conv_mixed_anon_enum_types;
1506 } else if (ACK == Sema::ACK_Conditional) {
1507 // Conditional expressions are separated out because they have
1508 // historically had a different warning flag.
1509 DiagID = S.getLangOpts().CPlusPlus20
1510 ? diag::warn_conditional_mixed_enum_types_cxx20
1511 : diag::warn_conditional_mixed_enum_types;
1512 } else if (ACK == Sema::ACK_Comparison) {
1513 // Comparison expressions are separated out because they have
1514 // historically had a different warning flag.
1515 DiagID = S.getLangOpts().CPlusPlus20
1516 ? diag::warn_comparison_mixed_enum_types_cxx20
1517 : diag::warn_comparison_mixed_enum_types;
1518 } else {
1519 DiagID = S.getLangOpts().CPlusPlus20
1520 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1521 : diag::warn_arith_conv_mixed_enum_types;
1522 }
1523 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1524 << (int)ACK << L << R;
1525 }
1526}
1527
1528/// UsualArithmeticConversions - Performs various conversions that are common to
1529/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1530/// routine returns the first non-arithmetic type found. The client is
1531/// responsible for emitting appropriate error diagnostics.
1533 SourceLocation Loc,
1534 ArithConvKind ACK) {
1535 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1536
1537 if (ACK != ACK_CompAssign) {
1538 LHS = UsualUnaryConversions(LHS.get());
1539 if (LHS.isInvalid())
1540 return QualType();
1541 }
1542
1543 RHS = UsualUnaryConversions(RHS.get());
1544 if (RHS.isInvalid())
1545 return QualType();
1546
1547 // For conversion purposes, we ignore any qualifiers.
1548 // For example, "const float" and "float" are equivalent.
1549 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1550 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1551
1552 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1553 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1554 LHSType = AtomicLHS->getValueType();
1555
1556 // If both types are identical, no conversion is needed.
1557 if (Context.hasSameType(LHSType, RHSType))
1558 return Context.getCommonSugaredType(LHSType, RHSType);
1559
1560 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1561 // The caller can deal with this (e.g. pointer + int).
1562 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1563 return QualType();
1564
1565 // Apply unary and bitfield promotions to the LHS's type.
1566 QualType LHSUnpromotedType = LHSType;
1567 if (Context.isPromotableIntegerType(LHSType))
1568 LHSType = Context.getPromotedIntegerType(LHSType);
1569 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1570 if (!LHSBitfieldPromoteTy.isNull())
1571 LHSType = LHSBitfieldPromoteTy;
1572 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1573 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1574
1575 // If both types are identical, no conversion is needed.
1576 if (Context.hasSameType(LHSType, RHSType))
1577 return Context.getCommonSugaredType(LHSType, RHSType);
1578
1579 // At this point, we have two different arithmetic types.
1580
1581 // Diagnose attempts to convert between __ibm128, __float128 and long double
1582 // where such conversions currently can't be handled.
1583 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1584 return QualType();
1585
1586 // Handle complex types first (C99 6.3.1.8p1).
1587 if (LHSType->isComplexType() || RHSType->isComplexType())
1588 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1589 ACK == ACK_CompAssign);
1590
1591 // Now handle "real" floating types (i.e. float, double, long double).
1592 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1593 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1594 ACK == ACK_CompAssign);
1595
1596 // Handle GCC complex int extension.
1597 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1598 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1599 ACK == ACK_CompAssign);
1600
1601 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1602 return handleFixedPointConversion(*this, LHSType, RHSType);
1603
1604 // Finally, we have two differing integer types.
1605 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1606 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1607}
1608
1609//===----------------------------------------------------------------------===//
1610// Semantic Analysis for various Expression Types
1611//===----------------------------------------------------------------------===//
1612
1613
1616 SourceLocation DefaultLoc,
1617 SourceLocation RParenLoc,
1618 Expr *ControllingExpr,
1619 ArrayRef<ParsedType> ArgTypes,
1620 ArrayRef<Expr *> ArgExprs) {
1621 unsigned NumAssocs = ArgTypes.size();
1622 assert(NumAssocs == ArgExprs.size());
1623
1624 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1625 for (unsigned i = 0; i < NumAssocs; ++i) {
1626 if (ArgTypes[i])
1627 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1628 else
1629 Types[i] = nullptr;
1630 }
1631
1632 ExprResult ER =
1633 CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, ControllingExpr,
1634 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1635 delete [] Types;
1636 return ER;
1637}
1638
1641 SourceLocation DefaultLoc,
1642 SourceLocation RParenLoc,
1643 Expr *ControllingExpr,
1645 ArrayRef<Expr *> Exprs) {
1646 unsigned NumAssocs = Types.size();
1647 assert(NumAssocs == Exprs.size());
1648
1649 // Decay and strip qualifiers for the controlling expression type, and handle
1650 // placeholder type replacement. See committee discussion from WG14 DR423.
1651 {
1655 if (R.isInvalid())
1656 return ExprError();
1657 ControllingExpr = R.get();
1658 }
1659
1660 bool TypeErrorFound = false,
1661 IsResultDependent = ControllingExpr->isTypeDependent(),
1662 ContainsUnexpandedParameterPack
1663 = ControllingExpr->containsUnexpandedParameterPack();
1664
1665 // The controlling expression is an unevaluated operand, so side effects are
1666 // likely unintended.
1667 if (!inTemplateInstantiation() && !IsResultDependent &&
1668 ControllingExpr->HasSideEffects(Context, false))
1669 Diag(ControllingExpr->getExprLoc(),
1670 diag::warn_side_effects_unevaluated_context);
1671
1672 for (unsigned i = 0; i < NumAssocs; ++i) {
1673 if (Exprs[i]->containsUnexpandedParameterPack())
1674 ContainsUnexpandedParameterPack = true;
1675
1676 if (Types[i]) {
1677 if (Types[i]->getType()->containsUnexpandedParameterPack())
1678 ContainsUnexpandedParameterPack = true;
1679
1680 if (Types[i]->getType()->isDependentType()) {
1681 IsResultDependent = true;
1682 } else {
1683 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1684 // complete object type other than a variably modified type."
1685 unsigned D = 0;
1686 if (Types[i]->getType()->isIncompleteType())
1687 D = diag::err_assoc_type_incomplete;
1688 else if (!Types[i]->getType()->isObjectType())
1689 D = diag::err_assoc_type_nonobject;
1690 else if (Types[i]->getType()->isVariablyModifiedType())
1691 D = diag::err_assoc_type_variably_modified;
1692 else {
1693 // Because the controlling expression undergoes lvalue conversion,
1694 // array conversion, and function conversion, an association which is
1695 // of array type, function type, or is qualified can never be
1696 // reached. We will warn about this so users are less surprised by
1697 // the unreachable association. However, we don't have to handle
1698 // function types; that's not an object type, so it's handled above.
1699 //
1700 // The logic is somewhat different for C++ because C++ has different
1701 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1702 // If T is a non-class type, the type of the prvalue is the cv-
1703 // unqualified version of T. Otherwise, the type of the prvalue is T.
1704 // The result of these rules is that all qualified types in an
1705 // association in C are unreachable, and in C++, only qualified non-
1706 // class types are unreachable.
1707 unsigned Reason = 0;
1708 QualType QT = Types[i]->getType();
1709 if (QT->isArrayType())
1710 Reason = 1;
1711 else if (QT.hasQualifiers() &&
1712 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1713 Reason = 2;
1714
1715 if (Reason)
1716 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1717 diag::warn_unreachable_association)
1718 << QT << (Reason - 1);
1719 }
1720
1721 if (D != 0) {
1722 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1723 << Types[i]->getTypeLoc().getSourceRange()
1724 << Types[i]->getType();
1725 TypeErrorFound = true;
1726 }
1727
1728 // C11 6.5.1.1p2 "No two generic associations in the same generic
1729 // selection shall specify compatible types."
1730 for (unsigned j = i+1; j < NumAssocs; ++j)
1731 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1732 Context.typesAreCompatible(Types[i]->getType(),
1733 Types[j]->getType())) {
1734 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1735 diag::err_assoc_compatible_types)
1736 << Types[j]->getTypeLoc().getSourceRange()
1737 << Types[j]->getType()
1738 << Types[i]->getType();
1739 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1740 diag::note_compat_assoc)
1741 << Types[i]->getTypeLoc().getSourceRange()
1742 << Types[i]->getType();
1743 TypeErrorFound = true;
1744 }
1745 }
1746 }
1747 }
1748 if (TypeErrorFound)
1749 return ExprError();
1750
1751 // If we determined that the generic selection is result-dependent, don't
1752 // try to compute the result expression.
1753 if (IsResultDependent)
1754 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1755 Exprs, DefaultLoc, RParenLoc,
1756 ContainsUnexpandedParameterPack);
1757
1758 SmallVector<unsigned, 1> CompatIndices;
1759 unsigned DefaultIndex = -1U;
1760 // Look at the canonical type of the controlling expression in case it was a
1761 // deduced type like __auto_type. However, when issuing diagnostics, use the
1762 // type the user wrote in source rather than the canonical one.
1763 for (unsigned i = 0; i < NumAssocs; ++i) {
1764 if (!Types[i])
1765 DefaultIndex = i;
1766 else if (Context.typesAreCompatible(
1767 ControllingExpr->getType().getCanonicalType(),
1768 Types[i]->getType()))
1769 CompatIndices.push_back(i);
1770 }
1771
1772 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1773 // type compatible with at most one of the types named in its generic
1774 // association list."
1775 if (CompatIndices.size() > 1) {
1776 // We strip parens here because the controlling expression is typically
1777 // parenthesized in macro definitions.
1778 ControllingExpr = ControllingExpr->IgnoreParens();
1779 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1780 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1781 << (unsigned)CompatIndices.size();
1782 for (unsigned I : CompatIndices) {
1783 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1784 diag::note_compat_assoc)
1785 << Types[I]->getTypeLoc().getSourceRange()
1786 << Types[I]->getType();
1787 }
1788 return ExprError();
1789 }
1790
1791 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1792 // its controlling expression shall have type compatible with exactly one of
1793 // the types named in its generic association list."
1794 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1795 // We strip parens here because the controlling expression is typically
1796 // parenthesized in macro definitions.
1797 ControllingExpr = ControllingExpr->IgnoreParens();
1798 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1799 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1800 return ExprError();
1801 }
1802
1803 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1804 // type name that is compatible with the type of the controlling expression,
1805 // then the result expression of the generic selection is the expression
1806 // in that generic association. Otherwise, the result expression of the
1807 // generic selection is the expression in the default generic association."
1808 unsigned ResultIndex =
1809 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1810
1812 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1813 ContainsUnexpandedParameterPack, ResultIndex);
1814}
1815
1816/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1817/// location of the token and the offset of the ud-suffix within it.
1819 unsigned Offset) {
1821 S.getLangOpts());
1822}
1823
1824/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1825/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1827 IdentifierInfo *UDSuffix,
1828 SourceLocation UDSuffixLoc,
1829 ArrayRef<Expr*> Args,
1830 SourceLocation LitEndLoc) {
1831 assert(Args.size() <= 2 && "too many arguments for literal operator");
1832
1833 QualType ArgTy[2];
1834 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1835 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1836 if (ArgTy[ArgIdx]->isArrayType())
1837 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1838 }
1839
1840 DeclarationName OpName =
1842 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1843 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1844
1845 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1846 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1847 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1848 /*AllowStringTemplatePack*/ false,
1849 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1850 return ExprError();
1851
1852 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1853}
1854
1855/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1856/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1857/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1858/// multiple tokens. However, the common case is that StringToks points to one
1859/// string.
1860///
1863 assert(!StringToks.empty() && "Must have at least one string!");
1864
1865 StringLiteralParser Literal(StringToks, PP);
1866 if (Literal.hadError)
1867 return ExprError();
1868
1869 SmallVector<SourceLocation, 4> StringTokLocs;
1870 for (const Token &Tok : StringToks)
1871 StringTokLocs.push_back(Tok.getLocation());
1872
1873 QualType CharTy = Context.CharTy;
1875 if (Literal.isWide()) {
1876 CharTy = Context.getWideCharType();
1877 Kind = StringLiteral::Wide;
1878 } else if (Literal.isUTF8()) {
1879 if (getLangOpts().Char8)
1880 CharTy = Context.Char8Ty;
1881 Kind = StringLiteral::UTF8;
1882 } else if (Literal.isUTF16()) {
1883 CharTy = Context.Char16Ty;
1884 Kind = StringLiteral::UTF16;
1885 } else if (Literal.isUTF32()) {
1886 CharTy = Context.Char32Ty;
1887 Kind = StringLiteral::UTF32;
1888 } else if (Literal.isPascal()) {
1889 CharTy = Context.UnsignedCharTy;
1890 }
1891
1892 // Warn on initializing an array of char from a u8 string literal; this
1893 // becomes ill-formed in C++2a.
1895 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1896 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1897
1898 // Create removals for all 'u8' prefixes in the string literal(s). This
1899 // ensures C++2a compatibility (but may change the program behavior when
1900 // built by non-Clang compilers for which the execution character set is
1901 // not always UTF-8).
1902 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1903 SourceLocation RemovalDiagLoc;
1904 for (const Token &Tok : StringToks) {
1905 if (Tok.getKind() == tok::utf8_string_literal) {
1906 if (RemovalDiagLoc.isInvalid())
1907 RemovalDiagLoc = Tok.getLocation();
1909 Tok.getLocation(),
1910 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1912 }
1913 }
1914 Diag(RemovalDiagLoc, RemovalDiag);
1915 }
1916
1917 QualType StrTy =
1918 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1919
1920 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1921 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1922 Kind, Literal.Pascal, StrTy,
1923 &StringTokLocs[0],
1924 StringTokLocs.size());
1925 if (Literal.getUDSuffix().empty())
1926 return Lit;
1927
1928 // We're building a user-defined literal.
1929 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1930 SourceLocation UDSuffixLoc =
1931 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1932 Literal.getUDSuffixOffset());
1933
1934 // Make sure we're allowed user-defined literals here.
1935 if (!UDLScope)
1936 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1937
1938 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1939 // operator "" X (str, len)
1940 QualType SizeType = Context.getSizeType();
1941
1942 DeclarationName OpName =
1944 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1945 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1946
1947 QualType ArgTy[] = {
1948 Context.getArrayDecayedType(StrTy), SizeType
1949 };
1950
1951 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1952 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1953 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1954 /*AllowStringTemplatePack*/ true,
1955 /*DiagnoseMissing*/ true, Lit)) {
1956
1957 case LOLR_Cooked: {
1958 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1959 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1960 StringTokLocs[0]);
1961 Expr *Args[] = { Lit, LenArg };
1962
1963 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1964 }
1965
1966 case LOLR_Template: {
1967 TemplateArgumentListInfo ExplicitArgs;
1968 TemplateArgument Arg(Lit);
1969 TemplateArgumentLocInfo ArgInfo(Lit);
1970 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1971 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
1972 StringTokLocs.back(), &ExplicitArgs);
1973 }
1974
1976 TemplateArgumentListInfo ExplicitArgs;
1977
1978 unsigned CharBits = Context.getIntWidth(CharTy);
1979 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1980 llvm::APSInt Value(CharBits, CharIsUnsigned);
1981
1982 TemplateArgument TypeArg(CharTy);
1984 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1985
1986 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1987 Value = Lit->getCodeUnit(I);
1988 TemplateArgument Arg(Context, Value, CharTy);
1990 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1991 }
1992 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
1993 StringTokLocs.back(), &ExplicitArgs);
1994 }
1995 case LOLR_Raw:
1997 llvm_unreachable("unexpected literal operator lookup result");
1998 case LOLR_Error:
1999 return ExprError();
2000 }
2001 llvm_unreachable("unexpected literal operator lookup result");
2002}
2003
2006 SourceLocation Loc,
2007 const CXXScopeSpec *SS) {
2008 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2009 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2010}
2011
2014 const DeclarationNameInfo &NameInfo,
2015 const CXXScopeSpec *SS, NamedDecl *FoundD,
2016 SourceLocation TemplateKWLoc,
2017 const TemplateArgumentListInfo *TemplateArgs) {
2020 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2021 TemplateArgs);
2022}
2023
2024// CUDA/HIP: Check whether a captured reference variable is referencing a
2025// host variable in a device or host device lambda.
2027 VarDecl *VD) {
2028 if (!S.getLangOpts().CUDA || !VD->hasInit())
2029 return false;
2030 assert(VD->getType()->isReferenceType());
2031
2032 // Check whether the reference variable is referencing a host variable.
2033 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2034 if (!DRE)
2035 return false;
2036 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2037 if (!Referee || !Referee->hasGlobalStorage() ||
2038 Referee->hasAttr<CUDADeviceAttr>())
2039 return false;
2040
2041 // Check whether the current function is a device or host device lambda.
2042 // Check whether the reference variable is a capture by getDeclContext()
2043 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2044 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2045 if (MD && MD->getParent()->isLambda() &&
2046 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2047 VD->getDeclContext() != MD)
2048 return true;
2049
2050 return false;
2051}
2052
2054 // A declaration named in an unevaluated operand never constitutes an odr-use.
2056 return NOUR_Unevaluated;
2057
2058 // C++2a [basic.def.odr]p4:
2059 // A variable x whose name appears as a potentially-evaluated expression e
2060 // is odr-used by e unless [...] x is a reference that is usable in
2061 // constant expressions.
2062 // CUDA/HIP:
2063 // If a reference variable referencing a host variable is captured in a
2064 // device or host device lambda, the value of the referee must be copied
2065 // to the capture and the reference variable must be treated as odr-use
2066 // since the value of the referee is not known at compile time and must
2067 // be loaded from the captured.
2068 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2069 if (VD->getType()->isReferenceType() &&
2070 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2072 VD->isUsableInConstantExpressions(Context))
2073 return NOUR_Constant;
2074 }
2075
2076 // All remaining non-variable cases constitute an odr-use. For variables, we
2077 // need to wait and see how the expression is used.
2078 return NOUR_None;
2079}
2080
2081/// BuildDeclRefExpr - Build an expression that references a
2082/// declaration that does not require a closure capture.
2085 const DeclarationNameInfo &NameInfo,
2086 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2087 SourceLocation TemplateKWLoc,
2088 const TemplateArgumentListInfo *TemplateArgs) {
2089 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2090 NeedToCaptureVariable(D, NameInfo.getLoc());
2091
2093 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2094 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2096
2097 // C++ [except.spec]p17:
2098 // An exception-specification is considered to be needed when:
2099 // - in an expression, the function is the unique lookup result or
2100 // the selected member of a set of overloaded functions.
2101 //
2102 // We delay doing this until after we've built the function reference and
2103 // marked it as used so that:
2104 // a) if the function is defaulted, we get errors from defining it before /
2105 // instead of errors from computing its exception specification, and
2106 // b) if the function is a defaulted comparison, we can use the body we
2107 // build when defining it as input to the exception specification
2108 // computation rather than computing a new body.
2109 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2110 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2111 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2113 }
2114 }
2115
2116 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2118 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2120
2121 const auto *FD = dyn_cast<FieldDecl>(D);
2122 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2123 FD = IFD->getAnonField();
2124 if (FD) {
2125 UnusedPrivateFields.remove(FD);
2126 // Just in case we're building an illegal pointer-to-member.
2127 if (FD->isBitField())
2129 }
2130
2131 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2132 // designates a bit-field.
2133 if (const auto *BD = dyn_cast<BindingDecl>(D))
2134 if (const auto *BE = BD->getBinding())
2135 E->setObjectKind(BE->getObjectKind());
2136
2137 return E;
2138}
2139
2140/// Decomposes the given name into a DeclarationNameInfo, its location, and
2141/// possibly a list of template arguments.
2142///
2143/// If this produces template arguments, it is permitted to call
2144/// DecomposeTemplateName.
2145///
2146/// This actually loses a lot of source location information for
2147/// non-standard name kinds; we should consider preserving that in
2148/// some way.
2149void
2152 DeclarationNameInfo &NameInfo,
2153 const TemplateArgumentListInfo *&TemplateArgs) {
2154 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2155 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2156 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2157
2158 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2159 Id.TemplateId->NumArgs);
2160 translateTemplateArguments(TemplateArgsPtr, Buffer);
2161
2162 TemplateName TName = Id.TemplateId->Template.get();
2163 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2164 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2165 TemplateArgs = &Buffer;
2166 } else {
2167 NameInfo = GetNameFromUnqualifiedId(Id);
2168 TemplateArgs = nullptr;
2169 }
2170}
2171
2173 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2175 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2176 DeclContext *Ctx =
2177 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2178 if (!TC) {
2179 // Emit a special diagnostic for failed member lookups.
2180 // FIXME: computing the declaration context might fail here (?)
2181 if (Ctx)
2182 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2183 << SS.getRange();
2184 else
2185 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2186 return;
2187 }
2188
2189 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2190 bool DroppedSpecifier =
2191 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2192 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2193 ? diag::note_implicit_param_decl
2194 : diag::note_previous_decl;
2195 if (!Ctx)
2196 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2197 SemaRef.PDiag(NoteID));
2198 else
2199 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2200 << Typo << Ctx << DroppedSpecifier
2201 << SS.getRange(),
2202 SemaRef.PDiag(NoteID));
2203}
2204
2205/// Diagnose a lookup that found results in an enclosing class during error
2206/// recovery. This usually indicates that the results were found in a dependent
2207/// base class that could not be searched as part of a template definition.
2208/// Always issues a diagnostic (though this may be only a warning in MS
2209/// compatibility mode).
2210///
2211/// Return \c true if the error is unrecoverable, or \c false if the caller
2212/// should attempt to recover using these lookup results.
2214 // During a default argument instantiation the CurContext points
2215 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2216 // function parameter list, hence add an explicit check.
2217 bool isDefaultArgument =
2218 !CodeSynthesisContexts.empty() &&
2219 CodeSynthesisContexts.back().Kind ==
2221 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2222 bool isInstance = CurMethod && CurMethod->isInstance() &&
2223 R.getNamingClass() == CurMethod->getParent() &&
2224 !isDefaultArgument;
2225
2226 // There are two ways we can find a class-scope declaration during template
2227 // instantiation that we did not find in the template definition: if it is a
2228 // member of a dependent base class, or if it is declared after the point of
2229 // use in the same class. Distinguish these by comparing the class in which
2230 // the member was found to the naming class of the lookup.
2231 unsigned DiagID = diag::err_found_in_dependent_base;
2232 unsigned NoteID = diag::note_member_declared_at;
2234 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2235 : diag::err_found_later_in_class;
2236 } else if (getLangOpts().MSVCCompat) {
2237 DiagID = diag::ext_found_in_dependent_base;
2238 NoteID = diag::note_dependent_member_use;
2239 }
2240
2241 if (isInstance) {
2242 // Give a code modification hint to insert 'this->'.
2243 Diag(R.getNameLoc(), DiagID)
2244 << R.getLookupName()
2245 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2247 } else {
2248 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2249 // they're not shadowed).
2250 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2251 }
2252
2253 for (const NamedDecl *D : R)
2254 Diag(D->getLocation(), NoteID);
2255
2256 // Return true if we are inside a default argument instantiation
2257 // and the found name refers to an instance member function, otherwise
2258 // the caller will try to create an implicit member call and this is wrong
2259 // for default arguments.
2260 //
2261 // FIXME: Is this special case necessary? We could allow the caller to
2262 // diagnose this.
2263 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2264 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2265 return true;
2266 }
2267
2268 // Tell the callee to try to recover.
2269 return false;
2270}
2271
2272/// Diagnose an empty lookup.
2273///
2274/// \return false if new lookup candidates were found
2277 TemplateArgumentListInfo *ExplicitTemplateArgs,
2278 ArrayRef<Expr *> Args, TypoExpr **Out) {
2279 DeclarationName Name = R.getLookupName();
2280
2281 unsigned diagnostic = diag::err_undeclared_var_use;
2282 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2283 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2284 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2285 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2286 diagnostic = diag::err_undeclared_use;
2287 diagnostic_suggest = diag::err_undeclared_use_suggest;
2288 }
2289
2290 // If the original lookup was an unqualified lookup, fake an
2291 // unqualified lookup. This is useful when (for example) the
2292 // original lookup would not have found something because it was a
2293 // dependent name.
2294 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2295 while (DC) {
2296 if (isa<CXXRecordDecl>(DC)) {
2297 LookupQualifiedName(R, DC);
2298
2299 if (!R.empty()) {
2300 // Don't give errors about ambiguities in this lookup.
2302
2303 // If there's a best viable function among the results, only mention
2304 // that one in the notes.
2305 OverloadCandidateSet Candidates(R.getNameLoc(),
2307 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2309 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2310 OR_Success) {
2311 R.clear();
2312 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2313 R.resolveKind();
2314 }
2315
2317 }
2318
2319 R.clear();
2320 }
2321
2322 DC = DC->getLookupParent();
2323 }
2324
2325 // We didn't find anything, so try to correct for a typo.
2326 TypoCorrection Corrected;
2327 if (S && Out) {
2328 SourceLocation TypoLoc = R.getNameLoc();
2329 assert(!ExplicitTemplateArgs &&
2330 "Diagnosing an empty lookup with explicit template args!");
2331 *Out = CorrectTypoDelayed(
2332 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2333 [=](const TypoCorrection &TC) {
2334 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2335 diagnostic, diagnostic_suggest);
2336 },
2337 nullptr, CTK_ErrorRecovery);
2338 if (*Out)
2339 return true;
2340 } else if (S &&
2341 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2342 S, &SS, CCC, CTK_ErrorRecovery))) {
2343 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2344 bool DroppedSpecifier =
2345 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2346 R.setLookupName(Corrected.getCorrection());
2347
2348 bool AcceptableWithRecovery = false;
2349 bool AcceptableWithoutRecovery = false;
2350 NamedDecl *ND = Corrected.getFoundDecl();
2351 if (ND) {
2352 if (Corrected.isOverloaded()) {
2356 for (NamedDecl *CD : Corrected) {
2357 if (FunctionTemplateDecl *FTD =
2358 dyn_cast<FunctionTemplateDecl>(CD))
2360 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2361 Args, OCS);
2362 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2363 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2365 Args, OCS);
2366 }
2367 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2368 case OR_Success:
2369 ND = Best->FoundDecl;
2370 Corrected.setCorrectionDecl(ND);
2371 break;
2372 default:
2373 // FIXME: Arbitrarily pick the first declaration for the note.
2374 Corrected.setCorrectionDecl(ND);
2375 break;
2376 }
2377 }
2378 R.addDecl(ND);
2379 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2380 CXXRecordDecl *Record = nullptr;
2381 if (Corrected.getCorrectionSpecifier()) {
2382 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2383 Record = Ty->getAsCXXRecordDecl();
2384 }
2385 if (!Record)
2386 Record = cast<CXXRecordDecl>(
2388 R.setNamingClass(Record);
2389 }
2390
2391 auto *UnderlyingND = ND->getUnderlyingDecl();
2392 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2393 isa<FunctionTemplateDecl>(UnderlyingND);
2394 // FIXME: If we ended up with a typo for a type name or
2395 // Objective-C class name, we're in trouble because the parser
2396 // is in the wrong place to recover. Suggest the typo
2397 // correction, but don't make it a fix-it since we're not going
2398 // to recover well anyway.
2399 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2400 getAsTypeTemplateDecl(UnderlyingND) ||
2401 isa<ObjCInterfaceDecl>(UnderlyingND);
2402 } else {
2403 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2404 // because we aren't able to recover.
2405 AcceptableWithoutRecovery = true;
2406 }
2407
2408 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2409 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2410 ? diag::note_implicit_param_decl
2411 : diag::note_previous_decl;
2412 if (SS.isEmpty())
2413 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2414 PDiag(NoteID), AcceptableWithRecovery);
2415 else
2416 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2417 << Name << computeDeclContext(SS, false)
2418 << DroppedSpecifier << SS.getRange(),
2419 PDiag(NoteID), AcceptableWithRecovery);
2420
2421 // Tell the callee whether to try to recover.
2422 return !AcceptableWithRecovery;
2423 }
2424 }
2425 R.clear();
2426
2427 // Emit a special diagnostic for failed member lookups.
2428 // FIXME: computing the declaration context might fail here (?)
2429 if (!SS.isEmpty()) {
2430 Diag(R.getNameLoc(), diag::err_no_member)
2431 << Name << computeDeclContext(SS, false)
2432 << SS.getRange();
2433 return true;
2434 }
2435
2436 // Give up, we can't recover.
2437 Diag(R.getNameLoc(), diagnostic) << Name;
2438 return true;
2439}
2440
2441/// In Microsoft mode, if we are inside a template class whose parent class has
2442/// dependent base classes, and we can't resolve an unqualified identifier, then
2443/// assume the identifier is a member of a dependent base class. We can only
2444/// recover successfully in static methods, instance methods, and other contexts
2445/// where 'this' is available. This doesn't precisely match MSVC's
2446/// instantiation model, but it's close enough.
2447static Expr *
2449 DeclarationNameInfo &NameInfo,
2450 SourceLocation TemplateKWLoc,
2451 const TemplateArgumentListInfo *TemplateArgs) {
2452 // Only try to recover from lookup into dependent bases in static methods or
2453 // contexts where 'this' is available.
2454 QualType ThisType = S.getCurrentThisType();
2455 const CXXRecordDecl *RD = nullptr;
2456 if (!ThisType.isNull())
2457 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2458 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2459 RD = MD->getParent();
2460 if (!RD || !RD->hasAnyDependentBases())
2461 return nullptr;
2462
2463 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2464 // is available, suggest inserting 'this->' as a fixit.
2465 SourceLocation Loc = NameInfo.getLoc();
2466 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2467 DB << NameInfo.getName() << RD;
2468
2469 if (!ThisType.isNull()) {
2470 DB << FixItHint::CreateInsertion(Loc, "this->");
2472 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2473 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2474 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2475 }
2476
2477 // Synthesize a fake NNS that points to the derived class. This will
2478 // perform name lookup during template instantiation.
2479 CXXScopeSpec SS;
2480 auto *NNS =
2481 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2482 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2484 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2485 TemplateArgs);
2486}
2487
2490 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2491 bool HasTrailingLParen, bool IsAddressOfOperand,
2493 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2494 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2495 "cannot be direct & operand and have a trailing lparen");
2496 if (SS.isInvalid())
2497 return ExprError();
2498
2499 TemplateArgumentListInfo TemplateArgsBuffer;
2500
2501 // Decompose the UnqualifiedId into the following data.
2502 DeclarationNameInfo NameInfo;
2503 const TemplateArgumentListInfo *TemplateArgs;
2504 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2505
2506 DeclarationName Name = NameInfo.getName();
2507 IdentifierInfo *II = Name.getAsIdentifierInfo();
2508 SourceLocation NameLoc = NameInfo.getLoc();
2509
2510 if (II && II->isEditorPlaceholder()) {
2511 // FIXME: When typed placeholders are supported we can create a typed
2512 // placeholder expression node.
2513 return ExprError();
2514 }
2515
2516 // C++ [temp.dep.expr]p3:
2517 // An id-expression is type-dependent if it contains:
2518 // -- an identifier that was declared with a dependent type,
2519 // (note: handled after lookup)
2520 // -- a template-id that is dependent,
2521 // (note: handled in BuildTemplateIdExpr)
2522 // -- a conversion-function-id that specifies a dependent type,
2523 // -- a nested-name-specifier that contains a class-name that
2524 // names a dependent type.
2525 // Determine whether this is a member of an unknown specialization;
2526 // we need to handle these differently.
2527 bool DependentID = false;
2528 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2529 Name.getCXXNameType()->isDependentType()) {
2530 DependentID = true;
2531 } else if (SS.isSet()) {
2532 if (DeclContext *DC = computeDeclContext(SS, false)) {
2533 if (RequireCompleteDeclContext(SS, DC))
2534 return ExprError();
2535 } else {
2536 DependentID = true;
2537 }
2538 }
2539
2540 if (DependentID)
2541 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2542 IsAddressOfOperand, TemplateArgs);
2543
2544 // Perform the required lookup.
2545 LookupResult R(*this, NameInfo,
2549 if (TemplateKWLoc.isValid() || TemplateArgs) {
2550 // Lookup the template name again to correctly establish the context in
2551 // which it was found. This is really unfortunate as we already did the
2552 // lookup to determine that it was a template name in the first place. If
2553 // this becomes a performance hit, we can work harder to preserve those
2554 // results until we get here but it's likely not worth it.
2555 bool MemberOfUnknownSpecialization;
2556 AssumedTemplateKind AssumedTemplate;
2557 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2558 MemberOfUnknownSpecialization, TemplateKWLoc,
2559 &AssumedTemplate))
2560 return ExprError();
2561
2562 if (MemberOfUnknownSpecialization ||
2564 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2565 IsAddressOfOperand, TemplateArgs);
2566 } else {
2567 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2568 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2569
2570 // If the result might be in a dependent base class, this is a dependent
2571 // id-expression.
2573 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2574 IsAddressOfOperand, TemplateArgs);
2575
2576 // If this reference is in an Objective-C method, then we need to do
2577 // some special Objective-C lookup, too.
2578 if (IvarLookupFollowUp) {
2579 ExprResult E(LookupInObjCMethod(R, S, II, true));
2580 if (E.isInvalid())
2581 return ExprError();
2582
2583 if (Expr *Ex = E.getAs<Expr>())
2584 return Ex;
2585 }
2586 }
2587
2588 if (R.isAmbiguous())
2589 return ExprError();
2590
2591 // This could be an implicitly declared function reference if the language
2592 // mode allows it as a feature.
2593 if (R.empty() && HasTrailingLParen && II &&
2594 getLangOpts().implicitFunctionsAllowed()) {
2595 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2596 if (D) R.addDecl(D);
2597 }
2598
2599 // Determine whether this name might be a candidate for
2600 // argument-dependent lookup.
2601 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2602
2603 if (R.empty() && !ADL) {
2604 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2605 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2606 TemplateKWLoc, TemplateArgs))
2607 return E;
2608 }
2609
2610 // Don't diagnose an empty lookup for inline assembly.
2611 if (IsInlineAsmIdentifier)
2612 return ExprError();
2613
2614 // If this name wasn't predeclared and if this is not a function
2615 // call, diagnose the problem.
2616 TypoExpr *TE = nullptr;
2617 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2618 : nullptr);
2619 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2620 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2621 "Typo correction callback misconfigured");
2622 if (CCC) {
2623 // Make sure the callback knows what the typo being diagnosed is.
2624 CCC->setTypoName(II);
2625 if (SS.isValid())
2626 CCC->setTypoNNS(SS.getScopeRep());
2627 }
2628 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2629 // a template name, but we happen to have always already looked up the name
2630 // before we get here if it must be a template name.
2631 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2632 std::nullopt, &TE)) {
2633 if (TE && KeywordReplacement) {
2634 auto &State = getTypoExprState(TE);
2635 auto BestTC = State.Consumer->getNextCorrection();
2636 if (BestTC.isKeyword()) {
2637 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2638 if (State.DiagHandler)
2639 State.DiagHandler(BestTC);
2640 KeywordReplacement->startToken();
2641 KeywordReplacement->setKind(II->getTokenID());
2642 KeywordReplacement->setIdentifierInfo(II);
2643 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2644 // Clean up the state associated with the TypoExpr, since it has
2645 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2646 clearDelayedTypo(TE);
2647 // Signal that a correction to a keyword was performed by returning a
2648 // valid-but-null ExprResult.
2649 return (Expr*)nullptr;
2650 }
2651 State.Consumer->resetCorrectionStream();
2652 }
2653 return TE ? TE : ExprError();
2654 }
2655
2656 assert(!R.empty() &&
2657 "DiagnoseEmptyLookup returned false but added no results");
2658
2659 // If we found an Objective-C instance variable, let
2660 // LookupInObjCMethod build the appropriate expression to
2661 // reference the ivar.
2662 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2663 R.clear();
2664 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2665 // In a hopelessly buggy code, Objective-C instance variable
2666 // lookup fails and no expression will be built to reference it.
2667 if (!E.isInvalid() && !E.get())
2668 return ExprError();
2669 return E;
2670 }
2671 }
2672
2673 // This is guaranteed from this point on.
2674 assert(!R.empty() || ADL);
2675
2676 // Check whether this might be a C++ implicit instance member access.
2677 // C++ [class.mfct.non-static]p3:
2678 // When an id-expression that is not part of a class member access
2679 // syntax and not used to form a pointer to member is used in the
2680 // body of a non-static member function of class X, if name lookup
2681 // resolves the name in the id-expression to a non-static non-type
2682 // member of some class C, the id-expression is transformed into a
2683 // class member access expression using (*this) as the
2684 // postfix-expression to the left of the . operator.
2685 //
2686 // But we don't actually need to do this for '&' operands if R
2687 // resolved to a function or overloaded function set, because the
2688 // expression is ill-formed if it actually works out to be a
2689 // non-static member function:
2690 //
2691 // C++ [expr.ref]p4:
2692 // Otherwise, if E1.E2 refers to a non-static member function. . .
2693 // [t]he expression can be used only as the left-hand operand of a
2694 // member function call.
2695 //
2696 // There are other safeguards against such uses, but it's important
2697 // to get this right here so that we don't end up making a
2698 // spuriously dependent expression if we're inside a dependent
2699 // instance method.
2700 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2701 bool MightBeImplicitMember;
2702 if (!IsAddressOfOperand)
2703 MightBeImplicitMember = true;
2704 else if (!SS.isEmpty())
2705 MightBeImplicitMember = false;
2706 else if (R.isOverloadedResult())
2707 MightBeImplicitMember = false;
2708 else if (R.isUnresolvableResult())
2709 MightBeImplicitMember = true;
2710 else
2711 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2712 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2713 isa<MSPropertyDecl>(R.getFoundDecl());
2714
2715 if (MightBeImplicitMember)
2716 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2717 R, TemplateArgs, S);
2718 }
2719
2720 if (TemplateArgs || TemplateKWLoc.isValid()) {
2721
2722 // In C++1y, if this is a variable template id, then check it
2723 // in BuildTemplateIdExpr().
2724 // The single lookup result must be a variable template declaration.
2725 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2726 Id.TemplateId->Kind == TNK_Var_template) {
2727 assert(R.getAsSingle<VarTemplateDecl>() &&
2728 "There should only be one declaration found.");
2729 }
2730
2731 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2732 }
2733
2734 return BuildDeclarationNameExpr(SS, R, ADL);
2735}
2736
2737/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2738/// declaration name, generally during template instantiation.
2739/// There's a large number of things which don't need to be done along
2740/// this path.
2742 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2743 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2744 if (NameInfo.getName().isDependentName())
2745 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2746 NameInfo, /*TemplateArgs=*/nullptr);
2747
2748 DeclContext *DC = computeDeclContext(SS, false);
2749 if (!DC)
2750 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2751 NameInfo, /*TemplateArgs=*/nullptr);
2752
2753 if (RequireCompleteDeclContext(SS, DC))
2754 return ExprError();
2755
2756 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2757 LookupQualifiedName(R, DC);
2758
2759 if (R.isAmbiguous())
2760 return ExprError();
2761
2763 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2764 NameInfo, /*TemplateArgs=*/nullptr);
2765
2766 if (R.empty()) {
2767 // Don't diagnose problems with invalid record decl, the secondary no_member
2768 // diagnostic during template instantiation is likely bogus, e.g. if a class
2769 // is invalid because it's derived from an invalid base class, then missing
2770 // members were likely supposed to be inherited.
2771 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2772 if (CD->isInvalidDecl())
2773 return ExprError();
2774 Diag(NameInfo.getLoc(), diag::err_no_member)
2775 << NameInfo.getName() << DC << SS.getRange();
2776 return ExprError();
2777 }
2778
2779 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2780 // Diagnose a missing typename if this resolved unambiguously to a type in
2781 // a dependent context. If we can recover with a type, downgrade this to
2782 // a warning in Microsoft compatibility mode.
2783 unsigned DiagID = diag::err_typename_missing;
2784 if (RecoveryTSI && getLangOpts().MSVCCompat)
2785 DiagID = diag::ext_typename_missing;
2786 SourceLocation Loc = SS.getBeginLoc();
2787 auto D = Diag(Loc, DiagID);
2788 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2789 << SourceRange(Loc, NameInfo.getEndLoc());
2790
2791 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2792 // context.
2793 if (!RecoveryTSI)
2794 return ExprError();
2795
2796 // Only issue the fixit if we're prepared to recover.
2797 D << FixItHint::CreateInsertion(Loc, "typename ");
2798
2799 // Recover by pretending this was an elaborated type.
2801 TypeLocBuilder TLB;
2802 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2803
2804 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2808
2809 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2810
2811 return ExprEmpty();
2812 }
2813
2814 // Defend against this resolving to an implicit member access. We usually
2815 // won't get here if this might be a legitimate a class member (we end up in
2816 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2817 // a pointer-to-member or in an unevaluated context in C++11.
2818 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2820 /*TemplateKWLoc=*/SourceLocation(),
2821 R, /*TemplateArgs=*/nullptr, S);
2822
2823 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2824}
2825
2826/// The parser has read a name in, and Sema has detected that we're currently
2827/// inside an ObjC method. Perform some additional checks and determine if we
2828/// should form a reference to an ivar.
2829///
2830/// Ideally, most of this would be done by lookup, but there's
2831/// actually quite a lot of extra work involved.
2833 IdentifierInfo *II) {
2834 SourceLocation Loc = Lookup.getNameLoc();
2835 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2836
2837 // Check for error condition which is already reported.
2838 if (!CurMethod)
2839 return DeclResult(true);
2840
2841 // There are two cases to handle here. 1) scoped lookup could have failed,
2842 // in which case we should look for an ivar. 2) scoped lookup could have
2843 // found a decl, but that decl is outside the current instance method (i.e.
2844 // a global variable). In these two cases, we do a lookup for an ivar with
2845 // this name, if the lookup sucedes, we replace it our current decl.
2846
2847 // If we're in a class method, we don't normally want to look for
2848 // ivars. But if we don't find anything else, and there's an
2849 // ivar, that's an error.
2850 bool IsClassMethod = CurMethod->isClassMethod();
2851
2852 bool LookForIvars;
2853 if (Lookup.empty())
2854 LookForIvars = true;
2855 else if (IsClassMethod)
2856 LookForIvars = false;
2857 else
2858 LookForIvars = (Lookup.isSingleResult() &&
2860 ObjCInterfaceDecl *IFace = nullptr;
2861 if (LookForIvars) {
2862 IFace = CurMethod->getClassInterface();
2863 ObjCInterfaceDecl *ClassDeclared;
2864 ObjCIvarDecl *IV = nullptr;
2865 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2866 // Diagnose using an ivar in a class method.
2867 if (IsClassMethod) {
2868 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2869 return DeclResult(true);
2870 }
2871
2872 // Diagnose the use of an ivar outside of the declaring class.
2874 !declaresSameEntity(ClassDeclared, IFace) &&
2875 !getLangOpts().DebuggerSupport)
2876 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2877
2878 // Success.
2879 return IV;
2880 }
2881 } else if (CurMethod->isInstanceMethod()) {
2882 // We should warn if a local variable hides an ivar.
2883 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2884 ObjCInterfaceDecl *ClassDeclared;
2885 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2886 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2887 declaresSameEntity(IFace, ClassDeclared))
2888 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2889 }
2890 }
2891 } else if (Lookup.isSingleResult() &&
2893 // If accessing a stand-alone ivar in a class method, this is an error.
2894 if (const ObjCIvarDecl *IV =
2895 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2896 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2897 return DeclResult(true);
2898 }
2899 }
2900
2901 // Didn't encounter an error, didn't find an ivar.
2902 return DeclResult(false);
2903}
2904
2906 ObjCIvarDecl *IV) {
2907 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2908 assert(CurMethod && CurMethod->isInstanceMethod() &&
2909 "should not reference ivar from this context");
2910
2911 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2912 assert(IFace && "should not reference ivar from this context");
2913
2914 // If we're referencing an invalid decl, just return this as a silent
2915 // error node. The error diagnostic was already emitted on the decl.
2916 if (IV->isInvalidDecl())
2917 return ExprError();
2918
2919 // Check if referencing a field with __attribute__((deprecated)).
2920 if (DiagnoseUseOfDecl(IV, Loc))
2921 return ExprError();
2922
2923 // FIXME: This should use a new expr for a direct reference, don't
2924 // turn this into Self->ivar, just return a BareIVarExpr or something.
2925 IdentifierInfo &II = Context.Idents.get("self");
2926 UnqualifiedId SelfName;
2927 SelfName.setImplicitSelfParam(&II);
2928 CXXScopeSpec SelfScopeSpec;
2929 SourceLocation TemplateKWLoc;
2930 ExprResult SelfExpr =
2931 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2932 /*HasTrailingLParen=*/false,
2933 /*IsAddressOfOperand=*/false);
2934 if (SelfExpr.isInvalid())
2935 return ExprError();
2936
2937 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2938 if (SelfExpr.isInvalid())
2939 return ExprError();
2940
2941 MarkAnyDeclReferenced(Loc, IV, true);
2942
2943 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2944 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2945 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2946 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2947
2949 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2950 IV->getLocation(), SelfExpr.get(), true, true);
2951
2953 if (!isUnevaluatedContext() &&
2954 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2956 }
2957 if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
2958 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2959 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2960
2961 return Result;
2962}
2963
2964/// The parser has read a name in, and Sema has detected that we're currently
2965/// inside an ObjC method. Perform some additional checks and determine if we
2966/// should form a reference to an ivar. If so, build an expression referencing
2967/// that ivar.
2970 IdentifierInfo *II, bool AllowBuiltinCreation) {
2971 // FIXME: Integrate this lookup step into LookupParsedName.
2972 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2973 if (Ivar.isInvalid())
2974 return ExprError();
2975 if (Ivar.isUsable())
2976 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2977 cast<ObjCIvarDecl>(Ivar.get()));
2978
2979 if (Lookup.empty() && II && AllowBuiltinCreation)
2980 LookupBuiltin(Lookup);
2981
2982 // Sentinel value saying that we didn't do anything special.
2983 return ExprResult(false);
2984}
2985
2986/// Cast a base object to a member's actual type.
2987///
2988/// There are two relevant checks:
2989///
2990/// C++ [class.access.base]p7:
2991///
2992/// If a class member access operator [...] is used to access a non-static
2993/// data member or non-static member function, the reference is ill-formed if
2994/// the left operand [...] cannot be implicitly converted to a pointer to the
2995/// naming class of the right operand.
2996///
2997/// C++ [expr.ref]p7:
2998///
2999/// If E2 is a non-static data member or a non-static member function, the
3000/// program is ill-formed if the class of which E2 is directly a member is an
3001/// ambiguous base (11.8) of the naming class (11.9.3) of E2.
3002///
3003/// Note that the latter check does not consider access; the access of the
3004/// "real" base class is checked as appropriate when checking the access of the
3005/// member name.
3008 NestedNameSpecifier *Qualifier,
3009 NamedDecl *FoundDecl,
3010 NamedDecl *Member) {
3011 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3012 if (!RD)
3013 return From;
3014
3015 QualType DestRecordType;
3016 QualType DestType;
3017 QualType FromRecordType;
3018 QualType FromType = From->getType();
3019 bool PointerConversions = false;
3020 if (isa<FieldDecl>(Member)) {
3021 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3022 auto FromPtrType = FromType->getAs<PointerType>();
3023 DestRecordType = Context.getAddrSpaceQualType(
3024 DestRecordType, FromPtrType
3025 ? FromType->getPointeeType().getAddressSpace()
3026 : FromType.getAddressSpace());
3027
3028 if (FromPtrType) {
3029 DestType = Context.getPointerType(DestRecordType);
3030 FromRecordType = FromPtrType->getPointeeType();
3031 PointerConversions = true;
3032 } else {
3033 DestType = DestRecordType;
3034 FromRecordType = FromType;
3035 }
3036 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3037 if (Method->isStatic())
3038 return From;
3039
3040 DestType = Method->getThisType();
3041 DestRecordType = DestType->getPointeeType();
3042
3043 if (FromType->getAs<PointerType>()) {
3044 FromRecordType = FromType->getPointeeType();
3045 PointerConversions = true;
3046 } else {
3047 FromRecordType = FromType;
3048 DestType = DestRecordType;
3049 }
3050
3051 LangAS FromAS = FromRecordType.getAddressSpace();
3052 LangAS DestAS = DestRecordType.getAddressSpace();
3053 if (FromAS != DestAS) {
3054 QualType FromRecordTypeWithoutAS =
3055 Context.removeAddrSpaceQualType(FromRecordType);
3056 QualType FromTypeWithDestAS =
3057 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3058 if (PointerConversions)
3059 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3060 From = ImpCastExprToType(From, FromTypeWithDestAS,
3061 CK_AddressSpaceConversion, From->getValueKind())
3062 .get();
3063 }
3064 } else {
3065 // No conversion necessary.
3066 return From;
3067 }
3068
3069 if (DestType->isDependentType() || FromType->isDependentType())
3070 return From;
3071
3072 // If the unqualified types are the same, no conversion is necessary.
3073 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3074 return From;
3075
3076 SourceRange FromRange = From->getSourceRange();
3077 SourceLocation FromLoc = FromRange.getBegin();
3078
3079 ExprValueKind VK = From->getValueKind();
3080
3081 // C++ [class.member.lookup]p8:
3082 // [...] Ambiguities can often be resolved by qualifying a name with its
3083 // class name.
3084 //
3085 // If the member was a qualified name and the qualified referred to a
3086 // specific base subobject type, we'll cast to that intermediate type
3087 // first and then to the object in which the member is declared. That allows
3088 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3089 //
3090 // class Base { public: int x; };
3091 // class Derived1 : public Base { };
3092 // class Derived2 : public Base { };
3093 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3094 //
3095 // void VeryDerived::f() {
3096 // x = 17; // error: ambiguous base subobjects
3097 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3098 // }
3099 if (Qualifier && Qualifier->getAsType()) {
3100 QualType QType = QualType(Qualifier->getAsType(), 0);
3101 assert(QType->isRecordType() && "lookup done with non-record type");
3102
3103 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3104
3105 // In C++98, the qualifier type doesn't actually have to be a base
3106 // type of the object type, in which case we just ignore it.
3107 // Otherwise build the appropriate casts.
3108 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3109 CXXCastPath BasePath;
3110 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3111 FromLoc, FromRange, &BasePath))
3112 return ExprError();
3113
3114 if (PointerConversions)
3115 QType = Context.getPointerType(QType);
3116 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3117 VK, &BasePath).get();
3118
3119 FromType = QType;
3120 FromRecordType = QRecordType;
3121
3122 // If the qualifier type was the same as the destination type,
3123 // we're done.
3124 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3125 return From;
3126 }
3127 }
3128
3129 CXXCastPath BasePath;
3130 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3131 FromLoc, FromRange, &BasePath,
3132 /*IgnoreAccess=*/true))
3133 return ExprError();
3134
3135 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3136 VK, &BasePath);
3137}
3138
3140 const LookupResult &R,
3141 bool HasTrailingLParen) {
3142 // Only when used directly as the postfix-expression of a call.
3143 if (!HasTrailingLParen)
3144 return false;
3145
3146 // Never if a scope specifier was provided.
3147 if (SS.isSet())
3148 return false;
3149
3150 // Only in C++ or ObjC++.
3151 if (!getLangOpts().CPlusPlus)
3152 return false;
3153
3154 // Turn off ADL when we find certain kinds of declarations during
3155 // normal lookup:
3156 for (const NamedDecl *D : R) {
3157 // C++0x [basic.lookup.argdep]p3:
3158 // -- a declaration of a class member
3159 // Since using decls preserve this property, we check this on the
3160 // original decl.
3161 if (D->isCXXClassMember())
3162 return false;
3163
3164 // C++0x [basic.lookup.argdep]p3:
3165 // -- a block-scope function declaration that is not a
3166 // using-declaration
3167 // NOTE: we also trigger this for function templates (in fact, we
3168 // don't check the decl type at all, since all other decl types
3169 // turn off ADL anyway).
3170 if (isa<UsingShadowDecl>(D))
3171 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3172 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3173 return false;
3174
3175 // C++0x [basic.lookup.argdep]p3:
3176 // -- a declaration that is neither a function or a function
3177 // template
3178 // And also for builtin functions.
3179 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3180 // But also builtin functions.
3181 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3182 return false;
3183 } else if (!isa<FunctionTemplateDecl>(D))
3184 return false;
3185 }
3186
3187 return true;
3188}
3189
3190
3191/// Diagnoses obvious problems with the use of the given declaration
3192/// as an expression. This is only actually called for lookups that
3193/// were not overloaded, and it doesn't promise that the declaration
3194/// will in fact be used.
3196 bool AcceptInvalid) {
3197 if (D->isInvalidDecl() && !AcceptInvalid)
3198 return true;
3199
3200 if (isa<TypedefNameDecl>(D)) {
3201 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3202 return true;
3203 }
3204
3205 if (isa<ObjCInterfaceDecl>(D)) {
3206 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3207 return true;
3208 }
3209
3210 if (isa<NamespaceDecl>(D)) {
3211 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3212 return true;
3213 }
3214
3215 return false;
3216}
3217
3218// Certain multiversion types should be treated as overloaded even when there is
3219// only one result.
3221 assert(R.isSingleResult() && "Expected only a single result");
3222 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3223 return FD &&
3224 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3225}
3226
3228 LookupResult &R, bool NeedsADL,
3229 bool AcceptInvalidDecl) {
3230 // If this is a single, fully-resolved result and we don't need ADL,
3231 // just build an ordinary singleton decl ref.
3232 if (!NeedsADL && R.isSingleResult() &&
3236 R.getRepresentativeDecl(), nullptr,
3237 AcceptInvalidDecl);
3238
3239 // We only need to check the declaration if there's exactly one
3240 // result, because in the overloaded case the results can only be
3241 // functions and function templates.
3243 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3244 AcceptInvalidDecl))
3245 return ExprError();
3246
3247 // Otherwise, just build an unresolved lookup expression. Suppress
3248 // any lookup-related diagnostics; we'll hash these out later, when
3249 // we've picked a target.
3251
3256 NeedsADL, R.isOverloadedResult(),
3257 R.begin(), R.end());
3258
3259 return ULE;
3260}
3261
3263 SourceLocation loc,
3264 ValueDecl *var);
3265
3266/// Complete semantic analysis for a reference to the given declaration.
3268 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3269 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3270 bool AcceptInvalidDecl) {
3271 assert(D && "Cannot refer to a NULL declaration");
3272 assert(!isa<FunctionTemplateDecl>(D) &&
3273 "Cannot refer unambiguously to a function template");
3274
3275 SourceLocation Loc = NameInfo.getLoc();
3276 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3277 // Recovery from invalid cases (e.g. D is an invalid Decl).
3278 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3279 // diagnostics, as invalid decls use int as a fallback type.
3280 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3281 }
3282
3283 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3284 // Specifically diagnose references to class templates that are missing
3285 // a template argument list.
3287 return ExprError();
3288 }
3289
3290 // Make sure that we're referring to a value.
3291 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3292 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3293 Diag(D->getLocation(), diag::note_declared_at);
3294 return ExprError();
3295 }
3296
3297 // Check whether this declaration can be used. Note that we suppress
3298 // this check when we're going to perform argument-dependent lookup
3299 // on this function name, because this might not be the function
3300 // that overload resolution actually selects.
3301 if (DiagnoseUseOfDecl(D, Loc))
3302 return ExprError();
3303
3304 auto *VD = cast<ValueDecl>(D);
3305
3306 // Only create DeclRefExpr's for valid Decl's.
3307 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3308 return ExprError();
3309
3310 // Handle members of anonymous structs and unions. If we got here,
3311 // and the reference is to a class member indirect field, then this
3312 // must be the subject of a pointer-to-member expression.
3313 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3314 IndirectField && !IndirectField->isCXXClassMember())
3316 IndirectField);
3317
3318 QualType type = VD->getType();
3319 if (type.isNull())
3320 return ExprError();
3321 ExprValueKind valueKind = VK_PRValue;
3322
3323 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3324 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3325 // is expanded by some outer '...' in the context of the use.
3326 type = type.getNonPackExpansionType();
3327
3328 switch (D->getKind()) {
3329 // Ignore all the non-ValueDecl kinds.
3330#define ABSTRACT_DECL(kind)
3331#define VALUE(type, base)
3332#define DECL(type, base) case Decl::type:
3333#include "clang/AST/DeclNodes.inc"
3334 llvm_unreachable("invalid value decl kind");
3335
3336 // These shouldn't make it here.
3337 case Decl::ObjCAtDefsField:
3338 llvm_unreachable("forming non-member reference to ivar?");
3339
3340 // Enum constants are always r-values and never references.
3341 // Unresolved using declarations are dependent.
3342 case Decl::EnumConstant:
3343 case Decl::UnresolvedUsingValue:
3344 case Decl::OMPDeclareReduction:
3345 case Decl::OMPDeclareMapper:
3346 valueKind = VK_PRValue;
3347 break;
3348
3349 // Fields and indirect fields that got here must be for
3350 // pointer-to-member expressions; we just call them l-values for
3351 // internal consistency, because this subexpression doesn't really
3352 // exist in the high-level semantics.
3353 case Decl::Field:
3354 case Decl::IndirectField:
3355 case Decl::ObjCIvar:
3356 assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3357
3358 // These can't have reference type in well-formed programs, but
3359 // for internal consistency we do this anyway.
3360 type = type.getNonReferenceType();
3361 valueKind = VK_LValue;
3362 break;
3363
3364 // Non-type template parameters are either l-values or r-values
3365 // depending on the type.
3366 case Decl::NonTypeTemplateParm: {
3367 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3368 type = reftype->getPointeeType();
3369 valueKind = VK_LValue; // even if the parameter is an r-value reference
3370 break;
3371 }
3372
3373 // [expr.prim.id.unqual]p2:
3374 // If the entity is a template parameter object for a template
3375 // parameter of type T, the type of the expression is const T.
3376 // [...] The expression is an lvalue if the entity is a [...] template
3377 // parameter object.
3378 if (type->isRecordType()) {
3379 type = type.getUnqualifiedType().withConst();
3380 valueKind = VK_LValue;
3381 break;
3382 }
3383
3384 // For non-references, we need to strip qualifiers just in case
3385 // the template parameter was declared as 'const int' or whatever.
3386 valueKind = VK_PRValue;
3387 type = type.getUnqualifiedType();
3388 break;
3389 }
3390
3391 case Decl::Var:
3392 case Decl::VarTemplateSpecialization:
3393 case Decl::VarTemplatePartialSpecialization:
3394 case Decl::Decomposition:
3395 case Decl::OMPCapturedExpr:
3396 // In C, "extern void blah;" is valid and is an r-value.
3397 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3398 type->isVoidType()) {
3399 valueKind = VK_PRValue;
3400 break;
3401 }
3402 [[fallthrough]];
3403
3404 case Decl::ImplicitParam:
3405 case Decl::ParmVar: {
3406 // These are always l-values.
3407 valueKind = VK_LValue;
3408 type = type.getNonReferenceType();
3409
3410 // FIXME: Does the addition of const really only apply in
3411 // potentially-evaluated contexts? Since the variable isn't actually
3412 // captured in an unevaluated context, it seems that the answer is no.
3413 if (!isUnevaluatedContext()) {
3414 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3415 if (!CapturedType.isNull())
3416 type = CapturedType;
3417 }
3418
3419 break;
3420 }
3421
3422 case Decl::Binding:
3423 // These are always lvalues.
3424 valueKind = VK_LValue;
3425 type = type.getNonReferenceType();
3426 break;
3427
3428 case Decl::Function: {
3429 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3432 valueKind = VK_PRValue;
3433 break;
3434 }
3435 }
3436
3437 const FunctionType *fty = type->castAs<FunctionType>();
3438
3439 // If we're referring to a function with an __unknown_anytype
3440 // result type, make the entire expression __unknown_anytype.
3441 if (fty->getReturnType() == Context.UnknownAnyTy) {
3443 valueKind = VK_PRValue;
3444 break;
3445 }
3446
3447 // Functions are l-values in C++.
3448 if (getLangOpts().CPlusPlus) {
3449 valueKind = VK_LValue;
3450 break;
3451 }
3452
3453 // C99 DR 316 says that, if a function type comes from a
3454 // function definition (without a prototype), that type is only
3455 // used for checking compatibility. Therefore, when referencing
3456 // the function, we pretend that we don't have the full function
3457 // type.
3458 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3460 fty->getExtInfo());
3461
3462 // Functions are r-values in C.
3463 valueKind = VK_PRValue;
3464 break;
3465 }
3466
3467 case Decl::CXXDeductionGuide:
3468 llvm_unreachable("building reference to deduction guide");
3469
3470 case Decl::MSProperty:
3471 case Decl::MSGuid:
3472 case Decl::TemplateParamObject:
3473 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3474 // capture in OpenMP, or duplicated between host and device?
3475 valueKind = VK_LValue;
3476 break;
3477
3478 case Decl::UnnamedGlobalConstant:
3479 valueKind = VK_LValue;
3480 break;
3481
3482 case Decl::CXXMethod:
3483 // If we're referring to a method with an __unknown_anytype
3484 // result type, make the entire expression __unknown_anytype.
3485 // This should only be possible with a type written directly.
3486 if (const FunctionProtoType *proto =
3487 dyn_cast<FunctionProtoType>(VD->getType()))
3488 if (proto->getReturnType() == Context.UnknownAnyTy) {
3490 valueKind = VK_PRValue;
3491 break;
3492 }
3493
3494 // C++ methods are l-values if static, r-values if non-static.
3495 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3496 valueKind = VK_LValue;
3497 break;
3498 }
3499 [[fallthrough]];
3500
3501 case Decl::CXXConversion:
3502 case Decl::CXXDestructor:
3503 case Decl::CXXConstructor:
3504 valueKind = VK_PRValue;
3505 break;
3506 }
3507
3508 auto *E =
3509 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3510 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3511 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3512 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3513 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3514 // diagnostics).
3515 if (VD->isInvalidDecl() && E)
3516 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3517 return E;
3518}
3519
3520static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3522 Target.resize(CharByteWidth * (Source.size() + 1));
3523 char *ResultPtr = &Target[0];
3524 const llvm::UTF8 *ErrorPtr;
3525 bool success =
3526 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3527 (void)success;
3528 assert(success);
3529 Target.resize(ResultPtr - &Target[0]);
3530}
3531
3534 // Pick the current block, lambda, captured statement or function.
3535 Decl *currentDecl = nullptr;
3536 if (const BlockScopeInfo *BSI = getCurBlock())
3537 currentDecl = BSI->TheDecl;
3538 else if (const LambdaScopeInfo *LSI = getCurLambda())
3539 currentDecl = LSI->CallOperator;
3540 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3541 currentDecl = CSI->TheCapturedDecl;
3542 else
3543 currentDecl = getCurFunctionOrMethodDecl();
3544
3545 if (!currentDecl) {
3546 Diag(Loc, diag::ext_predef_outside_function);
3547 currentDecl = Context.getTranslationUnitDecl();
3548 }
3549
3550 QualType ResTy;
3551 StringLiteral *SL = nullptr;
3552 if (cast<DeclContext>(currentDecl)->isDependentContext())
3553 ResTy = Context.DependentTy;
3554 else {
3555 // Pre-defined identifiers are of type char[x], where x is the length of
3556 // the string.
3557 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3558 unsigned Length = Str.length();
3559
3560 llvm::APInt LengthI(32, Length + 1);
3562 ResTy =
3564 SmallString<32> RawChars;
3566 Str, RawChars);
3567 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3569 /*IndexTypeQuals*/ 0);
3571 /*Pascal*/ false, ResTy, Loc);
3572 } else {
3574 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3576 /*IndexTypeQuals*/ 0);
3578 /*Pascal*/ false, ResTy, Loc);
3579 }
3580 }
3581
3582 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3583 SL);
3584}
3585
3587 SourceLocation LParen,
3588 SourceLocation RParen,
3589 TypeSourceInfo *TSI) {
3590 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3591}
3592
3594 SourceLocation LParen,
3595 SourceLocation RParen,
3596 ParsedType ParsedTy) {
3597 TypeSourceInfo *TSI = nullptr;
3598 QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3599
3600 if (Ty.isNull())
3601 return ExprError();
3602 if (!TSI)
3603 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3604
3605 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3606}
3607
3610
3611 switch (Kind) {
3612 default: llvm_unreachable("Unknown simple primary expr!");
3613 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3614 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3615 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3616 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3617 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3618 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3619 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3620 }
3621
3622 return BuildPredefinedExpr(Loc, IK);
3623}
3624
3626 SmallString<16> CharBuffer;
3627 bool Invalid = false;
3628 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3629 if (Invalid)
3630 return ExprError();
3631
3632 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3633 PP, Tok.getKind());
3634 if (Literal.hadError())
3635 return ExprError();
3636
3637 QualType Ty;
3638 if (Literal.isWide())
3639 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3640 else if (Literal.isUTF8() && getLangOpts().C2x)
3641 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x
3642 else if (Literal.isUTF8() && getLangOpts().Char8)
3643 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3644 else if (Literal.isUTF16())
3645 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3646 else if (Literal.isUTF32())
3647 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3648 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3649 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3650 else
3651 Ty = Context.CharTy; // 'x' -> char in C++;
3652 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3653
3655 if (Literal.isWide())
3657 else if (Literal.isUTF16())
3659 else if (Literal.isUTF32())
3661 else if (Literal.isUTF8())
3663
3664 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3665 Tok.getLocation());
3666
3667 if (Literal.getUDSuffix().empty())
3668 return Lit;
3669
3670 // We're building a user-defined literal.
3671 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3672 SourceLocation UDSuffixLoc =
3673 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3674
3675 // Make sure we're allowed user-defined literals here.
3676 if (!UDLScope)
3677 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3678
3679 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3680 // operator "" X (ch)
3681 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3682 Lit, Tok.getLocation());
3683}
3684
3686 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3687 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3688 Context.IntTy, Loc);
3689}
3690
3692 QualType Ty, SourceLocation Loc) {
3693 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3694
3695 using llvm::APFloat;
3696 APFloat Val(Format);
3697
3698 APFloat::opStatus result = Literal.GetFloatValue(Val);
3699
3700 // Overflow is always an error, but underflow is only an error if
3701 // we underflowed to zero (APFloat reports denormals as underflow).
3702 if ((result & APFloat::opOverflow) ||
3703 ((result & APFloat::opUnderflow) && Val.isZero())) {
3704 unsigned diagnostic;
3705 SmallString<20> buffer;
3706 if (result & APFloat::opOverflow) {
3707 diagnostic = diag::warn_float_overflow;
3708 APFloat::getLargest(Format).toString(buffer);
3709 } else {
3710 diagnostic = diag::warn_float_underflow;
3711 APFloat::getSmallest(Format).toString(buffer);
3712 }
3713
3714 S.Diag(Loc, diagnostic)
3715 << Ty
3716 << StringRef(buffer.data(), buffer.size());
3717 }
3718
3719 bool isExact = (result == APFloat::opOK);
3720 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3721}
3722
3724 assert(E && "Invalid expression");
3725
3726 if (E->isValueDependent())
3727 return false;
3728
3729 QualType QT = E->getType();
3730 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3731 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3732 return true;
3733 }
3734
3735 llvm::APSInt ValueAPS;
3737
3738 if (R.isInvalid())
3739 return true;
3740
3741 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3742 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3743 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3744 << toString(ValueAPS, 10) << ValueIsPositive;
3745 return true;
3746 }
3747
3748 return false;
3749}
3750
3752 // Fast path for a single digit (which is quite common). A single digit
3753 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3754 if (Tok.getLength() == 1) {
3755 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3756 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3757 }
3758
3759 SmallString<128> SpellingBuffer;
3760 // NumericLiteralParser wants to overread by one character. Add padding to
3761 // the buffer in case the token is copied to the buffer. If getSpelling()
3762 // returns a StringRef to the memory buffer, it should have a null char at
3763 // the EOF, so it is also safe.
3764 SpellingBuffer.resize(Tok.getLength() + 1);
3765
3766 // Get the spelling of the token, which eliminates trigraphs, etc.
3767 bool Invalid = false;
3768 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3769 if (Invalid)
3770 return ExprError();
3771
3772 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3775 if (Literal.hadError)
3776 return ExprError();
3777
3778 if (Literal.hasUDSuffix()) {
3779 // We're building a user-defined literal.
3780 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3781 SourceLocation UDSuffixLoc =
3782 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3783
3784 // Make sure we're allowed user-defined literals here.
3785 if (!UDLScope)
3786 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3787
3788 QualType CookedTy;
3789 if (Literal.isFloatingLiteral()) {
3790 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3791 // long double, the literal is treated as a call of the form
3792 // operator "" X (f L)
3793 CookedTy = Context.LongDoubleTy;
3794 } else {
3795 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3796 // unsigned long long, the literal is treated as a call of the form
3797 // operator "" X (n ULL)
3798 CookedTy = Context.UnsignedLongLongTy;
3799 }
3800
3801 DeclarationName OpName =
3803 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3804 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3805
3806 SourceLocation TokLoc = Tok.getLocation();
3807
3808 // Perform literal operator lookup to determine if we're building a raw
3809 // literal or a cooked one.
3810 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3811 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3812 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3813 /*AllowStringTemplatePack*/ false,
3814 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3816 // Lookup failure for imaginary constants isn't fatal, there's still the
3817 // GNU extension producing _Complex types.
3818 break;
3819 case LOLR_Error:
3820 return ExprError();
3821 case LOLR_Cooked: {
3822 Expr *Lit;
3823 if (Literal.isFloatingLiteral()) {
3824 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3825 } else {
3826 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3827 if (Literal.GetIntegerValue(ResultVal))
3828 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3829 << /* Unsigned */ 1;
3830 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3831 Tok.getLocation());
3832 }
3833 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3834 }
3835
3836 case LOLR_Raw: {
3837 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3838 // literal is treated as a call of the form
3839 // operator "" X ("n")
3840 unsigned Length = Literal.getUDSuffixOffset();
3843 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3844 Expr *Lit =
3845 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3847 /*Pascal*/ false, StrTy, &TokLoc, 1);
3848 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3849 }
3850
3851 case LOLR_Template: {
3852 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3853 // template), L is treated as a call fo the form
3854 // operator "" X <'c1', 'c2', ... 'ck'>()
3855 // where n is the source character sequence c1 c2 ... ck.
3856 TemplateArgumentListInfo ExplicitArgs;
3857 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3858 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3859 llvm::APSInt Value(CharBits, CharIsUnsigned);
3860 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3861 Value = TokSpelling[I];
3864 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3865 }
3866 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
3867 &ExplicitArgs);
3868 }
3870 llvm_unreachable("unexpected literal operator lookup result");
3871 }
3872 }
3873
3874 Expr *Res;
3875
3876 if (Literal.isFixedPointLiteral()) {
3877 QualType Ty;
3878
3879 if (Literal.isAccum) {
3880 if (Literal.isHalf) {
3881 Ty = Context.ShortAccumTy;
3882 } else if (Literal.isLong) {
3883 Ty = Context.LongAccumTy;
3884 } else {
3885 Ty = Context.AccumTy;
3886 }
3887 } else if (Literal.isFract) {
3888 if (Literal.isHalf) {
3889 Ty = Context.ShortFractTy;
3890 } else if (Literal.isLong) {
3891 Ty = Context.LongFractTy;
3892 } else {
3893 Ty = Context.FractTy;
3894 }
3895 }
3896
3897 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3898
3899 bool isSigned = !Literal.isUnsigned;
3900 unsigned scale = Context.getFixedPointScale(Ty);
3901 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3902
3903 llvm::APInt Val(bit_width, 0, isSigned);
3904 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3905 bool ValIsZero = Val.isZero() && !Overflowed;
3906
3907 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3908 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3909 // Clause 6.4.4 - The value of a constant shall be in the range of
3910 // representable values for its type, with exception for constants of a
3911 // fract type with a value of exactly 1; such a constant shall denote
3912 // the maximal value for the type.
3913 --Val;
3914 else if (Val.ugt(MaxVal) || Overflowed)
3915 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3916
3918 Tok.getLocation(), scale);
3919 } else if (Literal.isFloatingLiteral()) {
3920 QualType Ty;
3921 if (Literal.isHalf){
3922 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3923 Ty = Context.HalfTy;
3924 else {
3925 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3926 return ExprError();
3927 }
3928 } else if (Literal.isFloat)
3929 Ty = Context.FloatTy;
3930 else if (Literal.isLong)
3931 Ty = Context.LongDoubleTy;
3932 else if (Literal.isFloat16)
3933 Ty = Context.Float16Ty;
3934 else if (Literal.isFloat128)
3935 Ty = Context.Float128Ty;
3936 else
3937 Ty = Context.DoubleTy;
3938
3939 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3940
3941 if (Ty == Context.DoubleTy) {
3942 if (getLangOpts().SinglePrecisionConstants) {
3943 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3944 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3945 }
3946 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3947 "cl_khr_fp64", getLangOpts())) {
3948 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3949 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3951 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3952 }
3953 }
3954 } else if (!Literal.isIntegerLiteral()) {
3955 return ExprError();
3956 } else {
3957 QualType Ty;
3958
3959 // 'z/uz' literals are a C++23 feature.
3960 if (Literal.isSizeT)
3963 ? diag::warn_cxx20_compat_size_t_suffix
3964 : diag::ext_cxx23_size_t_suffix
3965 : diag::err_cxx23_size_t_suffix);
3966
3967 // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3968 // but we do not currently support the suffix in C++ mode because it's not
3969 // entirely clear whether WG21 will prefer this suffix to return a library
3970 // type such as std::bit_int instead of returning a _BitInt.
3971 if (Literal.isBitInt && !getLangOpts().CPlusPlus)
3973 ? diag::warn_c2x_compat_bitint_suffix
3974 : diag::ext_c2x_bitint_suffix);
3975
3976 // Get the value in the widest-possible width. What is "widest" depends on
3977 // whether the literal is a bit-precise integer or not. For a bit-precise
3978 // integer type, try to scan the source to determine how many bits are
3979 // needed to represent the value. This may seem a bit expensive, but trying
3980 // to get the integer value from an overly-wide APInt is *extremely*
3981 // expensive, so the naive approach of assuming
3982 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3983 unsigned BitsNeeded =
3984 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3985 Literal.getLiteralDigits(), Literal.getRadix())
3987 llvm::APInt ResultVal(BitsNeeded, 0);
3988
3989 if (Literal.GetIntegerValue(ResultVal)) {
3990 // If this value didn't fit into uintmax_t, error and force to ull.
3991 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3992 << /* Unsigned */ 1;
3994 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3995 "long long is not intmax_t?");
3996 } else {
3997 // If this value fits into a ULL, try to figure out what else it fits into
3998 // according to the rules of C99 6.4.4.1p5.
3999
4000 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4001 // be an unsigned int.
4002 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4003
4004 // Check from smallest to largest, picking the smallest type we can.
4005 unsigned Width = 0;
4006
4007 // Microsoft specific integer suffixes are explicitly sized.
4008 if (Literal.MicrosoftInteger) {
4009 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4010 Width = 8;
4011 Ty = Context.CharTy;
4012 } else {
4013 Width = Literal.MicrosoftInteger;
4014 Ty = Context.getIntTypeForBitwidth(Width,
4015 /*Signed=*/!Literal.isUnsigned);
4016 }
4017 }
4018
4019 // Bit-precise integer literals are automagically-sized based on the
4020 // width required by the literal.
4021 if (Literal.isBitInt) {
4022 // The signed version has one more bit for the sign value. There are no
4023 // zero-width bit-precise integers, even if the literal value is 0.
4024 Width = std::max(ResultVal.getActiveBits(), 1u) +
4025 (Literal.isUnsigned ? 0u : 1u);
4026
4027 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4028 // and reset the type to the largest supported width.
4029 unsigned int MaxBitIntWidth =
4031 if (Width > MaxBitIntWidth) {
4032 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4033 << Literal.isUnsigned;
4034 Width = MaxBitIntWidth;
4035 }
4036
4037 // Reset the result value to the smaller APInt and select the correct
4038 // type to be used. Note, we zext even for signed values because the
4039 // literal itself is always an unsigned value (a preceeding - is a
4040 // unary operator, not part of the literal).
4041 ResultVal = ResultVal.zextOrTrunc(Width);
4042 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4043 }
4044
4045 // Check C++23 size_t literals.
4046 if (Literal.isSizeT) {
4047 assert(!Literal.MicrosoftInteger &&
4048 "size_t literals can't be Microsoft literals");
4049 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4051
4052 // Does it fit in size_t?
4053 if (ResultVal.isIntN(SizeTSize)) {
4054 // Does it fit in ssize_t?
4055 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4057 else if (AllowUnsigned)
4058 Ty = Context.getSizeType();
4059 Width = SizeTSize;
4060 }
4061 }
4062
4063 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4064 !Literal.isSizeT) {
4065 // Are int/unsigned possibilities?
4066 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4067
4068 // Does it fit in a unsigned int?
4069 if (ResultVal.isIntN(IntSize)) {
4070 // Does it fit in a signed int?
4071 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4072 Ty = Context.IntTy;
4073 else if (AllowUnsigned)
4075 Width = IntSize;
4076 }
4077 }
4078
4079 // Are long/unsigned long possibilities?
4080 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4081 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4082
4083 // Does it fit in a unsigned long?
4084 if (ResultVal.isIntN(LongSize)) {
4085 // Does it fit in a signed long?
4086 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4087 Ty = Context.LongTy;
4088 else if (AllowUnsigned)
4090 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4091 // is compatible.
4092 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4093 const unsigned LongLongSize =
4095 Diag(Tok.getLocation(),
4097 ? Literal.isLong
4098 ? diag::warn_old_implicitly_unsigned_long_cxx
4099 : /*C++98 UB*/ diag::
4100 ext_old_implicitly_unsigned_long_cxx
4101 : diag::warn_old_implicitly_unsigned_long)
4102 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4103 : /*will be ill-formed*/ 1);
4105 }
4106 Width = LongSize;
4107 }
4108 }
4109
4110 // Check long long if needed.
4111 if (Ty.isNull() && !Literal.isSizeT) {
4112 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4113
4114 // Does it fit in a unsigned long long?
4115 if (ResultVal.isIntN(LongLongSize)) {
4116 // Does it fit in a signed long long?
4117 // To be compatible with MSVC, hex integer literals ending with the
4118 // LL or i64 suffix are always signed in Microsoft mode.
4119 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4120 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4121 Ty = Context.LongLongTy;
4122 else if (AllowUnsigned)
4124 Width = LongLongSize;
4125
4126 // 'long long' is a C99 or C++11 feature, whether the literal
4127 // explicitly specified 'long long' or we needed the extra width.
4128 if (getLangOpts().CPlusPlus)
4129 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4130 ? diag::warn_cxx98_compat_longlong
4131 : diag::ext_cxx11_longlong);
4132 else if (!getLangOpts().C99)
4133 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4134 }
4135 }
4136
4137 // If we still couldn't decide a type, we either have 'size_t' literal
4138 // that is out of range, or a decimal literal that does not fit in a
4139 // signed long long and has no U suffix.
4140 if (Ty.isNull()) {
4141 if (Literal.isSizeT)
4142 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4143 << Literal.isUnsigned;
4144 else
4145 Diag(Tok.getLocation(),
4146 diag::ext_integer_literal_too_large_for_signed);
4149 }
4150
4151 if (ResultVal.getBitWidth() != Width)
4152 ResultVal = ResultVal.trunc(Width);
4153 }
4154 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4155 }
4156
4157 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4158 if (Literal.isImaginary) {
4159 Res = new (Context) ImaginaryLiteral(Res,
4161
4162 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4163 }
4164 return Res;
4165}
4166
4168 assert(E && "ActOnParenExpr() missing expr");
4169 QualType ExprTy = E->getType();
4170 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4171 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4172 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4173 return new (Context) ParenExpr(L, R, E);
4174}
4175
4177 SourceLocation Loc,
4178 SourceRange ArgRange) {
4179 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4180 // scalar or vector data type argument..."
4181 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4182 // type (C99 6.2.5p18) or void.
4183 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4184 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4185 << T << ArgRange;
4186 return true;
4187 }
4188
4189 assert((T->isVoidType() || !T->isIncompleteType()) &&
4190 "Scalar types should always be complete");
4191 return false;
4192}
4193
4195 SourceLocation Loc,
4196 SourceRange ArgRange,
4197 UnaryExprOrTypeTrait TraitKind) {
4198 // Invalid types must be hard errors for SFINAE in C++.
4199 if (S.LangOpts.CPlusPlus)
4200 return true;
4201
4202 // C99 6.5.3.4p1:
4203 if (T->isFunctionType() &&
4204 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4205 TraitKind == UETT_PreferredAlignOf)) {
4206 // sizeof(function)/alignof(function) is allowed as an extension.
4207 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4208 << getTraitSpelling(TraitKind) << ArgRange;
4209 return false;
4210 }
4211
4212 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4213 // this is an error (OpenCL v1.1 s6.3.k)
4214 if (T->isVoidType()) {
4215 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4216 : diag::ext_sizeof_alignof_void_type;
4217 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4218 return false;
4219 }
4220
4221 return true;
4222}
4223
4225 SourceLocation Loc,
4226 SourceRange ArgRange,
4227 UnaryExprOrTypeTrait TraitKind) {
4228 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4229 // runtime doesn't allow it.
4231 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4232 << T << (TraitKind == UETT_SizeOf)
4233 << ArgRange;
4234 return true;
4235 }
4236
4237 return false;
4238}
4239
4240/// Check whether E is a pointer from a decayed array type (the decayed
4241/// pointer type is equal to T) and emit a warning if it is.
4243 const Expr *E) {
4244 // Don't warn if the operation changed the type.
4245 if (T != E->getType())
4246 return;
4247
4248 // Now look for array decays.
4249 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4250 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4251 return;
4252
4253 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4254 << ICE->getType()
4255 << ICE->getSubExpr()->getType();
4256}
4257
4258/// Check the constraints on expression operands to unary type expression
4259/// and type traits.
4260///
4261/// Completes any types necessary and validates the constraints on the operand
4262/// expression. The logic mostly mirrors the type-based overload, but may modify
4263/// the expression as it completes the type for that expression through template
4264/// instantiation, etc.
4266 UnaryExprOrTypeTrait ExprKind) {
4267 QualType ExprTy = E->getType();
4268 assert(!ExprTy->isReferenceType());
4269
4270 bool IsUnevaluatedOperand =
4271 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4272 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4273 if (IsUnevaluatedOperand) {
4275 if (Result.isInvalid())
4276 return true;
4277 E = Result.get();
4278 }
4279
4280 // The operand for sizeof and alignof is in an unevaluated expression context,
4281 // so side effects could result in unintended consequences.
4282 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4283 // used to build SFINAE gadgets.
4284 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4285 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4287 !E->getType()->isVariableArrayType() &&
4288 E->HasSideEffects(Context, false))
4289 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4290
4291 if (ExprKind == UETT_VecStep)
4292 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4293 E->getSourceRange());
4294
4295 // Explicitly list some types as extensions.
4296 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4297 E->getSourceRange(), ExprKind))
4298 return false;
4299
4300 // 'alignof' applied to an expression only requires the base element type of
4301 // the expression to be complete. 'sizeof' requires the expression's type to
4302 // be complete (and will attempt to complete it if it's an array of unknown
4303 // bound).
4304 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4307 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4308 getTraitSpelling(ExprKind), E->getSourceRange()))
4309 return true;
4310 } else {
4312 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4313 getTraitSpelling(ExprKind), E->getSourceRange()))
4314 return true;
4315 }
4316
4317 // Completing the expression's type may have changed it.
4318 ExprTy = E->getType();
4319 assert(!ExprTy->isReferenceType());
4320
4321 if (ExprTy->isFunctionType()) {
4322 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4323 << getTraitSpelling(ExprKind) << E->getSourceRange();
4324 return true;
4325 }
4326
4327 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4328 E->getSourceRange(), ExprKind))
4329 return true;
4330
4331 if (ExprKind == UETT_SizeOf) {
4332 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4333 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4334 QualType OType = PVD->getOriginalType();
4335 QualType Type = PVD->getType();
4336 if (Type->isPointerType() && OType->isArrayType()) {
4337 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4338 << Type << OType;
4339 Diag(PVD->getLocation(), diag::note_declared_at);
4340 }
4341 }
4342 }
4343
4344 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4345 // decays into a pointer and returns an unintended result. This is most
4346 // likely a typo for "sizeof(array) op x".
4347 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4348 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4349 BO->getLHS());
4350 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4351 BO->getRHS());
4352 }
4353 }
4354
4355 return false;
4356}
4357
4358static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4359 // Cannot know anything else if the expression is dependent.
4360 if (E->isTypeDependent())
4361 return false;
4362
4363 if (E->getObjectKind() == OK_BitField) {
4364 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4365 << 1 << E->getSourceRange();
4366 return true;
4367 }
4368
4369 ValueDecl *D = nullptr;
4370 Expr *Inner = E->IgnoreParens();
4371 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4372 D = DRE->getDecl();
4373 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4374 D = ME->getMemberDecl();
4375 }
4376
4377 // If it's a field, require the containing struct to have a
4378 // complete definition so that we can compute the layout.
4379 //
4380 // This can happen in C++11 onwards, either by naming the member
4381 // in a way that is not transformed into a member access expression
4382 // (in an unevaluated operand, for instance), or by naming the member
4383 // in a trailing-return-type.
4384 //
4385 // For the record, since __alignof__ on expressions is a GCC
4386 // extension, GCC seems to permit this but always gives the
4387 // nonsensical answer 0.
4388 //
4389 // We don't really need the layout here --- we could instead just
4390 // directly check for all the appropriate alignment-lowing
4391 // attributes --- but that would require duplicating a lot of
4392 // logic that just isn't worth duplicating for such a marginal
4393 // use-case.
4394 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4395 // Fast path this check, since we at least know the record has a
4396 // definition if we can find a member of it.
4397 if (!FD->getParent()->isCompleteDefinition()) {
4398 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4399 << E->getSourceRange();
4400 return true;
4401 }
4402
4403 // Otherwise, if it's a field, and the field doesn't have
4404 // reference type, then it must have a complete type (or be a
4405 // flexible array member, which we explicitly want to
4406 // white-list anyway), which makes the following checks trivial.
4407 if (!FD->getType()->isReferenceType())
4408 return false;
4409 }
4410
4411 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4412}
4413
4415 E = E->IgnoreParens();
4416
4417 // Cannot know anything else if the expression is dependent.
4418 if (E->isTypeDependent())
4419 return false;
4420
4421 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4422}
4423
4425 CapturingScopeInfo *CSI) {
4426 assert(T->isVariablyModifiedType());
4427 assert(CSI != nullptr);
4428
4429 // We're going to walk down into the type and look for VLA expressions.
4430 do {
4431 const Type *Ty = T.getTypePtr();
4432 switch (Ty->getTypeClass()) {
4433#define TYPE(Class, Base)
4434#define ABSTRACT_TYPE(Class, Base)
4435#define NON_CANONICAL_TYPE(Class, Base)
4436#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4437#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4438#include "clang/AST/TypeNodes.inc"
4439 T = QualType();
4440 break;
4441 // These types are never variably-modified.
4442 case Type::Builtin:
4443 case Type::Complex:
4444 case Type::Vector:
4445 case Type::ExtVector:
4446 case Type::ConstantMatrix:
4447 case Type::Record:
4448 case Type::Enum:
4449 case Type::TemplateSpecialization:
4450 case Type::ObjCObject:
4451 case Type::ObjCInterface:
4452 case Type::ObjCObjectPointer:
4453 case Type::ObjCTypeParam:
4454 case Type::Pipe:
4455 case Type::BitInt:
4456 llvm_unreachable("type class is never variably-modified!");
4457 case Type::Elaborated:
4458 T = cast<ElaboratedType>(Ty)->getNamedType();
4459 break;
4460 case Type::Adjusted:
4461 T = cast<AdjustedType>(Ty)->getOriginalType();
4462 break;
4463 case Type::Decayed:
4464 T = cast<DecayedType>(Ty)->getPointeeType();
4465 break;
4466 case Type::Pointer:
4467 T = cast<PointerType>(Ty)->getPointeeType();
4468 break;
4469 case Type::BlockPointer:
4470 T = cast<BlockPointerType>(Ty)->getPointeeType();
4471 break;
4472 case Type::LValueReference:
4473 case Type::RValueReference:
4474 T = cast<ReferenceType>(Ty)->getPointeeType();
4475 break;
4476 case Type::MemberPointer:
4477 T = cast<MemberPointerType>(Ty)->getPointeeType();
4478 break;
4479 case Type::ConstantArray:
4480 case Type::IncompleteArray:
4481 // Losing element qualification here is fine.
4482 T = cast<ArrayType>(Ty)->getElementType();
4483 break;
4484 case Type::VariableArray: {
4485 // Losing element qualification here is fine.
4486 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4487
4488 // Unknown size indication requires no size computation.
4489 // Otherwise, evaluate and record it.
4490 auto Size = VAT->getSizeExpr();
4491 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4492 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4493 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4494
4495 T = VAT->getElementType();
4496 break;
4497 }
4498 case Type::FunctionProto:
4499 case Type::FunctionNoProto:
4500 T = cast<FunctionType>(Ty)->getReturnType();
4501 break;
4502 case Type::Paren:
4503 case Type::TypeOf:
4504 case Type::UnaryTransform:
4505 case Type::Attributed:
4506 case Type::BTFTagAttributed:
4507 case Type::SubstTemplateTypeParm:
4508 case Type::MacroQualified:
4509 // Keep walking after single level desugaring.
4510 T = T.getSingleStepDesugaredType(Context);
4511 break;
4512 case Type::Typedef:
4513 T = cast<TypedefType>(Ty)->desugar();
4514 break;
4515 case Type::Decltype:
4516 T = cast<DecltypeType>(Ty)->desugar();
4517 break;
4518 case Type::Using:
4519 T = cast<UsingType>(Ty)->desugar();
4520 break;
4521 case Type::Auto:
4522 case Type::DeducedTemplateSpecialization:
4523 T = cast<DeducedType>(Ty)->getDeducedType();
4524 break;
4525 case Type::TypeOfExpr:
4526 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4527 break;
4528 case Type::Atomic:
4529 T = cast<AtomicType>(Ty)->getValueType();
4530 break;
4531 }
4532 } while (!T.isNull() && T->isVariablyModifiedType());
4533}
4534
4535/// Check the constraints on operands to unary expression and type
4536/// traits.
4537///
4538/// This will complete any types necessary, and validate the various constraints
4539/// on those operands.
4540///
4541/// The UsualUnaryConversions() function is *not* called by this routine.
4542/// C99 6.3.2.1p[2-4] all state:
4543/// Except when it is the operand of the sizeof operator ...
4544///
4545/// C++ [expr.sizeof]p4
4546/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4547/// standard conversions are not applied to the operand of sizeof.
4548///
4549/// This policy is followed for all of the unary trait expressions.
4551 SourceLocation OpLoc,
4552 SourceRange ExprRange,
4553 UnaryExprOrTypeTrait ExprKind,
4554 StringRef KWName) {
4555 if (ExprType->isDependentType())
4556 return false;
4557
4558 // C++ [expr.sizeof]p2:
4559 // When applied to a reference or a reference type, the result
4560 // is the size of the referenced type.
4561 // C++11 [expr.alignof]p3:
4562 // When alignof is applied to a reference type, the result
4563 // shall be the alignment of the referenced type.
4564 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4565 ExprType = Ref->getPointeeType();
4566
4567 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4568 // When alignof or _Alignof is applied to an array type, the result
4569 // is the alignment of the element type.
4570 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4571 ExprKind == UETT_OpenMPRequiredSimdAlign)
4572 ExprType = Context.getBaseElementType(ExprType);
4573
4574 if (ExprKind == UETT_VecStep)
4575 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4576
4577 // Explicitly list some types as extensions.
4578 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4579 ExprKind))
4580 return false;
4581
4583 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4584 KWName, ExprRange))
4585 return true;
4586
4587 if (ExprType->isFunctionType()) {
4588 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4589 return true;
4590 }
4591
4592 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4593 ExprKind))
4594 return true;
4595
4596 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4597 if (auto *TT = ExprType->getAs<TypedefType>()) {
4598 for (auto I = FunctionScopes.rbegin(),
4599 E = std::prev(FunctionScopes.rend());
4600 I != E; ++I) {
4601 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4602 if (CSI == nullptr)
4603 break;
4604 DeclContext *DC = nullptr;
4605 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4606 DC = LSI->CallOperator;
4607 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4608 DC = CRSI->TheCapturedDecl;
4609 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4610 DC = BSI->TheDecl;
4611 if (DC) {
4612 if (DC->containsDecl(TT->getDecl()))
4613 break;
4614 captureVariablyModifiedType(Context, ExprType, CSI);
4615 }
4616 }
4617 }
4618 }
4619
4620 return false;
4621}
4622
4623/// Build a sizeof or alignof expression given a type operand.
4625 SourceLocation OpLoc,
4626 UnaryExprOrTypeTrait ExprKind,
4627 SourceRange R) {
4628 if (!TInfo)
4629 return ExprError();
4630
4631 QualType T = TInfo->getType();
4632
4633 if (!T->isDependentType() &&
4634 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4635 getTraitSpelling(ExprKind)))
4636 return ExprError();
4637
4638 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4639 // properly deal with VLAs in nested calls of sizeof and typeof.
4640 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4641 TInfo->getType()->isVariablyModifiedType())
4642 TInfo = TransformToPotentiallyEvaluated(TInfo);
4643
4644 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4645 return new (Context) UnaryExprOrTypeTraitExpr(
4646 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4647}
4648
4649/// Build a sizeof or alignof expression given an expression
4650/// operand.
4653 UnaryExprOrTypeTrait ExprKind) {
4655 if (PE.isInvalid())
4656 return ExprError();
4657
4658 E = PE.get();
4659
4660 // Verify that the operand is valid.
4661 bool isInvalid = false;
4662 if (E->isTypeDependent()) {
4663 // Delay type-checking for type-dependent expressions.
4664 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4665 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4666 } else if (ExprKind == UETT_VecStep) {
4668 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4669 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4670 isInvalid = true;
4671 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4672 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4673 isInvalid = true;
4674 } else {
4676 }
4677
4678 if (isInvalid)
4679 return ExprError();
4680
4681 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4683 if (PE.isInvalid()) return ExprError();
4684 E = PE.get();
4685 }
4686
4687 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4688 return new (Context) UnaryExprOrTypeTraitExpr(
4689 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4690}
4691
4692/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4693/// expr and the same for @c alignof and @c __alignof
4694/// Note that the ArgRange is invalid if isType is false.
4697 UnaryExprOrTypeTrait ExprKind, bool IsType,
4698 void *TyOrEx, SourceRange ArgRange) {
4699 // If error parsing type, ignore.
4700 if (!TyOrEx) return ExprError();
4701
4702 if (IsType) {
4703 TypeSourceInfo *TInfo;
4704 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4705 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4706 }
4707
4708 Expr *ArgEx = (Expr *)TyOrEx;
4709 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4710 return Result;
4711}
4712
4714 SourceLocation OpLoc, SourceRange R) {
4715 if (!TInfo)
4716 return true;
4717 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4718 UETT_AlignOf, KWName);
4719}
4720
4721/// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
4722/// _Alignas(type-name) .
4723/// [dcl.align] An alignment-specifier of the form
4724/// alignas(type-id) has the same effect as alignas(alignof(type-id)).
4725///
4726/// [N1570 6.7.5] _Alignas(type-name) is equivalent to
4727/// _Alignas(_Alignof(type-name)).
4729 SourceLocation OpLoc, SourceRange R) {
4730 TypeSourceInfo *TInfo;
4732 &TInfo);
4733 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4734}
4735
4737 bool IsReal) {
4738 if (V.get()->isTypeDependent())
4739 return S.Context.DependentTy;
4740
4741 // _Real and _Imag are only l-values for normal l-values.
4742 if (V.get()->getObjectKind() != OK_Ordinary) {
4743 V = S.DefaultLvalueConversion(V.get());
4744 if (V.isInvalid())
4745 return QualType();
4746 }
4747
4748 // These operators return the element type of a complex type.
4749 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4750 return CT->getElementType();
4751
4752 // Otherwise they pass through real integer and floating point types here.
4753 if (V.get()->getType()->isArithmeticType())
4754 return V.get()->getType();
4755
4756 // Test for placeholders.
4757 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4758 if (PR.isInvalid()) return QualType();
4759 if (PR.get() != V.get()) {
4760 V = PR;
4761 return CheckRealImagOperand(S, V, Loc, IsReal);
4762 }
4763
4764 // Reject anything else.
4765 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4766 << (IsReal ? "__real" : "__imag");
4767 return QualType();
4768}
4769
4770
4771
4774 tok::TokenKind Kind, Expr *Input) {
4776 switch (Kind) {
4777 default: llvm_unreachable("Unknown unary op!");
4778 case tok::plusplus: Opc = UO_PostInc; break;
4779 case tok::minusminus: Opc = UO_PostDec; break;
4780 }
4781
4782 // Since this might is a postfix expression, get rid of ParenListExprs.
4784 if (Result.isInvalid()) return ExprError();
4785 Input = Result.get();
4786
4787 return BuildUnaryOp(S, OpLoc, Opc, Input);
4788}
4789
4790/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4791///
4792/// \return true on error
4794 SourceLocation opLoc,
4795 Expr *op) {
4796 assert(op->getType()->isObjCObjectPointerType());
4798 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4799 return false;
4800
4801 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4802 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4803 << op->getSourceRange();
4804 return true;
4805}
4806
4808 auto *BaseNoParens = Base->IgnoreParens();
4809 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4810 return MSProp->getPropertyDecl()->getType()->isArrayType();
4811 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4812}
4813
4814// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4815// Typically this is DependentTy, but can sometimes be more precise.
4816//
4817// There are cases when we could determine a non-dependent type:
4818// - LHS and RHS may have non-dependent types despite being type-dependent
4819// (e.g. unbounded array static members of the current instantiation)
4820// - one may be a dependent-sized array with known element type
4821// - one may be a dependent-typed valid index (enum in current instantiation)
4822//
4823// We *always* return a dependent type, in such cases it is DependentTy.
4824// This avoids creating type-dependent expressions with non-dependent types.
4825// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4827 const ASTContext &Ctx) {
4828 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4829 QualType LTy = LHS->getType(), RTy = RHS->getType();
4831 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4832 if (const PointerType *PT = LTy->getAs<PointerType>())
4833 Result = PT->getPointeeType();
4834 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4835 Result = AT->getElementType();
4836 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4837 if (const PointerType *PT = RTy->getAs<PointerType>())
4838 Result = PT->getPointeeType();
4839 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4840 Result = AT->getElementType();
4841 }
4842 // Ensure we return a dependent type.
4843 return Result->isDependentType() ? Result : Ctx.DependentTy;
4844}
4845
4846static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4847
4849 SourceLocation lbLoc,
4850 MultiExprArg ArgExprs,
4851 SourceLocation rbLoc) {
4852
4853 if (base && !base->getType().isNull() &&
4854 base->hasPlaceholderType(BuiltinType::OMPArraySection))
4855 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4856 SourceLocation(), /*Length*/ nullptr,
4857 /*Stride=*/nullptr, rbLoc);
4858
4859 // Since this might be a postfix expression, get rid of ParenListExprs.
4860 if (isa<ParenListExpr>(base)) {
4862 if (result.isInvalid())
4863 return ExprError();
4864 base = result.get();
4865 }
4866
4867 // Check if base and idx form a MatrixSubscriptExpr.
4868 //
4869 // Helper to check for comma expressions, which are not allowed as indices for
4870 // matrix subscript expressions.
4871 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4872 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4873 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4874 << SourceRange(base->getBeginLoc(), rbLoc);
4875 return true;
4876 }
4877 return false;
4878 };
4879 // The matrix subscript operator ([][])is considered a single operator.
4880 // Separating the index expressions by parenthesis is not allowed.
4881 if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4882 !isa<MatrixSubscriptExpr>(base)) {
4883 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4884 << SourceRange(base->getBeginLoc(), rbLoc);
4885 return ExprError();
4886 }
4887 // If the base is a MatrixSubscriptExpr, try to create a new
4888 // MatrixSubscriptExpr.
4889 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4890 if (matSubscriptE) {
4891 assert(ArgExprs.size() == 1);
4892 if (CheckAndReportCommaError(ArgExprs.front()))
4893 return ExprError();
4894
4895 assert(matSubscriptE->isIncomplete() &&
4896 "base has to be an incomplete matrix subscript");
4897 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4898 matSubscriptE->getRowIdx(),
4899 ArgExprs.front(), rbLoc);
4900 }
4901
4902 // Handle any non-overload placeholder types in the base and index
4903 // expressions. We can't handle overloads here because the other
4904 // operand might be an overloadable type, in which case the overload
4905 // resolution for the operator overload should get the first crack
4906 // at the overload.
4907 bool IsMSPropertySubscript = false;
4908 if (base->getType()->isNonOverloadPlaceholderType()) {
4909 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4910 if (!IsMSPropertySubscript) {
4911 ExprResult result = CheckPlaceholderExpr(base);
4912 if (result.isInvalid())
4913 return ExprError();
4914 base = result.get();
4915 }
4916 }
4917
4918 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4919 if (base->getType()->isMatrixType()) {
4920 assert(ArgExprs.size() == 1);
4921 if (CheckAndReportCommaError(ArgExprs.front()))
4922 return ExprError();
4923
4924 return