clang 24.0.0git
CIRGenExprScalar.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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// Emit Expr nodes with scalar CIR types as CIR code.
10//
11//===----------------------------------------------------------------------===//
12
15#include "CIRGenFunction.h"
16#include "CIRGenValue.h"
17
18#include "clang/AST/Expr.h"
23
24#include "mlir/Dialect/Ptr/IR/MemorySpaceInterfaces.h"
25#include "mlir/IR/Location.h"
26#include "mlir/IR/Value.h"
27
28#include <cassert>
29#include <numeric>
30#include <utility>
31
32using namespace clang;
33using namespace clang::CIRGen;
34
35namespace {
36
37struct BinOpInfo {
38 mlir::Value lhs;
39 mlir::Value rhs;
40 SourceRange loc;
41 QualType fullType; // Type of operands and result
42 QualType compType; // Type used for computations. Element type
43 // for vectors, otherwise same as FullType.
44 BinaryOperator::Opcode opcode; // Opcode of BinOp to perform
45 FPOptions fpFeatures;
46 const Expr *e; // Entire expr, for error unsupported. May not be binop.
47
48 /// Check if the binop computes a division or a remainder.
49 bool isDivRemOp() const {
50 return opcode == BO_Div || opcode == BO_Rem || opcode == BO_DivAssign ||
51 opcode == BO_RemAssign;
52 }
53
54 /// Check if the binop can result in integer overflow.
55 bool mayHaveIntegerOverflow() const {
56 // Without constant input, we can't rule out overflow.
57 auto lhsci = lhs.getDefiningOp<cir::ConstantOp>();
58 auto rhsci = rhs.getDefiningOp<cir::ConstantOp>();
59 if (!lhsci || !rhsci)
60 return true;
61
63 // TODO(cir): For now we just assume that we might overflow
64 return true;
65 }
66
67 /// Check if at least one operand is a fixed point type. In such cases,
68 /// this operation did not follow usual arithmetic conversion and both
69 /// operands might not be of the same type.
70 bool isFixedPointOp() const {
71 // We cannot simply check the result type since comparison operations
72 // return an int.
73 if (const auto *binOp = llvm::dyn_cast<BinaryOperator>(e)) {
74 QualType lhstype = binOp->getLHS()->getType();
75 QualType rhstype = binOp->getRHS()->getType();
76 return lhstype->isFixedPointType() || rhstype->isFixedPointType();
77 }
78 if (const auto *unop = llvm::dyn_cast<UnaryOperator>(e))
79 return unop->getSubExpr()->getType()->isFixedPointType();
80 return false;
81 }
82};
83
84class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
85 CIRGenFunction &cgf;
86 CIRGenBuilderTy &builder;
87 // Unlike classic codegen we set this to false or use std::exchange to read
88 // the value instead of calling TestAndClearIgnoreResultAssign to make it
89 // explicit when the value is used
90 bool ignoreResultAssign;
91
92public:
93 ScalarExprEmitter(CIRGenFunction &cgf, CIRGenBuilderTy &builder,
94 bool ignoreResultAssign = false)
95 : cgf(cgf), builder(builder), ignoreResultAssign(ignoreResultAssign) {}
96
97 //===--------------------------------------------------------------------===//
98 // Utilities
99 //===--------------------------------------------------------------------===//
100 mlir::Type convertType(QualType ty) { return cgf.convertType(ty); }
101
102 mlir::Value emitComplexToScalarConversion(mlir::Location loc,
103 mlir::Value value, CastKind kind,
104 QualType destTy);
105
106 mlir::Value emitNullValue(QualType ty, mlir::Location loc) {
107 return cgf.cgm.emitNullConstant(ty, loc);
108 }
109
110 mlir::Value emitPromotedValue(mlir::Value result, QualType promotionType) {
111 return builder.createFloatingCast(result, cgf.convertType(promotionType));
112 }
113
114 mlir::Value emitUnPromotedValue(mlir::Value result, QualType exprType) {
115 return builder.createFloatingCast(result, cgf.convertType(exprType));
116 }
117
118 mlir::Value emitPromoted(const Expr *e, QualType promotionType);
119
120 mlir::Value maybePromoteBoolResult(mlir::Value value,
121 mlir::Type dstTy) const {
122 if (mlir::isa<cir::IntType>(dstTy))
123 return builder.createBoolToInt(value, dstTy);
124 if (mlir::isa<cir::BoolType>(dstTy))
125 return value;
126 llvm_unreachable("Can only promote integer or boolean types");
127 }
128
129 //===--------------------------------------------------------------------===//
130 // Visitor Methods
131 //===--------------------------------------------------------------------===//
132
133 mlir::Value Visit(Expr *e) {
134 return StmtVisitor<ScalarExprEmitter, mlir::Value>::Visit(e);
135 }
136
137 mlir::Value VisitStmt(Stmt *s) {
138 llvm_unreachable("Statement passed to ScalarExprEmitter");
139 }
140
141 mlir::Value VisitExpr(Expr *e) {
142 cgf.getCIRGenModule().errorNYI(
143 e->getSourceRange(), "scalar expression kind: ", e->getStmtClassName());
144 return {};
145 }
146
147 mlir::Value VisitConstantExpr(ConstantExpr *e) {
148 // A constant expression of type 'void' generates no code and produces no
149 // value.
150 if (e->getType()->isVoidType())
151 return {};
152
153 if (mlir::Attribute result = ConstantEmitter(cgf).tryEmitConstantExpr(e)) {
154 if (e->isGLValue()) {
155 cgf.cgm.errorNYI(e->getSourceRange(),
156 "ScalarExprEmitter: constant expr GL Value");
157 return {};
158 }
159
160 return builder.getConstant(cgf.getLoc(e->getSourceRange()),
161 mlir::cast<mlir::TypedAttr>(result));
162 }
163
164 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: constant expr");
165 return {};
166 }
167
168 mlir::Value VisitPackIndexingExpr(PackIndexingExpr *e) {
169 return Visit(e->getSelectedExpr());
170 }
171
172 mlir::Value VisitParenExpr(ParenExpr *pe) { return Visit(pe->getSubExpr()); }
173
174 mlir::Value VisitGenericSelectionExpr(GenericSelectionExpr *ge) {
175 return Visit(ge->getResultExpr());
176 }
177
178 /// Emits the address of the l-value, then loads and returns the result.
179 mlir::Value emitLoadOfLValue(const Expr *e) {
180 LValue lv = cgf.emitLValue(e);
181 // FIXME: add some akin to EmitLValueAlignmentAssumption(E, V);
182 return cgf.emitLoadOfLValue(lv, e->getExprLoc()).getValue();
183 }
184
185 mlir::Value VisitCoawaitExpr(CoawaitExpr *s) {
186 return cgf.emitCoawaitExpr(*s).getValue();
187 }
188
189 mlir::Value VisitCoyieldExpr(CoyieldExpr *e) {
190 return cgf.emitCoyieldExpr(*e).getValue();
191 }
192
193 mlir::Value VisitUnaryCoawait(const UnaryOperator *e) {
194 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: unary coawait");
195 return {};
196 }
197
198 mlir::Value emitLoadOfLValue(LValue lv, SourceLocation loc) {
199 return cgf.emitLoadOfLValue(lv, loc).getValue();
200 }
201
202 // l-values
203 mlir::Value VisitDeclRefExpr(DeclRefExpr *e) {
204 if (CIRGenFunction::ConstantEmission constant = cgf.tryEmitAsConstant(e))
205 return cgf.emitScalarConstant(constant, e);
206
207 return emitLoadOfLValue(e);
208 }
209
210 mlir::Value VisitAddrLabelExpr(const AddrLabelExpr *e) {
211 auto func = cast<cir::FuncOp>(cgf.curFn);
212 cir::BlockAddrInfoAttr blockInfoAttr = cir::BlockAddrInfoAttr::get(
213 &cgf.getMLIRContext(), func.getSymName(), e->getLabel()->getName());
214 // GotoSolver collects this cir.block_address op after FlattenCFG to keep
215 // the label and wire it as an indirect-branch successor.
216 return cir::BlockAddressOp::create(builder, cgf.getLoc(e->getSourceRange()),
217 cgf.convertType(e->getType()),
218 blockInfoAttr);
219 }
220
221 mlir::Value VisitIntegerLiteral(const IntegerLiteral *e) {
222 mlir::Type type = cgf.convertType(e->getType());
223 return cir::ConstantOp::create(builder, cgf.getLoc(e->getExprLoc()),
224 cir::IntAttr::get(type, e->getValue()));
225 }
226
227 mlir::Value VisitFixedPointLiteral(const FixedPointLiteral *e) {
228 mlir::Type type = cgf.convertType(e->getType());
229 return cir::ConstantOp::create(builder, cgf.getLoc(e->getExprLoc()),
230 cir::IntAttr::get(type, e->getValue()));
231 }
232
233 mlir::Value VisitFloatingLiteral(const FloatingLiteral *e) {
234 mlir::Type type = cgf.convertType(e->getType());
235 assert(mlir::isa<cir::FPTypeInterface>(type) &&
236 "expect floating-point type");
237 return cir::ConstantOp::create(builder, cgf.getLoc(e->getExprLoc()),
238 cir::FPAttr::get(type, e->getValue()));
239 }
240
241 mlir::Value VisitCharacterLiteral(const CharacterLiteral *e) {
242 mlir::Type ty = cgf.convertType(e->getType());
243 // Character literals are always stored in an unsigned (even for signed
244 // char), so allow implicit truncation here.
245 auto intTy = mlir::cast<cir::IntTypeInterface>(ty);
246 llvm::APInt apValue(intTy.getWidth(), e->getValue(),
247 /*isSigned=*/false, /*implicitTrunc=*/true);
248 return cir::ConstantOp::create(builder, cgf.getLoc(e->getExprLoc()),
249 cir::IntAttr::get(ty, apValue));
250 }
251
252 mlir::Value VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *e) {
253 return builder.getBool(e->getValue(), cgf.getLoc(e->getExprLoc()));
254 }
255
256 mlir::Value VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *e) {
257 if (e->getType()->isVoidType())
258 return {};
259
260 return emitNullValue(e->getType(), cgf.getLoc(e->getSourceRange()));
261 }
262
263 mlir::Value VisitGNUNullExpr(const GNUNullExpr *e) {
264 return emitNullValue(e->getType(), cgf.getLoc(e->getSourceRange()));
265 }
266
267 mlir::Value VisitOffsetOfExpr(OffsetOfExpr *e);
268
269 mlir::Value VisitSizeOfPackExpr(SizeOfPackExpr *e) {
270 return builder.getConstInt(cgf.getLoc(e->getExprLoc()),
271 convertType(e->getType()), e->getPackLength());
272 }
273 mlir::Value VisitPseudoObjectExpr(PseudoObjectExpr *e) {
274 return cgf.emitPseudoObjectRValue(e).getValue();
275 }
276 mlir::Value VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *e);
277 mlir::Value VisitEmbedExpr(EmbedExpr *e) {
278 assert(e->getDataElementCount() == 1);
279 auto it = e->begin();
280 llvm::APInt value = (*it)->getValue();
281 return builder.getConstInt(cgf.getLoc(e->getExprLoc()), value,
283 }
284 mlir::Value VisitOpaqueValueExpr(OpaqueValueExpr *e) {
285 if (e->isGLValue())
286 return emitLoadOfLValue(cgf.getOrCreateOpaqueLValueMapping(e),
287 e->getExprLoc());
288
289 // Otherwise, assume the mapping is the scalar directly.
290 return cgf.getOrCreateOpaqueRValueMapping(e).getValue();
291 }
292
293 mlir::Value VisitObjCSelectorExpr(ObjCSelectorExpr *e) {
294 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc selector");
295 return {};
296 }
297 mlir::Value VisitObjCProtocolExpr(ObjCProtocolExpr *e) {
298 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc protocol");
299 return {};
300 }
301 mlir::Value VisitObjCIVarRefExpr(ObjCIvarRefExpr *e) {
302 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc ivar ref");
303 return {};
304 }
305 mlir::Value VisitObjCMessageExpr(ObjCMessageExpr *e) {
306 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc message");
307 return {};
308 }
309 mlir::Value VisitObjCIsaExpr(ObjCIsaExpr *e) {
310 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc isa");
311 return {};
312 }
313 mlir::Value VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *e) {
314 cgf.cgm.errorNYI(e->getSourceRange(),
315 "ScalarExprEmitter: objc availability check");
316 return {};
317 }
318
319 mlir::Value VisitMatrixSubscriptExpr(MatrixSubscriptExpr *e) {
320 mlir::Value rowIdx = cgf.emitScalarExpr(e->getRowIdx());
321 mlir::Value columnIdx = cgf.emitScalarExpr(e->getColumnIdx());
322 mlir::Value matrix = Visit(e->getBase());
323 mlir::Location loc = cgf.getLoc(e->getSourceRange());
325 return builder.createMatrixExtract(loc, matrix, rowIdx, columnIdx);
326 }
327
328 mlir::Value VisitMatrixSingleSubscriptExpr(MatrixSingleSubscriptExpr *e) {
329 mlir::Value rowIdx = cgf.emitScalarExpr(e->getRowIdx());
331 mlir::Value matrix = Visit(e->getBase());
332 mlir::Location loc = cgf.getLoc(e->getSourceRange());
333 return builder.createMatrixExtractRow(loc, matrix, rowIdx);
334 }
335
336 mlir::Value VisitCastExpr(CastExpr *e);
337 mlir::Value VisitCallExpr(const CallExpr *e);
338
339 mlir::Value VisitStmtExpr(StmtExpr *e) {
340 CIRGenFunction::StmtExprEvaluation eval(cgf);
341 if (e->getType()->isVoidType()) {
342 (void)cgf.emitCompoundStmt(*e->getSubStmt());
343 return {};
344 }
345
346 Address retAlloca =
347 cgf.createMemTemp(e->getType(), cgf.getLoc(e->getSourceRange()));
348 (void)cgf.emitCompoundStmt(*e->getSubStmt(), &retAlloca);
349
350 return cgf.emitLoadOfScalar(cgf.makeAddrLValue(retAlloca, e->getType()),
351 e->getExprLoc());
352 }
353
354 mlir::Value VisitArraySubscriptExpr(ArraySubscriptExpr *e) {
355 ignoreResultAssign = false;
356
357 if (e->getBase()->getType()->isVectorType()) {
359
360 const mlir::Location loc = cgf.getLoc(e->getSourceRange());
361 const mlir::Value vecValue = Visit(e->getBase());
362 const mlir::Value indexValue = Visit(e->getIdx());
363 return cir::VecExtractOp::create(cgf.getBuilder(), loc, vecValue,
364 indexValue);
365 }
366 // Just load the lvalue formed by the subscript expression.
367 return emitLoadOfLValue(e);
368 }
369
370 mlir::Value VisitShuffleVectorExpr(ShuffleVectorExpr *e) {
371 if (e->getNumSubExprs() == 2) {
372 // The undocumented form of __builtin_shufflevector.
373 mlir::Value inputVec = Visit(e->getExpr(0));
374 mlir::Value indexVec = Visit(e->getExpr(1));
375 return cir::VecShuffleDynamicOp::create(cgf.getBuilder(),
376 cgf.getLoc(e->getSourceRange()),
377 inputVec, indexVec);
378 }
379
380 mlir::Value vec1 = Visit(e->getExpr(0));
381 mlir::Value vec2 = Visit(e->getExpr(1));
382
383 // The documented form of __builtin_shufflevector, where the indices are
384 // a variable number of integer constants. The constants will be stored
385 // in an ArrayAttr.
386 SmallVector<mlir::Attribute, 8> indices;
387 for (unsigned i = 2; i < e->getNumSubExprs(); ++i) {
388 indices.push_back(
389 cir::IntAttr::get(cgf.getBuilder().getSInt64Ty(),
390 e->getExpr(i)
391 ->EvaluateKnownConstInt(cgf.getContext())
392 .getSExtValue()));
393 }
394
395 return cir::VecShuffleOp::create(cgf.getBuilder(),
396 cgf.getLoc(e->getSourceRange()),
397 cgf.convertType(e->getType()), vec1, vec2,
398 cgf.getBuilder().getArrayAttr(indices));
399 }
400
401 mlir::Value VisitConvertVectorExpr(ConvertVectorExpr *e) {
402 // __builtin_convertvector is an element-wise cast, and is implemented as a
403 // regular cast. The back end handles casts of vectors correctly.
404 return emitScalarConversion(Visit(e->getSrcExpr()),
405 e->getSrcExpr()->getType(), e->getType(),
406 e->getSourceRange().getBegin());
407 }
408
409 mlir::Value VisitExtVectorElementExpr(Expr *e) { return emitLoadOfLValue(e); }
410
411 mlir::Value VisitMatrixElementExpr(Expr *e) { return emitLoadOfLValue(e); }
412
413 mlir::Value VisitMemberExpr(MemberExpr *e);
414
415 mlir::Value VisitCompoundLiteralExpr(CompoundLiteralExpr *e) {
416 return emitLoadOfLValue(e);
417 }
418
419 mlir::Value VisitInitListExpr(InitListExpr *e);
420 mlir::Value emitVectorInitWithSubvectors(mlir::Location loc,
421 cir::VectorType vectorType,
422 ArrayRef<mlir::Value> inits);
423
424 mlir::Value VisitArrayInitIndexExpr(ArrayInitIndexExpr *e) {
425 assert(cgf.getArrayInitIndex() &&
426 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
427 return cgf.getArrayInitIndex();
428 }
429
430 mlir::Value VisitImplicitValueInitExpr(const ImplicitValueInitExpr *e) {
431 return emitNullValue(e->getType(), cgf.getLoc(e->getSourceRange()));
432 }
433
434 mlir::Value VisitExplicitCastExpr(ExplicitCastExpr *e) {
435 return VisitCastExpr(e);
436 }
437
438 mlir::Value VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *e) {
439 return cgf.cgm.emitNullConstant(e->getType(),
440 cgf.getLoc(e->getSourceRange()));
441 }
442
443 /// Perform a pointer to boolean conversion.
444 mlir::Value emitPointerToBoolConversion(mlir::Value v, QualType qt) {
445 // TODO(cir): comparing the ptr to null is done when lowering CIR to LLVM.
446 // We might want to have a separate pass for these types of conversions.
447 return cgf.getBuilder().createPtrToBoolCast(v);
448 }
449
450 mlir::Value emitFloatToBoolConversion(mlir::Value src, mlir::Location loc) {
451 cir::BoolType boolTy = builder.getBoolTy();
452 return cir::CastOp::create(builder, loc, boolTy,
453 cir::CastKind::float_to_bool, src);
454 }
455
456 mlir::Value emitIntToBoolConversion(mlir::Value srcVal, mlir::Location loc) {
457 // The enumerator of an enum with an integral underlying type is lowered to
458 // that type, which can be bool. In that case the operand is already a
459 // !cir.bool, so return it -- int_to_bool requires a !cir.int source.
460 if (mlir::isa<cir::BoolType>(srcVal.getType()))
461 return srcVal;
462
463 // Because of the type rules of C, we often end up computing a
464 // logical value, then zero extending it to int, then wanting it
465 // as a logical value again.
466 // TODO: optimize this common case here or leave it for later
467 // CIR passes?
468 cir::BoolType boolTy = builder.getBoolTy();
469 return cir::CastOp::create(builder, loc, boolTy, cir::CastKind::int_to_bool,
470 srcVal);
471 }
472
473 /// Convert the specified expression value to a boolean (!cir.bool) truth
474 /// value. This is equivalent to "Val != 0".
475 mlir::Value emitConversionToBool(mlir::Value src, QualType srcType,
476 mlir::Location loc) {
477 assert(srcType.isCanonical() && "EmitScalarConversion strips typedefs");
478
479 if (srcType->isRealFloatingType())
480 return emitFloatToBoolConversion(src, loc);
481
482 if (llvm::isa<MemberPointerType>(srcType)) {
483 cgf.getCIRGenModule().errorNYI(loc, "member pointer to bool conversion");
484 return builder.getFalse(loc);
485 }
486
487 if (srcType->isIntegerType())
488 return emitIntToBoolConversion(src, loc);
489
490 assert(::mlir::isa<cir::PointerType>(src.getType()));
491 return emitPointerToBoolConversion(src, srcType);
492 }
493
494 // Emit a conversion from the specified type to the specified destination
495 // type, both of which are CIR scalar types.
496 struct ScalarConversionOpts {
497 bool treatBooleanAsSigned;
498 bool emitImplicitIntegerTruncationChecks;
499 bool emitImplicitIntegerSignChangeChecks;
500
501 ScalarConversionOpts()
502 : treatBooleanAsSigned(false),
503 emitImplicitIntegerTruncationChecks(false),
504 emitImplicitIntegerSignChangeChecks(false) {}
505
506 ScalarConversionOpts(clang::SanitizerSet sanOpts)
507 : treatBooleanAsSigned(false),
508 emitImplicitIntegerTruncationChecks(
509 sanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
510 emitImplicitIntegerSignChangeChecks(
511 sanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
512 };
513
514 // Conversion from bool, integral, or floating-point to integral or
515 // floating-point. Conversions involving other types are handled elsewhere.
516 // Conversion to bool is handled elsewhere because that's a comparison against
517 // zero, not a simple cast. This handles both individual scalars and vectors.
518 mlir::Value emitScalarCast(mlir::Value src, QualType srcType,
519 QualType dstType, mlir::Type srcTy,
520 mlir::Type dstTy, ScalarConversionOpts opts) {
521 assert(!(mlir::isa<mlir::IntegerType>(srcTy) ||
522 mlir::isa<mlir::IntegerType>(dstTy)) &&
523 "Obsolete code. Don't use mlir::IntegerType with CIR.");
524
525 mlir::Type fullDstTy = dstTy;
526 if (mlir::isa<cir::MatrixType>(srcTy) &&
527 mlir::isa<cir::MatrixType>(dstTy)) {
528 // Use the element types of the matrices to figure out the CastKind.
529 srcTy = mlir::dyn_cast<cir::MatrixType>(srcTy).getElementType();
530 dstTy = mlir::dyn_cast<cir::MatrixType>(dstTy).getElementType();
531 } else if (mlir::isa<cir::VectorType>(srcTy) &&
532 mlir::isa<cir::VectorType>(dstTy)) {
533 // Use the element types of the vectors to figure out the CastKind.
534 srcTy = mlir::dyn_cast<cir::VectorType>(srcTy).getElementType();
535 dstTy = mlir::dyn_cast<cir::VectorType>(dstTy).getElementType();
536 }
537
538 std::optional<cir::CastKind> castKind;
539
540 // Start with a null fenv attr. If this is a floating point cast, we will
541 // get the attribute from the builder.
542 cir::FenvAttr fenvAttr;
543
544 if (mlir::isa<cir::BoolType>(srcTy)) {
545 if (opts.treatBooleanAsSigned)
546 cgf.getCIRGenModule().errorNYI("signed bool");
547 if (cgf.getBuilder().isInt(dstTy)) {
548 castKind = cir::CastKind::bool_to_int;
549 } else if (mlir::isa<cir::FPTypeInterface>(dstTy)) {
550 fenvAttr = cgf.getBuilder().getConstrainedFPAttr();
551 castKind = cir::CastKind::bool_to_float;
552 } else {
553 llvm_unreachable("Internal error: Cast to unexpected type");
554 }
555 } else if (cgf.getBuilder().isInt(srcTy)) {
556 if (cgf.getBuilder().isInt(dstTy)) {
557 castKind = cir::CastKind::integral;
558 } else if (mlir::isa<cir::FPTypeInterface>(dstTy)) {
559 fenvAttr = cgf.getBuilder().getConstrainedFPAttr();
560 castKind = cir::CastKind::int_to_float;
561 } else if (mlir::isa<cir::BoolType>(dstTy)) {
562 castKind = cir::CastKind::int_to_bool;
563 } else {
564 llvm_unreachable("Internal error: Cast to unexpected type");
565 }
566 } else if (mlir::isa<cir::FPTypeInterface>(srcTy)) {
567 fenvAttr = cgf.getBuilder().getConstrainedFPAttr();
568 if (cgf.getBuilder().isInt(dstTy)) {
569 // If we can't recognize overflow as undefined behavior, assume that
570 // overflow saturates. This protects against normal optimizations if we
571 // are compiling with non-standard FP semantics.
572 if (!cgf.cgm.getCodeGenOpts().StrictFloatCastOverflow)
573 cgf.getCIRGenModule().errorNYI("strict float cast overflow");
574 castKind = cir::CastKind::float_to_int;
575 } else if (mlir::isa<cir::FPTypeInterface>(dstTy)) {
576 // TODO: split this to createFPExt/createFPTrunc
577 return builder.createFloatingCast(src, fullDstTy);
578 } else if (mlir::isa<cir::BoolType>(dstTy)) {
579 castKind = cir::CastKind::float_to_bool;
580 } else {
581 llvm_unreachable("Internal error: Cast to unexpected type");
582 }
583 } else {
584 llvm_unreachable("Internal error: Cast from unexpected type");
585 }
586
587 assert(castKind.has_value() && "Internal error: CastKind not set.");
588 return builder.createOrFold<cir::CastOp>(src.getLoc(), fullDstTy, *castKind,
589 src, fenvAttr);
590 }
591
592 mlir::Value
593 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *e) {
594 return Visit(e->getReplacement());
595 }
596
597 mlir::Value VisitVAArgExpr(VAArgExpr *ve) {
598 QualType ty = ve->getType();
599
600 if (ty->isVariablyModifiedType()) {
601 cgf.cgm.errorNYI(ve->getSourceRange(),
602 "variably modified types in varargs");
603 }
604
605 return cgf.emitVAArg(ve);
606 }
607
608 mlir::Value VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *e) {
609 return Visit(e->getSemanticForm());
610 }
611
612 mlir::Value VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *e);
613 mlir::Value
614 VisitAbstractConditionalOperator(const AbstractConditionalOperator *e);
615
616 // Unary Operators.
617 mlir::Value VisitUnaryPrePostIncDec(const UnaryOperator *e) {
618 LValue lv = cgf.emitLValue(e->getSubExpr());
619 return emitScalarPrePostIncDec(e, lv);
620 }
621 mlir::Value VisitUnaryPostDec(const UnaryOperator *e) {
622 return VisitUnaryPrePostIncDec(e);
623 }
624 mlir::Value VisitUnaryPostInc(const UnaryOperator *e) {
625 return VisitUnaryPrePostIncDec(e);
626 }
627 mlir::Value VisitUnaryPreDec(const UnaryOperator *e) {
628 return VisitUnaryPrePostIncDec(e);
629 }
630 mlir::Value VisitUnaryPreInc(const UnaryOperator *e) {
631 return VisitUnaryPrePostIncDec(e);
632 }
633
634 mlir::Value emitFixedPointIncDec(const UnaryOperator *e, mlir::Value value,
635 QualType type);
636 mlir::Value emitScalarPrePostIncDec(const UnaryOperator *e, LValue lv) {
638
639 QualType type = e->getSubExpr()->getType();
640
641 mlir::Value value;
642 mlir::Value input;
643
644 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
645 QualType valType = atomicTy->getValueType();
646 mlir::Location loc = cgf.getLoc(e->getSourceRange());
647 bool isInc = e->isIncrementOp();
648 bool isPre = e->isPrefix();
649
650 // Bools are always set-to-true, as decrement isn't legal on bools.
651 if (valType->isBooleanType()) {
652 assert(isInc);
653 // Atomic operations require an integer type; reinterpret the bool
654 // pointer as a pointer to its underlying storage integer type.
655 cir::IntType intTy = builder.getBoolMemoryTy();
656 mlir::Value one = builder.getConstInt(loc, intTy, 1);
657 Address intAddr = lv.getAddress().withElementType(builder, intTy);
658
659 if (isPre) {
660 // Pre-increment: atomically store true, return true.
661 cir::StoreOp store = builder.createStore(loc, one, intAddr);
662 store.setMemOrder(cir::MemOrder::SequentiallyConsistent);
663 if (lv.isVolatileQualified())
664 store.setIsVolatile(true);
665 return builder.getTrue(loc);
666 }
667 // Post-increment: atomically exchange with true, return old value.
668 auto xchg = cir::AtomicXchgOp::create(
669 builder, loc, intAddr.getPointer(), one,
670 cir::MemOrder::SequentiallyConsistent, cir::SyncScopeKind::System,
671 lv.isVolatileQualified());
672 return builder.createCast(cir::CastKind::int_to_bool, xchg.getResult(),
673 builder.getBoolTy());
674 }
675
676 // Special case for atomic increment / decrement on integers, emit
677 // atomicrmw instructions. We skip this if we want to be doing overflow
678 // checking, and fall into the slow path with the atomic cmpxchg loop.
679 if (valType->isIntegerType() &&
680 !(valType->isUnsignedIntegerType() &&
681 cgf.sanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
682 cgf.getLangOpts().getSignedOverflowBehavior() !=
683 LangOptions::SOB_Trapping) {
684 mlir::Type intTy = cgf.convertType(valType);
685 mlir::Value one = builder.getConstInt(loc, intTy, 1);
686 cir::AtomicFetchKind kind =
687 isInc ? cir::AtomicFetchKind::Add : cir::AtomicFetchKind::Sub;
688 auto rmw = cir::AtomicFetchOp::create(
689 builder, loc, lv.getPointer(), one, kind,
690 cir::MemOrder::SequentiallyConsistent, cir::SyncScopeKind::System,
691 lv.isVolatileQualified(), /*fetch_first=*/true);
692 mlir::Value oldVal = rmw->getResult(0);
693 // Prefix returns new value; postfix returns old value.
694 return isPre ? emitIntIncOrDec(e, oldVal) : oldVal;
695 }
696
697 // Special case for atomic increment/decrement on floats.
698 // Bail out non-power-of-2-sized floating point types (e.g., x86_fp80).
699 if (valType->isFloatingType()) {
700 mlir::Type fpTy = cgf.convertType(valType);
701 auto fpType = mlir::cast<cir::FPTypeInterface>(fpTy);
702 // Bail on non-power-of-2 types (e.g., x86_fp80 is 80 bits).
703 if (llvm::has_single_bit(fpType.getWidth())) {
704 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, e);
705 mlir::Value amt = builder.getConstFP(
706 loc, fpTy, llvm::APFloat(fpType.getFloatSemantics(), 1));
707 cir::AtomicFetchKind kind =
708 isInc ? cir::AtomicFetchKind::Add : cir::AtomicFetchKind::Sub;
709 auto rmw = cir::AtomicFetchOp::create(
710 builder, loc, lv.getPointer(), amt, kind,
711 cir::MemOrder::SequentiallyConsistent, cir::SyncScopeKind::System,
712 lv.isVolatileQualified(), /*fetch_first=*/true);
713 mlir::Value oldVal = rmw->getResult(0);
714 if (isPre)
715 return isInc ? builder.createFAdd(loc, oldVal, amt)
716 : builder.createFSub(loc, oldVal, amt);
717 return oldVal;
718 } else {
719 cgf.cgm.errorNYI(e->getSourceRange(),
720 "Atomic inc/dec of non-power-of-2 float");
721 }
722 }
723
724 // Otherwise we need a loop on compare-exchange.
725 cgf.cgm.errorNYI(e->getSourceRange(), "Atomic inc/dec");
726 value = cgf.emitLoadOfLValue(lv, e->getExprLoc()).getValue();
727 input = value;
728 } else {
729 value = cgf.emitLoadOfLValue(lv, e->getExprLoc()).getValue();
730 input = value;
731 }
732
733 // NOTE: When possible, more frequent cases are handled first.
734
735 // Special case of integer increment that we have to check first: bool++.
736 // Due to promotion rules, we get:
737 // bool++ -> bool = bool + 1
738 // -> bool = (int)bool + 1
739 // -> bool = ((int)bool + 1 != 0)
740 // An interesting aspect of this is that increment is always true.
741 // Decrement does not have this property.
742 if (e->isIncrementOp() && type->isBooleanType()) {
743 value = builder.getTrue(cgf.getLoc(e->getExprLoc()));
744 } else if (type->isIntegerType()) {
745 QualType promotedType;
746 [[maybe_unused]] bool canPerformLossyDemotionCheck = false;
747 if (cgf.getContext().isPromotableIntegerType(type)) {
748 promotedType = cgf.getContext().getPromotedIntegerType(type);
749 assert(promotedType != type && "Shouldn't promote to the same type.");
750 canPerformLossyDemotionCheck = true;
751 canPerformLossyDemotionCheck &=
752 cgf.getContext().getCanonicalType(type) !=
753 cgf.getContext().getCanonicalType(promotedType);
754 canPerformLossyDemotionCheck &=
755 type->isIntegerType() && promotedType->isIntegerType();
756
757 // TODO(cir): Currently, we store bitwidths in CIR types only for
758 // integers. This might also be required for other types.
759
760 assert(
761 (!canPerformLossyDemotionCheck ||
762 type->isSignedIntegerOrEnumerationType() ||
763 promotedType->isSignedIntegerOrEnumerationType() ||
764 mlir::cast<cir::IntType>(cgf.convertType(type)).getWidth() ==
765 mlir::cast<cir::IntType>(cgf.convertType(type)).getWidth()) &&
766 "The following check expects that if we do promotion to different "
767 "underlying canonical type, at least one of the types (either "
768 "base or promoted) will be signed, or the bitwidths will match.");
769 }
770
772 if (e->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
773 value = emitIncDecConsiderOverflowBehavior(e, value);
774 } else {
775 // NOTE(CIR): clang calls CreateAdd but folds this to a unary op
776 value = emitIntIncOrDec(e, input, /*nsw=*/false);
777 }
778 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
779 QualType type = ptr->getPointeeType();
780 if (const VariableArrayType *vla =
781 cgf.getContext().getAsVariableArrayType(type)) {
782 mlir::Location loc = cgf.getLoc(e->getSourceRange());
783 mlir::Value numElts = cgf.getVLASize(vla).numElts;
784 if (!e->isIncrementOp())
785 numElts = cgf.getBuilder().createNeg(loc, numElts, /*nsw=*/true);
787 value = cgf.getBuilder().createPtrStride(loc, value, numElts);
788 } else {
789 // For everything else, we can just do a simple increment.
790 mlir::Location loc = cgf.getLoc(e->getSourceRange());
791 int amount = e->isIncrementOp() ? 1 : -1;
792 mlir::Value amt = builder.getSInt32(amount, loc);
794 value = builder.createPtrStride(loc, value, amt);
795 }
796 } else if (type->isVectorType()) {
797 if (type->hasIntegerRepresentation()) {
798 value = emitIntIncOrDec(e, input, /*nsw=*/false);
799 } else {
800 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, e);
801 value = emitFloatIncOrDec(e, input);
802 }
803 } else if (type->isRealFloatingType()) {
804 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, e);
805 value = emitFloatIncOrDec(e, input);
806 } else if (type->isFixedPointType()) {
807 value = emitFixedPointIncDec(e, value, type);
808 } else {
809 assert(type->castAs<ObjCObjectPointerType>());
810 cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec ObjectiveC pointer");
811 return {};
812 }
813
814 CIRGenFunction::SourceLocRAIIObject sourceloc{cgf, e->getSourceRange()};
815
816 // Store the updated result through the lvalue
817 if (lv.isBitField())
818 value = cgf.emitStoreThroughBitfieldLValue(RValue::get(value), lv);
819 else
820 cgf.emitStoreThroughLValue(RValue::get(value), lv);
821
822 // If this is a postinc, return the value read from memory, otherwise use
823 // the updated value.
824 return e->isPrefix() ? value : input;
825 }
826
827 mlir::Value emitIncDecConsiderOverflowBehavior(const UnaryOperator *e,
828 mlir::Value inVal) {
829 switch (cgf.getLangOpts().getSignedOverflowBehavior()) {
830 case LangOptions::SOB_Defined:
831 return emitIntIncOrDec(e, inVal, /*nsw=*/false);
832 case LangOptions::SOB_Undefined:
834 return emitIntIncOrDec(e, inVal, /*nsw=*/true);
835 case LangOptions::SOB_Trapping:
836 if (!e->canOverflow())
837 return emitIntIncOrDec(e, inVal, /*nsw=*/true);
838 cgf.cgm.errorNYI(e->getSourceRange(), "inc/def overflow SOB_Trapping");
839 return {};
840 }
841 llvm_unreachable("Unexpected signed overflow behavior kind");
842 }
843
844 mlir::Value VisitUnaryAddrOf(const UnaryOperator *e) {
845 if (llvm::isa<MemberPointerType>(e->getType()))
846 return cgf.cgm.emitMemberPointerConstant(e);
847
848 return cgf.emitLValue(e->getSubExpr()).getPointer();
849 }
850
851 mlir::Value VisitUnaryDeref(const UnaryOperator *e) {
852 if (e->getType()->isVoidType())
853 return Visit(e->getSubExpr()); // the actual value should be unused
854 return emitLoadOfLValue(e);
855 }
856
857 mlir::Value VisitUnaryPlus(const UnaryOperator *e) {
858 QualType promotionType = getPromotionType(e->getSubExpr()->getType());
859 mlir::Value result = VisitUnaryPlus(e, promotionType);
860 if (result && !promotionType.isNull())
861 return emitUnPromotedValue(result, e->getType());
862 return result;
863 }
864
865 mlir::Value VisitUnaryPlus(const UnaryOperator *e, QualType promotionType) {
866 ignoreResultAssign = false;
867 if (!promotionType.isNull())
868 return cgf.emitPromotedScalarExpr(e->getSubExpr(), promotionType);
869 return Visit(e->getSubExpr());
870 }
871
872 mlir::Value VisitUnaryMinus(const UnaryOperator *e) {
873 QualType promotionType = getPromotionType(e->getSubExpr()->getType());
874 mlir::Value result = VisitUnaryMinus(e, promotionType);
875 if (result && !promotionType.isNull())
876 return emitUnPromotedValue(result, e->getType());
877 return result;
878 }
879
880 mlir::Value VisitUnaryMinus(const UnaryOperator *e, QualType promotionType) {
881 ignoreResultAssign = false;
882 mlir::Value operand;
883 if (!promotionType.isNull())
884 operand = cgf.emitPromotedScalarExpr(e->getSubExpr(), promotionType);
885 else
886 operand = Visit(e->getSubExpr());
887
888 mlir::Location loc = cgf.getLoc(e->getSourceRange().getBegin());
889
890 if (cir::isFPOrVectorOfFPType(operand.getType())) {
891 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, e);
892 return builder.createOrFold<cir::FNegOp>(loc, operand,
893 builder.getFastMathFlagsAttr());
894 }
895
896 // Saturated negation must saturate (-min for signed, any nonzero value for
897 // unsigned), as in classic codegen.
899 CIRGenFixedPointBuilder fpBuilder(builder, loc);
900 return fpBuilder.createNeg(
901 operand, cgf.getContext().getFixedPointSemantics(e->getType()));
902 }
903
904 // TODO(cir): We might have to change this to support overflow trapping.
905 // Classic codegen routes unary minus through emitSub to ensure
906 // that the overflow behavior is handled correctly.
907 bool nsw = e->getType()->isSignedIntegerType() &&
908 cgf.getLangOpts().getSignedOverflowBehavior() !=
909 LangOptions::SOB_Defined;
910
911 return builder.createOrFold<cir::MinusOp>(loc, operand, nsw);
912 }
913
914 mlir::Value emitIntIncOrDec(const UnaryOperator *e, mlir::Value input,
915 bool nsw = false) {
916 mlir::Location loc = cgf.getLoc(e->getSourceRange().getBegin());
917 return e->isIncrementOp()
918 ? builder.createOrFold<cir::IncOp>(loc, input, nsw)
919 : builder.createOrFold<cir::DecOp>(loc, input, nsw);
920 }
921
922 mlir::Value emitFloatIncOrDec(const UnaryOperator *e, mlir::Value input) {
923 assert(cir::isFPOrVectorOfFPType(input.getType()) &&
924 "Expect floating-point operand");
925 mlir::Location loc = cgf.getLoc(e->getSourceRange().getBegin());
926
927 if (auto vecType = mlir::dyn_cast<cir::VectorType>(input.getType())) {
928 mlir::Type fpScalarType = vecType.getElementType();
929 auto fpInterface = mlir::cast<cir::FPTypeInterface>(fpScalarType);
930 auto amount = llvm::APFloat::getOne(fpInterface.getFloatSemantics(),
931 /*Negative=*/e->isDecrementOp());
932 mlir::Value amtValue = builder.getConstFP(loc, fpScalarType, amount);
933 amtValue = cir::VecSplatOp::create(builder, loc, vecType, amtValue);
934 return builder.createFAdd(loc, input, amtValue);
935 }
936
937 QualType type = e->getSubExpr()->getType();
938 // Another special case: half FP increment should be done via float.
939 if (type->isHalfType() && !cgf.getContext().getLangOpts().NativeHalfType)
940 input = builder.createFloatingCast(input, builder.getSingleTy());
941
942 auto fpInterface = mlir::cast<cir::FPTypeInterface>(input.getType());
943 auto amount = llvm::APFloat::getOne(fpInterface.getFloatSemantics(),
944 /*Negative=*/e->isDecrementOp());
945 mlir::Value amtValue = builder.getConstFP(loc, input.getType(), amount);
946 mlir::Value output = builder.createFAdd(loc, input, amtValue);
947
948 if (type->isHalfType() && !cgf.getContext().getLangOpts().NativeHalfType)
949 output = builder.createFloatingCast(output, builder.getFp16Ty());
950
951 return output;
952 }
953
954 mlir::Value VisitUnaryNot(const UnaryOperator *e) {
955 ignoreResultAssign = false;
956 mlir::Value op = Visit(e->getSubExpr());
957 return builder.createOrFold<cir::NotOp>(
958 cgf.getLoc(e->getSourceRange().getBegin()), op);
959 }
960
961 mlir::Value VisitUnaryLNot(const UnaryOperator *e);
962
963 mlir::Value VisitUnaryReal(const UnaryOperator *e);
964 mlir::Value VisitUnaryImag(const UnaryOperator *e);
965 mlir::Value VisitRealImag(const UnaryOperator *e,
966 QualType promotionType = QualType());
967
968 mlir::Value VisitUnaryExtension(const UnaryOperator *e) {
969 return Visit(e->getSubExpr());
970 }
971
972 // C++
973 mlir::Value VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *e) {
974 return emitLoadOfLValue(e);
975 }
976 mlir::Value VisitSourceLocExpr(SourceLocExpr *e) {
977 ASTContext &ctx = cgf.getContext();
978 APValue evaluated =
979 e->EvaluateInContext(ctx, cgf.curSourceLocExprScope.getDefaultExpr());
980 mlir::Attribute attribute = ConstantEmitter(cgf).emitAbstract(
981 e->getLocation(), evaluated, e->getType());
982 mlir::TypedAttr typedAttr = mlir::cast<mlir::TypedAttr>(attribute);
983 return cir::ConstantOp::create(builder, cgf.getLoc(e->getExprLoc()),
984 typedAttr);
985 }
986 mlir::Value VisitCXXDefaultArgExpr(CXXDefaultArgExpr *dae) {
987 CIRGenFunction::CXXDefaultArgExprScope scope(cgf, dae);
988 return Visit(dae->getExpr());
989 }
990 mlir::Value VisitCXXDefaultInitExpr(CXXDefaultInitExpr *die) {
991 CIRGenFunction::CXXDefaultInitExprScope scope(cgf, die);
992 return Visit(die->getExpr());
993 }
994
995 mlir::Value VisitCXXThisExpr(CXXThisExpr *te) { return cgf.loadCXXThis(); }
996
997 mlir::Value VisitExprWithCleanups(ExprWithCleanups *e);
998 mlir::Value VisitCXXNewExpr(const CXXNewExpr *e) {
999 return cgf.emitCXXNewExpr(e);
1000 }
1001 mlir::Value VisitCXXDeleteExpr(const CXXDeleteExpr *e) {
1002 cgf.emitCXXDeleteExpr(e);
1003 return {};
1004 }
1005 mlir::Value VisitTypeTraitExpr(const TypeTraitExpr *e) {
1006 // We diverge slightly from classic codegen here because CIR has stricter
1007 // typing. In LLVM IR, constant folding covers up some potential type
1008 // mismatches such as bool-to-int conversions that would fail the verifier
1009 // in CIR. To make things work, we need to be sure we only emit a bool value
1010 // if the expression type is bool.
1011 mlir::Location loc = cgf.getLoc(e->getExprLoc());
1012 if (e->isStoredAsBoolean()) {
1013 if (e->getType()->isBooleanType())
1014 return builder.getBool(e->getBoolValue(), loc);
1015 assert(e->getType()->isIntegerType() &&
1016 "Expected int type for TypeTraitExpr");
1017 return builder.getConstInt(loc, cgf.convertType(e->getType()),
1018 (uint64_t)e->getBoolValue());
1019 }
1020 assert(e->getType()->isIntegerType() && "not a scalar type trait");
1021 return builder.getConstInt(loc, e->getAPValue().getInt());
1022 }
1023 mlir::Value
1024 VisitConceptSpecializationExpr(const ConceptSpecializationExpr *e) {
1025 return builder.getBool(e->isSatisfied(), cgf.getLoc(e->getExprLoc()));
1026 }
1027 mlir::Value VisitRequiresExpr(const RequiresExpr *e) {
1028 return builder.getBool(e->isSatisfied(), cgf.getLoc(e->getExprLoc()));
1029 }
1030 mlir::Value VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *e) {
1031 mlir::Type type = cgf.convertType(e->getType());
1032 mlir::Location loc = cgf.getLoc(e->getExprLoc());
1033 return builder.getConstInt(loc, type, e->getValue());
1034 }
1035 mlir::Value VisitExpressionTraitExpr(const ExpressionTraitExpr *e) {
1036 return builder.getBool(e->getValue(), cgf.getLoc(e->getExprLoc()));
1037 }
1038 mlir::Value VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *e) {
1039 cgf.cgm.errorNYI(e->getSourceRange(),
1040 "ScalarExprEmitter: cxx pseudo destructor");
1041 return {};
1042 }
1043 mlir::Value VisitCXXThrowExpr(const CXXThrowExpr *e) {
1044 cgf.emitCXXThrowExpr(e);
1045 return {};
1046 }
1047
1048 mlir::Value VisitCXXNoexceptExpr(CXXNoexceptExpr *e) {
1049 return builder.getBool(e->getValue(), cgf.getLoc(e->getExprLoc()));
1050 }
1051
1052 mlir::Value emitFixedPointConversion(mlir::Value src, QualType srcTy,
1053 QualType dstTy, mlir::Location loc);
1054
1055 /// Emit a conversion from the specified type to the specified destination
1056 /// type, both of which are CIR scalar types.
1057 /// TODO: do we need ScalarConversionOpts here? Should be done in another
1058 /// pass.
1059 mlir::Value
1060 emitScalarConversion(mlir::Value src, QualType srcType, QualType dstType,
1061 SourceLocation loc,
1062 ScalarConversionOpts opts = ScalarConversionOpts()) {
1063 // All conversions involving fixed point types should be handled by the
1064 // emitFixedPoint family functions. This is done to prevent bloating up
1065 // this function more, and although fixed point numbers are represented by
1066 // integers, we do not want to follow any logic that assumes they should be
1067 // treated as integers.
1068 if (srcType->isFixedPointType()) {
1069 if (dstType->isBooleanType()) {
1070 cir::BoolType boolTy = builder.getBoolTy();
1071 return cir::CastOp::create(builder, cgf.getLoc(loc), boolTy,
1072 cir::CastKind::int_to_bool, src);
1073 }
1074
1075 if (dstType->isFixedPointType() || dstType->isIntegerType() ||
1076 dstType->isRealFloatingType())
1077 return emitFixedPointConversion(src, srcType, dstType, cgf.getLoc(loc));
1078
1079 llvm_unreachable("Unhandled scalar conversion from a fixed point type to "
1080 "another type.");
1081 } else if (dstType->isFixedPointType()) {
1082 if (srcType->isIntegerType() || srcType->isRealFloatingType()) {
1083 // This also includes converting booleans and enums to fixed point
1084 // types.
1085 return emitFixedPointConversion(src, srcType, dstType, cgf.getLoc(loc));
1086 }
1087
1088 llvm_unreachable("Unhandled scalar conversion to a fixed point type from "
1089 "another type.");
1090 }
1091
1092 srcType = srcType.getCanonicalType();
1093 dstType = dstType.getCanonicalType();
1094 if (srcType == dstType) {
1095 if (opts.emitImplicitIntegerSignChangeChecks)
1096 cgf.getCIRGenModule().errorNYI(loc,
1097 "implicit integer sign change checks");
1098 return src;
1099 }
1100
1101 if (dstType->isVoidType())
1102 return {};
1103
1104 mlir::Type mlirSrcType = src.getType();
1105
1106 // Handle conversions to bool first, they are special: comparisons against
1107 // 0.
1108 if (dstType->isBooleanType())
1109 return emitConversionToBool(src, srcType, cgf.getLoc(loc));
1110
1111 mlir::Type mlirDstType = cgf.convertType(dstType);
1112
1113 if (srcType->isHalfType() &&
1114 !cgf.getContext().getLangOpts().NativeHalfType) {
1115 // Cast to FP using the intrinsic if the half type itself isn't supported.
1116 if (!mlir::isa<cir::FPTypeInterface>(mlirDstType)) {
1117 // Cast to other types through float, using FPExt, depending on whether
1118 // the half type itself is supported (as opposed to operations on half,
1119 // available with NativeHalfType).
1120 src = builder.createCast(cgf.getLoc(loc), cir::CastKind::floating, src,
1121 cgf.floatTy);
1122 srcType = cgf.getContext().FloatTy;
1123 mlirSrcType = cgf.floatTy;
1124 }
1125 }
1126
1127 // TODO(cir): LLVM codegen ignore conversions like int -> uint,
1128 // is there anything to be done for CIR here?
1129 if (mlirSrcType == mlirDstType) {
1130 if (opts.emitImplicitIntegerSignChangeChecks)
1131 cgf.getCIRGenModule().errorNYI(loc,
1132 "implicit integer sign change checks");
1133 return src;
1134 }
1135
1136 // Handle pointer conversions next: pointers can only be converted to/from
1137 // other pointers and integers. Check for pointer types in terms of LLVM, as
1138 // some native types (like Obj-C id) may map to a pointer type.
1139 if (auto dstPT = dyn_cast<cir::PointerType>(mlirDstType)) {
1140 cgf.getCIRGenModule().errorNYI(loc, "pointer casts");
1141 return builder.getNullPtr(dstPT, src.getLoc());
1142 }
1143
1144 if (isa<cir::PointerType>(mlirSrcType)) {
1145 // Must be an ptr to int cast.
1146 assert(isa<cir::IntType>(mlirDstType) && "not ptr->int?");
1147 return builder.createPtrToInt(src, mlirDstType);
1148 }
1149
1150 // A scalar can be splatted to an extended vector of the same element type
1151 if (dstType->isExtVectorType() && !srcType->isVectorType()) {
1152 // Sema should add casts to make sure that the source expression's type
1153 // is the same as the vector's element type (sans qualifiers)
1154 assert(dstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
1155 srcType.getTypePtr() &&
1156 "Splatted expr doesn't match with vector element type?");
1157
1158 cgf.getCIRGenModule().errorNYI(loc, "vector splatting");
1159 return {};
1160 }
1161
1162 if (srcType->isMatrixType() && dstType->isMatrixType()) {
1163 return emitScalarCast(src, srcType, dstType, mlirSrcType, mlirDstType,
1164 opts);
1165 }
1166 assert(!srcType->isMatrixType() && !dstType->isMatrixType() &&
1167 "Internal error: conversion between matrix type and scalar type");
1168
1169 // Finally, we have the arithmetic types or vectors of arithmetic types.
1170 mlir::Value res = nullptr;
1171 mlir::Type resTy = mlirDstType;
1172
1173 res = emitScalarCast(src, srcType, dstType, mlirSrcType, mlirDstType, opts);
1174
1175 if (mlirDstType != resTy) {
1176 res = builder.createCast(cgf.getLoc(loc), cir::CastKind::floating, res,
1177 resTy);
1178 }
1179
1180 if (opts.emitImplicitIntegerTruncationChecks)
1181 cgf.getCIRGenModule().errorNYI(loc, "implicit integer truncation checks");
1182
1183 if (opts.emitImplicitIntegerSignChangeChecks)
1184 cgf.getCIRGenModule().errorNYI(loc,
1185 "implicit integer sign change checks");
1186
1187 return res;
1188 }
1189
1190 BinOpInfo emitBinOps(const BinaryOperator *e,
1191 QualType promotionType = QualType()) {
1192 ignoreResultAssign = false;
1193 BinOpInfo result;
1194 result.lhs = cgf.emitPromotedScalarExpr(e->getLHS(), promotionType);
1195 result.rhs = cgf.emitPromotedScalarExpr(e->getRHS(), promotionType);
1196 if (!promotionType.isNull())
1197 result.fullType = promotionType;
1198 else
1199 result.fullType = e->getType();
1200 result.compType = result.fullType;
1201 if (const auto *vecType = result.fullType->getAs<VectorType>())
1202 result.compType = vecType->getElementType();
1203 result.opcode = e->getOpcode();
1204 result.loc = e->getSourceRange();
1205 result.fpFeatures = e->getFPFeaturesInEffect(cgf.getLangOpts());
1206 result.e = e;
1207 return result;
1208 }
1209
1210 mlir::Value emitMul(const BinOpInfo &ops);
1211 mlir::Value emitDiv(const BinOpInfo &ops);
1212 mlir::Value emitRem(const BinOpInfo &ops);
1213 mlir::Value emitAdd(const BinOpInfo &ops);
1214 mlir::Value emitSub(const BinOpInfo &ops);
1215 mlir::Value emitShl(const BinOpInfo &ops);
1216 mlir::Value emitShr(const BinOpInfo &ops);
1217 mlir::Value emitAnd(const BinOpInfo &ops);
1218 mlir::Value emitXor(const BinOpInfo &ops);
1219 mlir::Value emitOr(const BinOpInfo &ops);
1220
1221 mlir::Value emitFixedPointBinOp(const BinOpInfo &ops);
1222
1223 LValue emitCompoundAssignLValue(
1224 const CompoundAssignOperator *e,
1225 mlir::Value (ScalarExprEmitter::*f)(const BinOpInfo &),
1226 mlir::Value &result);
1227 mlir::Value
1228 emitCompoundAssign(const CompoundAssignOperator *e,
1229 mlir::Value (ScalarExprEmitter::*f)(const BinOpInfo &));
1230
1231 // TODO(cir): Candidate to be in a common AST helper between CIR and LLVM
1232 // codegen.
1233 QualType getPromotionType(QualType ty) {
1234 const clang::ASTContext &ctx = cgf.getContext();
1235 if (auto *complexTy = ty->getAs<ComplexType>()) {
1236 QualType elementTy = complexTy->getElementType();
1237 if (elementTy.UseExcessPrecision(ctx))
1238 return ctx.getComplexType(ctx.FloatTy);
1239 }
1240
1241 if (ty.UseExcessPrecision(cgf.getContext())) {
1242 if (auto *vt = ty->getAs<VectorType>()) {
1243 unsigned numElements = vt->getNumElements();
1244 return ctx.getVectorType(ctx.FloatTy, numElements, vt->getVectorKind());
1245 }
1246 return cgf.getContext().FloatTy;
1247 }
1248
1249 return QualType();
1250 }
1251
1252// Binary operators and binary compound assignment operators.
1253#define HANDLEBINOP(OP) \
1254 mlir::Value VisitBin##OP(const BinaryOperator *e) { \
1255 QualType promotionTy = getPromotionType(e->getType()); \
1256 auto result = emit##OP(emitBinOps(e, promotionTy)); \
1257 if (result && !promotionTy.isNull()) \
1258 result = emitUnPromotedValue(result, e->getType()); \
1259 return result; \
1260 } \
1261 mlir::Value VisitBin##OP##Assign(const CompoundAssignOperator *e) { \
1262 return emitCompoundAssign(e, &ScalarExprEmitter::emit##OP); \
1263 }
1264
1265 HANDLEBINOP(Mul)
1266 HANDLEBINOP(Div)
1267 HANDLEBINOP(Rem)
1268 HANDLEBINOP(Add)
1269 HANDLEBINOP(Sub)
1270 HANDLEBINOP(Shl)
1271 HANDLEBINOP(Shr)
1273 HANDLEBINOP(Xor)
1275#undef HANDLEBINOP
1276
1277 cir::CmpOpKind clangCmpToCIRCmp(clang::BinaryOperatorKind clangCmp) {
1278 switch (clangCmp) {
1279 case BO_LT:
1280 return cir::CmpOpKind::lt;
1281 case BO_GT:
1282 return cir::CmpOpKind::gt;
1283 case BO_LE:
1284 return cir::CmpOpKind::le;
1285 case BO_GE:
1286 return cir::CmpOpKind::ge;
1287 case BO_EQ:
1288 return cir::CmpOpKind::eq;
1289 case BO_NE:
1290 return cir::CmpOpKind::ne;
1291 default:
1292 llvm_unreachable("unsupported comparison kind for cir.cmp");
1293 }
1294 }
1295
1296 mlir::Value emitCmp(const BinaryOperator *e) {
1297 ignoreResultAssign = false;
1298 const mlir::Location loc = cgf.getLoc(e->getExprLoc());
1299 mlir::Value result;
1300 QualType lhsTy = e->getLHS()->getType();
1301 QualType rhsTy = e->getRHS()->getType();
1302
1303 cir::CmpOpKind kind = clangCmpToCIRCmp(e->getOpcode());
1304 if (lhsTy->getAs<MemberPointerType>()) {
1306 assert(e->getOpcode() == BO_EQ || e->getOpcode() == BO_NE);
1307 mlir::Value lhs = cgf.emitScalarExpr(e->getLHS());
1308 mlir::Value rhs = cgf.emitScalarExpr(e->getRHS());
1309 result = builder.createCompare(loc, kind, lhs, rhs);
1310 } else if (!lhsTy->isAnyComplexType() && !rhsTy->isAnyComplexType()) {
1311 BinOpInfo boInfo = emitBinOps(e);
1312 mlir::Value lhs = boInfo.lhs;
1313 mlir::Value rhs = boInfo.rhs;
1314
1315 if (lhsTy->isVectorType()) {
1316 if (!e->getType()->isVectorType()) {
1317 // If AltiVec, the comparison results in a numeric type, so we use
1318 // intrinsics comparing vectors and giving 0 or 1 as a result
1319 cgf.cgm.errorNYI(loc, "AltiVec comparison");
1320 } else {
1321 // Other kinds of vectors. Element-wise comparison returning
1322 // a vector.
1323 result = cir::VecCmpOp::create(builder, cgf.getLoc(boInfo.loc),
1324 cgf.convertType(boInfo.fullType), kind,
1325 boInfo.lhs, boInfo.rhs);
1326 }
1327 } else if (boInfo.isFixedPointOp()) {
1328 result = emitFixedPointBinOp(boInfo);
1329 } else {
1330 // integers and pointers
1331 if (cgf.cgm.getCodeGenOpts().StrictVTablePointers &&
1332 mlir::isa<cir::PointerType>(lhs.getType()) &&
1333 mlir::isa<cir::PointerType>(rhs.getType())) {
1334 cgf.cgm.errorNYI(loc, "strict vtable pointer comparisons");
1335 }
1336 result = builder.createCompare(loc, kind, lhs, rhs);
1337 }
1338 } else {
1339 assert((e->getOpcode() == BO_EQ || e->getOpcode() == BO_NE) &&
1340 "Complex Comparison: can only be an equality comparison");
1341
1342 mlir::Value lhs;
1343 if (lhsTy->isAnyComplexType()) {
1344 lhs = cgf.emitComplexExpr(e->getLHS());
1345 } else {
1346 mlir::Value lhsReal = Visit(e->getLHS());
1347 mlir::Value lhsImag = builder.getNullValue(convertType(lhsTy), loc);
1348 lhs = builder.createComplexCreate(loc, lhsReal, lhsImag);
1349 }
1350
1351 mlir::Value rhs;
1352 if (rhsTy->isAnyComplexType()) {
1353 rhs = cgf.emitComplexExpr(e->getRHS());
1354 } else {
1355 mlir::Value rhsReal = Visit(e->getRHS());
1356 mlir::Value rhsImag = builder.getNullValue(convertType(rhsTy), loc);
1357 rhs = builder.createComplexCreate(loc, rhsReal, rhsImag);
1358 }
1359
1360 result = builder.createCompare(loc, kind, lhs, rhs);
1361 }
1362
1363 return emitScalarConversion(result, cgf.getContext().BoolTy, e->getType(),
1364 e->getExprLoc());
1365 }
1366
1367// Comparisons.
1368#define VISITCOMP(CODE) \
1369 mlir::Value VisitBin##CODE(const BinaryOperator *E) { return emitCmp(E); }
1370 VISITCOMP(LT)
1371 VISITCOMP(GT)
1372 VISITCOMP(LE)
1373 VISITCOMP(GE)
1374 VISITCOMP(EQ)
1375 VISITCOMP(NE)
1376#undef VISITCOMP
1377
1378 mlir::Value VisitBinAssign(const BinaryOperator *e) {
1379 const bool ignore = std::exchange(ignoreResultAssign, false);
1380
1381 mlir::Value rhs;
1382 LValue lhs;
1383
1384 switch (e->getLHS()->getType().getObjCLifetime()) {
1390 break;
1392 // __block variables need to have the rhs evaluated first, plus this
1393 // should improve codegen just a little.
1394 rhs = Visit(e->getRHS());
1396 // TODO(cir): This needs to be emitCheckedLValue() once we support
1397 // sanitizers
1398 lhs = cgf.emitLValue(e->getLHS());
1399
1400 // Store the value into the LHS. Bit-fields are handled specially because
1401 // the result is altered by the store, i.e., [C99 6.5.16p1]
1402 // 'An assignment expression has the value of the left operand after the
1403 // assignment...'.
1404 if (lhs.isBitField()) {
1406 rhs = cgf.emitStoreThroughBitfieldLValue(RValue::get(rhs), lhs);
1407 } else {
1408 cgf.emitNullabilityCheck(lhs, rhs, e->getExprLoc());
1410 cgf.emitStoreThroughLValue(RValue::get(rhs), lhs);
1411 }
1412 }
1413
1414 // If the result is clearly ignored, return now.
1415 if (ignore)
1416 return nullptr;
1417
1418 // The result of an assignment in C is the assigned r-value.
1419 if (!cgf.getLangOpts().CPlusPlus)
1420 return rhs;
1421
1422 // If the lvalue is non-volatile, return the computed value of the
1423 // assignment.
1424 if (!lhs.isVolatile())
1425 return rhs;
1426
1427 // Otherwise, reload the value.
1428 return emitLoadOfLValue(lhs, e->getExprLoc());
1429 }
1430
1431 mlir::Value VisitBinComma(const BinaryOperator *e) {
1432 cgf.emitIgnoredExpr(e->getLHS());
1433 // NOTE: We don't need to EnsureInsertPoint() like LLVM codegen.
1434 return Visit(e->getRHS());
1435 }
1436
1437 mlir::Value VisitBinLAnd(const clang::BinaryOperator *e) {
1438 if (e->getType()->isVectorType()) {
1439 mlir::Location loc = cgf.getLoc(e->getExprLoc());
1440 mlir::Type lhsTy = cgf.convertType(e->getLHS()->getType());
1441 mlir::Value zeroVec = builder.getNullValue(lhsTy, loc);
1442
1443 mlir::Value lhs = Visit(e->getLHS());
1444 mlir::Value rhs = Visit(e->getRHS());
1445
1446 auto resultTy =
1447 mlir::cast<cir::VectorType>(cgf.convertType(e->getType()));
1448 if (cir::isFPOrVectorOfFPType(lhs.getType())) {
1449 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, e);
1450 auto cmpOpKind = cir::FCmpOpKind::une;
1451 lhs = builder.createVecFCompare(loc, resultTy, cmpOpKind, lhs, zeroVec);
1452 rhs = builder.createVecFCompare(loc, resultTy, cmpOpKind, rhs, zeroVec);
1453 } else {
1454 auto cmpOpKind = cir::CmpOpKind::ne;
1455 lhs = builder.createVecCompare(loc, resultTy, cmpOpKind, lhs, zeroVec);
1456 rhs = builder.createVecCompare(loc, resultTy, cmpOpKind, rhs, zeroVec);
1457 }
1458 return builder.createAnd(loc, lhs, rhs);
1459 }
1460
1462 mlir::Type resTy = cgf.convertType(e->getType());
1463 mlir::Location loc = cgf.getLoc(e->getExprLoc());
1464
1465 mlir::Value lhsCondV = cgf.evaluateExprAsBool(e->getLHS());
1466
1467 CIRGenFunction::ConditionalEvaluation eval(cgf, loc);
1468
1469 auto resOp = cir::TernaryOp::create(
1470 builder, loc, lhsCondV, /*trueBuilder=*/
1471 [&](mlir::OpBuilder &b, mlir::Location loc) {
1472 CIRGenFunction::LexicalScope lexScope{cgf, loc,
1473 b.getInsertionBlock()};
1474 cgf.curLexScope->setAsTernary();
1475 eval.beginEvaluation();
1476 mlir::Value res = cgf.evaluateExprAsBool(e->getRHS());
1477 eval.endEvaluation();
1478 lexScope.forceCleanup({&res});
1479 cir::YieldOp::create(b, loc, res);
1480 },
1481 /*falseBuilder*/
1482 [&](mlir::OpBuilder &b, mlir::Location loc) {
1483 CIRGenFunction::LexicalScope lexScope{cgf, loc,
1484 b.getInsertionBlock()};
1485 cgf.curLexScope->setAsTernary();
1486 auto res = cir::ConstantOp::create(b, loc, builder.getFalseAttr());
1487 cir::YieldOp::create(b, loc, res.getRes());
1488 });
1489 return maybePromoteBoolResult(resOp.getResult(), resTy);
1490 }
1491
1492 mlir::Value VisitBinLOr(const clang::BinaryOperator *e) {
1493 if (e->getType()->isVectorType()) {
1494 mlir::Location loc = cgf.getLoc(e->getExprLoc());
1495 mlir::Type lhsTy = cgf.convertType(e->getLHS()->getType());
1496 mlir::Value zeroVec = builder.getNullValue(lhsTy, loc);
1497
1498 mlir::Value lhs = Visit(e->getLHS());
1499 mlir::Value rhs = Visit(e->getRHS());
1500
1501 auto resultTy =
1502 mlir::cast<cir::VectorType>(cgf.convertType(e->getType()));
1503 if (cir::isFPOrVectorOfFPType(lhs.getType())) {
1504 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, e);
1505 auto cmpOpKind = cir::FCmpOpKind::une;
1506 lhs = builder.createVecFCompare(loc, resultTy, cmpOpKind, lhs, zeroVec);
1507 rhs = builder.createVecFCompare(loc, resultTy, cmpOpKind, rhs, zeroVec);
1508 } else {
1509 auto cmpOpKind = cir::CmpOpKind::ne;
1510 lhs = builder.createVecCompare(loc, resultTy, cmpOpKind, lhs, zeroVec);
1511 rhs = builder.createVecCompare(loc, resultTy, cmpOpKind, rhs, zeroVec);
1512 }
1513 return builder.createOr(loc, lhs, rhs);
1514 }
1515
1517 mlir::Type resTy = cgf.convertType(e->getType());
1518 mlir::Location loc = cgf.getLoc(e->getExprLoc());
1519
1520 mlir::Value lhsCondV = cgf.evaluateExprAsBool(e->getLHS());
1521
1522 CIRGenFunction::ConditionalEvaluation eval(cgf, loc);
1523
1524 auto resOp = cir::TernaryOp::create(
1525 builder, loc, lhsCondV, /*trueBuilder=*/
1526 [&](mlir::OpBuilder &b, mlir::Location loc) {
1527 CIRGenFunction::LexicalScope lexScope{cgf, loc,
1528 b.getInsertionBlock()};
1529 cgf.curLexScope->setAsTernary();
1530 auto res = cir::ConstantOp::create(b, loc, builder.getTrueAttr());
1531 cir::YieldOp::create(b, loc, res.getRes());
1532 },
1533 /*falseBuilder*/
1534 [&](mlir::OpBuilder &b, mlir::Location loc) {
1535 CIRGenFunction::LexicalScope lexScope{cgf, loc,
1536 b.getInsertionBlock()};
1537 cgf.curLexScope->setAsTernary();
1538 eval.beginEvaluation();
1539 mlir::Value res = cgf.evaluateExprAsBool(e->getRHS());
1540 eval.endEvaluation();
1541 lexScope.forceCleanup({&res});
1542 cir::YieldOp::create(b, loc, res);
1543 });
1544
1545 return maybePromoteBoolResult(resOp.getResult(), resTy);
1546 }
1547
1548 mlir::Value VisitBinPtrMemD(const BinaryOperator *e) {
1549 return emitLoadOfLValue(e);
1550 }
1551
1552 mlir::Value VisitBinPtrMemI(const BinaryOperator *e) {
1553 return emitLoadOfLValue(e);
1554 }
1555
1556 // Other Operators.
1557 mlir::Value VisitBlockExpr(const BlockExpr *e) {
1558 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: block");
1559 return {};
1560 }
1561
1562 mlir::Value VisitChooseExpr(ChooseExpr *e) {
1563 return Visit(e->getChosenSubExpr());
1564 }
1565
1566 mlir::Value VisitObjCStringLiteral(const ObjCStringLiteral *e) {
1567 cgf.cgm.errorNYI(e->getSourceRange(),
1568 "ScalarExprEmitter: objc string literal");
1569 return {};
1570 }
1571 mlir::Value VisitObjCBoxedExpr(ObjCBoxedExpr *e) {
1572 cgf.cgm.errorNYI(e->getSourceRange(), "ScalarExprEmitter: objc boxed");
1573 return {};
1574 }
1575 mlir::Value VisitObjCArrayLiteral(ObjCArrayLiteral *e) {
1576 cgf.cgm.errorNYI(e->getSourceRange(),
1577 "ScalarExprEmitter: objc array literal");
1578 return {};
1579 }
1580 mlir::Value VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *e) {
1581 cgf.cgm.errorNYI(e->getSourceRange(),
1582 "ScalarExprEmitter: objc dictionary literal");
1583 return {};
1584 }
1585
1586 mlir::Value convertVec3AndVec4(CIRGenBuilderTy &builder, mlir::Location loc,
1587 mlir::Value src, unsigned numElementsDst) {
1588 static constexpr int64_t mask[] = {0, 1, 2, -1};
1589 return builder.createVecShuffle(
1590 loc, src, llvm::ArrayRef<int64_t>(mask, numElementsDst));
1591 }
1592
1593 // Create cast instructions for converting MLIR value \p Src to MLIR type \p
1594 // DstTy. \p Src has the same size as \p DstTy. Both are single value types
1595 // but could be scalar or vectors of different lengths, and either can be
1596 // pointer.
1597 //
1598 // There are 4 cases:
1599 // 1. non-pointer -> non-pointer : needs 1 bitcast
1600 // 2. pointer -> pointer : needs 1 bitcast or addrspacecast
1601 // 3. pointer -> non-pointer
1602 // a) pointer -> intptr_t : needs 1 ptrtoint
1603 // b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast
1604 // 4. non-pointer -> pointer
1605 // a) intptr_t -> pointer : needs 1 inttoptr
1606 // b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr
1607 //
1608 // Note: for cases 3b and 4b two casts are required since LLVM casts do not
1609 // allow casting directly between pointer types and non-integer non-pointer
1610 // types.
1611 mlir::Value createCastsForTypeOfSameSize(mlir::Value src, mlir::Type dstTy) {
1612 mlir::Type srcTy = src.getType();
1613
1614 // Case 1.
1615 if (!isa<cir::PointerType>(srcTy) && !isa<cir::PointerType>(dstTy))
1616 return builder.createBitcast(src, dstTy);
1617
1618 // Case 2.
1619 if (isa<cir::PointerType>(srcTy) && isa<cir::PointerType>(dstTy)) {
1620 cgf.cgm.errorNYI(
1621 "ScalarExprEmitter: createCastsForTypeOfSameSize Case 2");
1622 return {};
1623 }
1624
1625 // Case 3.
1626 if (isa<cir::PointerType>(srcTy) && !isa<cir::PointerType>(dstTy)) {
1627 if (!isa<cir::IntType>(dstTy)) {
1628 cgf.cgm.errorNYI(
1629 "ScalarExprEmitter: createCastsForTypeOfSameSize Case 3a");
1630 }
1631
1632 cgf.cgm.errorNYI(
1633 "ScalarExprEmitter: createCastsForTypeOfSameSize Case 3a and 3b");
1634 return {};
1635 }
1636
1637 // Case 4b.
1638 if (!isa<cir::IntType>(srcTy)) {
1639 cgf.cgm.errorNYI(
1640 "ScalarExprEmitter: createCastsForTypeOfSameSize Case 4a");
1641 return {};
1642 }
1643 // Cases 4a and 4b.
1644 return builder.createIntToPtr(src, dstTy);
1645 }
1646
1647 mlir::Value VisitAsTypeExpr(AsTypeExpr *e) {
1648 mlir::Value src = cgf.emitScalarExpr(e->getSrcExpr());
1649 mlir::Type srcTy = src.getType();
1650 mlir::Type dstTy = cgf.convertType(e->getType());
1651
1652 unsigned numElementsSrc = isa<cir::VectorType>(srcTy)
1653 ? cast<cir::VectorType>(srcTy).getFixedSize()
1654 : 0;
1655 unsigned numElementsDst = isa<cir::VectorType>(dstTy)
1656 ? cast<cir::VectorType>(dstTy).getFixedSize()
1657 : 0;
1658
1659 // Use bit vector expansion for ext_vector_type boolean vectors.
1660 if (e->getType()->isExtVectorBoolType()) {
1661 cgf.cgm.errorNYI(e->getSourceRange(),
1662 "ScalarExprEmitter: VisitAsTypeExpr ExtVectorBoolType");
1663 return {};
1664 }
1665
1666 // Going from vec3 to non-vec3 is a special case and requires a shuffle
1667 // vector to get a vec4, then a bitcast if the target type is different.
1668 if (numElementsSrc == 3 && numElementsDst != 3) {
1669 cgf.cgm.errorNYI(e->getSourceRange(),
1670 "ScalarExprEmitter: VisitAsTypeExpr numElemsSrc = 3, "
1671 "numElemsDst != 3");
1672 return {};
1673 }
1674
1675 // Going from non-vec3 to vec3 is a special case and requires a bitcast
1676 // to vec4 if the original type is not vec4, then a shuffle vector to
1677 // get a vec3.
1678 if (numElementsSrc != 3 && numElementsDst == 3) {
1679 mlir::Location loc = cgf.getLoc(e->getExprLoc());
1680 auto dstElemTy = cast<cir::VectorType>(dstTy).getElementType();
1681 auto dstVec4Ty = cir::VectorType::getFixed(dstElemTy, 4);
1682 src = createCastsForTypeOfSameSize(src, dstVec4Ty);
1683 src = convertVec3AndVec4(builder, loc, src, 3);
1684 return src;
1685 }
1686
1687 return createCastsForTypeOfSameSize(src, dstTy);
1688 }
1689
1690 mlir::Value VisitAtomicExpr(AtomicExpr *e) {
1691 return cgf.emitAtomicExpr(e).getValue();
1692 }
1693};
1694
1695LValue ScalarExprEmitter::emitCompoundAssignLValue(
1696 const CompoundAssignOperator *e,
1697 mlir::Value (ScalarExprEmitter::*func)(const BinOpInfo &),
1698 mlir::Value &result) {
1700 return cgf.emitScalarCompoundAssignWithComplex(e, result);
1701
1702 QualType lhsTy = e->getLHS()->getType();
1703 BinOpInfo opInfo;
1704
1705 // Emit the RHS first. __block variables need to have the rhs evaluated
1706 // first, plus this should improve codegen a little.
1707
1708 QualType promotionTypeCR = getPromotionType(e->getComputationResultType());
1709 if (promotionTypeCR.isNull())
1710 promotionTypeCR = e->getComputationResultType();
1711
1712 QualType promotionTypeLHS = getPromotionType(e->getComputationLHSType());
1713 QualType promotionTypeRHS = getPromotionType(e->getRHS()->getType());
1714
1715 if (!promotionTypeRHS.isNull())
1716 opInfo.rhs = cgf.emitPromotedScalarExpr(e->getRHS(), promotionTypeRHS);
1717 else
1718 opInfo.rhs = Visit(e->getRHS());
1719
1720 opInfo.fullType = promotionTypeCR;
1721 opInfo.compType = opInfo.fullType;
1722 if (const auto *vecType = opInfo.fullType->getAs<VectorType>())
1723 opInfo.compType = vecType->getElementType();
1724 opInfo.opcode = e->getOpcode();
1725 opInfo.fpFeatures = e->getFPFeaturesInEffect(cgf.getLangOpts());
1726 opInfo.e = e;
1727 opInfo.loc = e->getSourceRange();
1728
1729 // Load/convert the LHS
1730 LValue lhsLV = cgf.emitLValue(e->getLHS());
1731
1732 if (lhsTy->getAs<AtomicType>()) {
1733 cgf.cgm.errorNYI(result.getLoc(), "atomic lvalue assign");
1734 return LValue();
1735 }
1736
1737 opInfo.lhs = emitLoadOfLValue(lhsLV, e->getExprLoc());
1738
1739 CIRGenFunction::SourceLocRAIIObject sourceloc{cgf, e->getSourceRange()};
1740 SourceLocation loc = e->getExprLoc();
1741 if (!promotionTypeLHS.isNull())
1742 opInfo.lhs = emitScalarConversion(opInfo.lhs, lhsTy, promotionTypeLHS, loc);
1743 else
1744 opInfo.lhs = emitScalarConversion(opInfo.lhs, lhsTy,
1745 e->getComputationLHSType(), loc);
1746
1747 // Expand the binary operator.
1748 result = (this->*func)(opInfo);
1749
1750 // Convert the result back to the LHS type,
1751 // potentially with Implicit Conversion sanitizer check.
1752 result = emitScalarConversion(result, promotionTypeCR, lhsTy, loc,
1753 ScalarConversionOpts(cgf.sanOpts));
1754
1755 // Store the result value into the LHS lvalue. Bit-fields are handled
1756 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1757 // 'An assignment expression has the value of the left operand after the
1758 // assignment...'.
1759 if (lhsLV.isBitField())
1760 cgf.emitStoreThroughBitfieldLValue(RValue::get(result), lhsLV);
1761 else
1762 cgf.emitStoreThroughLValue(RValue::get(result), lhsLV);
1763
1765
1766 return lhsLV;
1767}
1768
1769mlir::Value ScalarExprEmitter::emitComplexToScalarConversion(mlir::Location lov,
1770 mlir::Value value,
1771 CastKind kind,
1772 QualType destTy) {
1773 cir::CastKind castOpKind;
1774 switch (kind) {
1775 case CK_FloatingComplexToReal:
1776 castOpKind = cir::CastKind::float_complex_to_real;
1777 break;
1778 case CK_IntegralComplexToReal:
1779 castOpKind = cir::CastKind::int_complex_to_real;
1780 break;
1781 case CK_FloatingComplexToBoolean:
1782 castOpKind = cir::CastKind::float_complex_to_bool;
1783 break;
1784 case CK_IntegralComplexToBoolean:
1785 castOpKind = cir::CastKind::int_complex_to_bool;
1786 break;
1787 default:
1788 llvm_unreachable("invalid complex-to-scalar cast kind");
1789 }
1790
1791 return builder.createCast(lov, castOpKind, value, cgf.convertType(destTy));
1792}
1793
1794mlir::Value ScalarExprEmitter::emitPromoted(const Expr *e,
1795 QualType promotionType) {
1796 e = e->IgnoreParens();
1797 if (const auto *bo = dyn_cast<BinaryOperator>(e)) {
1798 switch (bo->getOpcode()) {
1799#define HANDLE_BINOP(OP) \
1800 case BO_##OP: \
1801 return emit##OP(emitBinOps(bo, promotionType));
1802 HANDLE_BINOP(Add)
1803 HANDLE_BINOP(Sub)
1804 HANDLE_BINOP(Mul)
1805 HANDLE_BINOP(Div)
1806#undef HANDLE_BINOP
1807 default:
1808 break;
1809 }
1810 } else if (const auto *uo = dyn_cast<UnaryOperator>(e)) {
1811 switch (uo->getOpcode()) {
1812 case UO_Imag:
1813 case UO_Real:
1814 return VisitRealImag(uo, promotionType);
1815 case UO_Minus:
1816 return VisitUnaryMinus(uo, promotionType);
1817 case UO_Plus:
1818 return VisitUnaryPlus(uo, promotionType);
1819 default:
1820 break;
1821 }
1822 }
1823 mlir::Value result = Visit(const_cast<Expr *>(e));
1824 if (result) {
1825 if (!promotionType.isNull())
1826 return emitPromotedValue(result, promotionType);
1827 return emitUnPromotedValue(result, e->getType());
1828 }
1829 return result;
1830}
1831
1832mlir::Value ScalarExprEmitter::emitCompoundAssign(
1833 const CompoundAssignOperator *e,
1834 mlir::Value (ScalarExprEmitter::*func)(const BinOpInfo &)) {
1835
1836 bool ignore = std::exchange(ignoreResultAssign, false);
1837 mlir::Value rhs;
1838 LValue lhs = emitCompoundAssignLValue(e, func, rhs);
1839
1840 // If the result is clearly ignored, return now.
1841 if (ignore)
1842 return {};
1843
1844 // The result of an assignment in C is the assigned r-value.
1845 if (!cgf.getLangOpts().CPlusPlus)
1846 return rhs;
1847
1848 // If the lvalue is non-volatile, return the computed value of the assignment.
1849 if (!lhs.isVolatile())
1850 return rhs;
1851
1852 // Otherwise, reload the value.
1853 return emitLoadOfLValue(lhs, e->getExprLoc());
1854}
1855
1856mlir::Value
1857ScalarExprEmitter::VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *e) {
1858 ASTContext &context = cgf.getContext();
1859 mlir::Location loc = cgf.getLoc(e->getSourceRange());
1860 cir::GlobalOp globalConstStr =
1861 cgf.cgm.createGlobalString(loc, e->ComputeName(context), "__usn_str");
1862
1863 // Unlike LLVM IR, CIR pointers are typed, so the bitcast and the address
1864 // space cast are emitted as separate operations when both are needed.
1865 mlir::Value addr = builder.createGetGlobal(loc, globalConstStr);
1866 auto exprTy = mlir::cast<cir::PointerType>(convertType(e->getType()));
1867 auto addrTy = mlir::cast<cir::PointerType>(addr.getType());
1868 if (addrTy.getAddrSpace() != exprTy.getAddrSpace())
1869 addr = cgf.performAddrSpaceCast(
1870 addr, builder.getPointerTo(addrTy.getPointee(), exprTy.getAddrSpace()));
1871 return builder.createBitcast(loc, addr, exprTy);
1872}
1873
1874mlir::Value ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *e) {
1875 CIRGenFunction::FullExprCleanupScope scope(cgf, e->getSubExpr());
1876 mlir::Value v = Visit(e->getSubExpr());
1877 // Defend against dominance problems caused by jumps out of expression
1878 // evaluation through the shared cleanup block.
1879 scope.exit({&v});
1880 return v;
1881}
1882
1883} // namespace
1884
1885LValue
1887 ScalarExprEmitter emitter(*this, builder);
1888 mlir::Value result;
1889 switch (e->getOpcode()) {
1890#define COMPOUND_OP(Op) \
1891 case BO_##Op##Assign: \
1892 return emitter.emitCompoundAssignLValue(e, &ScalarExprEmitter::emit##Op, \
1893 result)
1894 COMPOUND_OP(Mul);
1895 COMPOUND_OP(Div);
1896 COMPOUND_OP(Rem);
1897 COMPOUND_OP(Add);
1898 COMPOUND_OP(Sub);
1899 COMPOUND_OP(Shl);
1900 COMPOUND_OP(Shr);
1902 COMPOUND_OP(Xor);
1903 COMPOUND_OP(Or);
1904#undef COMPOUND_OP
1905
1906 case BO_PtrMemD:
1907 case BO_PtrMemI:
1908 case BO_Mul:
1909 case BO_Div:
1910 case BO_Rem:
1911 case BO_Add:
1912 case BO_Sub:
1913 case BO_Shl:
1914 case BO_Shr:
1915 case BO_LT:
1916 case BO_GT:
1917 case BO_LE:
1918 case BO_GE:
1919 case BO_EQ:
1920 case BO_NE:
1921 case BO_Cmp:
1922 case BO_And:
1923 case BO_Xor:
1924 case BO_Or:
1925 case BO_LAnd:
1926 case BO_LOr:
1927 case BO_Assign:
1928 case BO_Comma:
1929 llvm_unreachable("Not valid compound assignment operators");
1930 }
1931 llvm_unreachable("Unhandled compound assignment operator");
1932}
1933
1934/// Emit the computation of the specified expression of scalar type.
1936 bool ignoreResultAssign) {
1937 assert(e && hasScalarEvaluationKind(e->getType()) &&
1938 "Invalid scalar expression to emit");
1939
1940 return ScalarExprEmitter(*this, builder, ignoreResultAssign)
1941 .Visit(const_cast<Expr *>(e));
1942}
1943
1945 QualType promotionType) {
1946 if (!promotionType.isNull())
1947 return ScalarExprEmitter(*this, builder).emitPromoted(e, promotionType);
1948 return ScalarExprEmitter(*this, builder).Visit(const_cast<Expr *>(e));
1949}
1950
1951[[maybe_unused]] static bool mustVisitNullValue(const Expr *e) {
1952 // If a null pointer expression's type is the C++0x nullptr_t and
1953 // the expression is not a simple literal, it must be evaluated
1954 // for its potential side effects.
1956 return false;
1957 return e->getType()->isNullPtrType();
1958}
1959
1960/// If \p e is a widened promoted integer, get its base (unpromoted) type.
1961static std::optional<QualType>
1962getUnwidenedIntegerType(const ASTContext &astContext, const Expr *e) {
1963 const Expr *base = e->IgnoreImpCasts();
1964 if (e == base)
1965 return std::nullopt;
1966
1967 QualType baseTy = base->getType();
1968 if (!astContext.isPromotableIntegerType(baseTy) ||
1969 astContext.getTypeSize(baseTy) >= astContext.getTypeSize(e->getType()))
1970 return std::nullopt;
1971
1972 return baseTy;
1973}
1974
1975/// Check if \p e is a widened promoted integer.
1976[[maybe_unused]] static bool isWidenedIntegerOp(const ASTContext &astContext,
1977 const Expr *e) {
1978 return getUnwidenedIntegerType(astContext, e).has_value();
1979}
1980
1981/// Check if we can skip the overflow check for \p Op.
1982[[maybe_unused]] static bool canElideOverflowCheck(const ASTContext &astContext,
1983 const BinOpInfo &op) {
1984 assert((isa<UnaryOperator>(op.e) || isa<BinaryOperator>(op.e)) &&
1985 "Expected a unary or binary operator");
1986
1987 // If the binop has constant inputs and we can prove there is no overflow,
1988 // we can elide the overflow check.
1989 if (!op.mayHaveIntegerOverflow())
1990 return true;
1991
1992 // If a unary op has a widened operand, the op cannot overflow.
1993 if (const auto *uo = dyn_cast<UnaryOperator>(op.e))
1994 return !uo->canOverflow();
1995
1996 // We usually don't need overflow checks for binops with widened operands.
1997 // Multiplication with promoted unsigned operands is a special case.
1998 const auto *bo = cast<BinaryOperator>(op.e);
1999 std::optional<QualType> optionalLHSTy =
2000 getUnwidenedIntegerType(astContext, bo->getLHS());
2001 if (!optionalLHSTy)
2002 return false;
2003
2004 std::optional<QualType> optionalRHSTy =
2005 getUnwidenedIntegerType(astContext, bo->getRHS());
2006 if (!optionalRHSTy)
2007 return false;
2008
2009 QualType lhsTy = *optionalLHSTy;
2010 QualType rhsTy = *optionalRHSTy;
2011
2012 // This is the simple case: binops without unsigned multiplication, and with
2013 // widened operands. No overflow check is needed here.
2014 if ((op.opcode != BO_Mul && op.opcode != BO_MulAssign) ||
2015 !lhsTy->isUnsignedIntegerType() || !rhsTy->isUnsignedIntegerType())
2016 return true;
2017
2018 // For unsigned multiplication the overflow check can be elided if either one
2019 // of the unpromoted types are less than half the size of the promoted type.
2020 unsigned promotedSize = astContext.getTypeSize(op.e->getType());
2021 return (2 * astContext.getTypeSize(lhsTy)) < promotedSize ||
2022 (2 * astContext.getTypeSize(rhsTy)) < promotedSize;
2023}
2024
2025/// Emit pointer + index arithmetic.
2027 const BinOpInfo &op,
2028 bool isSubtraction) {
2029 // Must have binary (not unary) expr here. Unary pointer
2030 // increment/decrement doesn't use this path.
2032
2033 mlir::Value pointer = op.lhs;
2034 Expr *pointerOperand = expr->getLHS();
2035 mlir::Value index = op.rhs;
2036 Expr *indexOperand = expr->getRHS();
2037
2038 // In the case of subtraction, the FE has ensured that the LHS is always the
2039 // pointer. However, addition can have the pointer on either side. We will
2040 // always have a pointer operand and an integer operand, so if the LHS wasn't
2041 // a pointer, we need to swap our values.
2042 if (!isSubtraction && !mlir::isa<cir::PointerType>(pointer.getType())) {
2043 std::swap(pointer, index);
2044 std::swap(pointerOperand, indexOperand);
2045 }
2046 assert(mlir::isa<cir::PointerType>(pointer.getType()) &&
2047 "Need a pointer operand");
2048 assert(mlir::isa<cir::IntType>(index.getType()) && "Need an integer operand");
2049
2050 // Some versions of glibc and gcc use idioms (particularly in their malloc
2051 // routines) that add a pointer-sized integer (known to be a pointer value)
2052 // to a null pointer in order to cast the value back to an integer or as
2053 // part of a pointer alignment algorithm. This is undefined behavior, but
2054 // we'd like to be able to compile programs that use it.
2055 //
2056 // Normally, we'd generate a GEP with a null-pointer base here in response
2057 // to that code, but it's also UB to dereference a pointer created that
2058 // way. Instead (as an acknowledged hack to tolerate the idiom) we will
2059 // generate a direct cast of the integer value to a pointer.
2060 //
2061 // The idiom (p = nullptr + N) is not met if any of the following are true:
2062 //
2063 // The operation is subtraction.
2064 // The index is not pointer-sized.
2065 // The pointer type is not byte-sized.
2066 //
2068 cgf.getContext(), op.opcode, expr->getLHS(), expr->getRHS()))
2069 return cgf.getBuilder().createIntToPtr(index, pointer.getType());
2070
2071 // Differently from LLVM codegen, ABI bits for index sizes is handled during
2072 // LLVM lowering.
2073
2074 // If this is subtraction, negate the index.
2075 if (isSubtraction)
2076 index = cgf.getBuilder().createNeg(cgf.getLoc(op.e->getExprLoc()), index);
2077
2079
2080 const PointerType *pointerType =
2081 pointerOperand->getType()->getAs<PointerType>();
2082 if (!pointerType) {
2083 cgf.cgm.errorNYI("Objective-C:pointer arithmetic with non-pointer type");
2084 return nullptr;
2085 }
2086
2087 QualType elementType = pointerType->getPointeeType();
2088 if (const VariableArrayType *vla =
2089 cgf.getContext().getAsVariableArrayType(elementType)) {
2090 mlir::Value numElements = cgf.getVLASize(vla).numElts;
2091 mlir::Location loc = cgf.getLoc(op.e->getExprLoc());
2092 index = cgf.getBuilder().createCast(cir::CastKind::integral, index,
2093 numElements.getType());
2094 // GEP indexes are signed, and scaling an index isn't permitted to
2095 // signed-overflow, so we use the same semantics for our explicit
2096 // multiply. We suppress this if overflow is not undefined behavior.
2097 cir::OverflowFlags overflowFlags = cgf.getLangOpts().PointerOverflowDefined
2098 ? cir::OverflowFlags::None
2099 : cir::OverflowFlags::NoSignedWrap;
2100 index = cgf.getBuilder().createMul(loc, index, numElements, overflowFlags);
2102 return cir::PtrStrideOp::create(cgf.getBuilder(), loc, pointer.getType(),
2103 pointer, index);
2104 }
2105
2107 return cir::PtrStrideOp::create(cgf.getBuilder(),
2108 cgf.getLoc(op.e->getExprLoc()),
2109 pointer.getType(), pointer, index);
2110}
2111
2112static bool isIntegerVectorBinOp(mlir::Type ty) {
2113 auto vecTy = mlir::dyn_cast<cir::VectorType>(ty);
2114 return vecTy && mlir::isa<cir::IntType>(vecTy.getElementType());
2115}
2116
2117// Construct a cir.fmuladd op to represent a fused mul-add of `mulOp` and
2118// `addend`. Use negMul and negAdd to negate the first operand of the mul or
2119// the addend respectively. This allows fmuladd to represent a*b-c, or c-a*b.
2120// Patterns in LLVM should catch the negated forms and translate them to
2121// efficient operations.
2122static mlir::Value buildFMulAdd(mlir::Location addLoc, cir::FMulOp mulOp,
2123 mlir::Value addend, CIRGenBuilderTy &builder,
2124 bool negMul, bool negAdd) {
2125 mlir::Location loc = builder.getFusedLoc({mulOp.getLoc(), addLoc});
2126 mlir::Value mulOp0 = mulOp.getLhs();
2127 mlir::Value mulOp1 = mulOp.getRhs();
2128 if (negMul)
2129 mulOp0 = builder.createFNeg(loc, mulOp0);
2130 if (negAdd)
2131 addend = builder.createFNeg(loc, addend);
2132
2133 // Carry the mul's fenv attribute so a constrained fmul yields a constrained
2134 // fmuladd; the builder is under the add's FP options, not the mul's.
2135 mlir::Value fmuladd = cir::FMulAddOp::create(
2136 builder, loc, addend.getType(), mulOp0, mulOp1, addend,
2137 mulOp.getFenvAttr(), builder.getFastMathFlagsAttr());
2138 mulOp.erase();
2139 return fmuladd;
2140}
2141
2142// Check whether it would be legal to emit a cir.fmuladd op to represent op
2143// and if so, build it.
2144//
2145// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2146// Does NOT check the type of the operation - it's assumed that this function
2147// will be called from contexts where it's known that the type is contractable.
2148static mlir::Value tryEmitFMulAdd(mlir::Location loc, const BinOpInfo &op,
2149 CIRGenBuilderTy &builder,
2150 bool isSub = false) {
2151 assert((op.opcode == BO_Add || op.opcode == BO_AddAssign ||
2152 op.opcode == BO_Sub || op.opcode == BO_SubAssign) &&
2153 "Only fadd/fsub can be the root of an fmuladd.");
2154
2155 // Check whether this op is fusable, i.e. -ffp-contract=on. -ffp-contract=fast
2156 // is represented by the `contract` flag on the fmul/fadd instead.
2157 if (!op.fpFeatures.allowFPContractWithinStatement())
2158 return nullptr;
2159
2160 mlir::Value lhs = op.lhs;
2161 mlir::Value rhs = op.rhs;
2162
2163 // Peek through fneg to look for fmul. Make sure the fneg has no other users,
2164 // and that it is the only use of its operand.
2165 bool negLHS = false;
2166 if (auto lhsNeg = lhs.getDefiningOp<cir::FNegOp>()) {
2167 if (lhsNeg.getResult().use_empty() && lhsNeg.getInput().hasOneUse()) {
2168 lhs = lhsNeg.getInput();
2169 negLHS = true;
2170 }
2171 }
2172
2173 bool negRHS = false;
2174 if (auto rhsNeg = rhs.getDefiningOp<cir::FNegOp>()) {
2175 if (rhsNeg.getResult().use_empty() && rhsNeg.getInput().hasOneUse()) {
2176 rhs = rhsNeg.getInput();
2177 negRHS = true;
2178 }
2179 }
2180
2181 // We have a potentially fusable op. Look for a mul on one of the operands.
2182 // Also make sure that the mul result isn't used directly. In that case,
2183 // there's no point creating a muladd operation.
2184 if (auto lhsMul = lhs.getDefiningOp<cir::FMulOp>()) {
2185 if (lhsMul.getResult().use_empty() || negLHS) {
2186 // If we looked through fneg, erase it.
2187 if (negLHS)
2188 op.lhs.getDefiningOp<cir::FNegOp>().erase();
2189 return buildFMulAdd(loc, lhsMul, op.rhs, builder, negLHS, isSub);
2190 }
2191 }
2192 if (auto rhsMul = rhs.getDefiningOp<cir::FMulOp>()) {
2193 if (rhsMul.getResult().use_empty() || negRHS) {
2194 // If we looked through fneg, erase it.
2195 if (negRHS)
2196 op.rhs.getDefiningOp<cir::FNegOp>().erase();
2197 return buildFMulAdd(loc, rhsMul, op.lhs, builder, isSub ^ negRHS, false);
2198 }
2199 }
2200
2201 return nullptr;
2202}
2203
2204mlir::Value ScalarExprEmitter::emitFixedPointIncDec(const UnaryOperator *e,
2205 mlir::Value value,
2206 QualType type) {
2207 // Fixed-point types are tricky. In some cases, it isn't possible to
2208 // represent a 1 or a -1 in the type at all. Piggyback off of
2209 // EmitFixedPointBinOp to avoid having to reimplement saturation.
2210 BinOpInfo info;
2211 info.loc = e->getSourceRange();
2212 info.fpFeatures = e->getFPFeaturesInEffect(cgf.getLangOpts());
2213 info.e = e;
2214 info.compType = info.fullType = e->getType();
2215 info.opcode = e->isIncrementOp() ? BO_Add : BO_Sub;
2216 info.lhs = value;
2217 info.rhs = builder.getConstInt(cgf.getLoc(info.loc), value.getType(), 1);
2218 // If the type is signed, it's better to represent this as +(-1) or -(-1),
2219 // since -1 is guaranteed to be representable.
2220 // FIXME(cir): This is a carry-over from Classic codegen, we should probably
2221 // figure out if ++ -> -(-1) and -- -> +(-1) is REALLY what we want? For now
2222 // we are just doing what classic does here.
2223 if (type->isSignedFixedPointType()) {
2224 info.opcode = e->isIncrementOp() ? BO_Sub : BO_Add;
2225 info.rhs = builder.createNeg(cgf.getLoc(info.loc), info.rhs);
2226 }
2227 // Now, convert from our invented integer literal to the type of the unary
2228 // op. This will upscale and saturate if necessary. This value can become
2229 // undef in some cases.
2230 CIRGenFixedPointBuilder fpbuilder(builder, cgf.getLoc(info.loc));
2231 auto dstSema = cgf.getContext().getFixedPointSemantics(info.fullType);
2232 info.rhs =
2233 fpbuilder.createIntegerToFixed(info.rhs, /*srcIsSigned=*/true, dstSema);
2234 return emitFixedPointBinOp(info);
2235}
2236
2237mlir::Value ScalarExprEmitter::emitFixedPointConversion(mlir::Value src,
2238 QualType srcTy,
2239 QualType dstTy,
2240 mlir::Location loc) {
2241 assert(srcTy->isFixedPointType() || dstTy->isFixedPointType());
2242
2243 CIRGenFixedPointBuilder fpBuilder(builder, loc);
2244 mlir::Value result;
2245 if (srcTy->isRealFloatingType()) {
2246 assert(dstTy->isFixedPointType());
2247 result = fpBuilder.createFloatingToFixed(
2248 src, cgf.getContext().getFixedPointSemantics(dstTy));
2249 } else if (dstTy->isRealFloatingType()) {
2250 assert(srcTy->isFixedPointType());
2251 result = fpBuilder.createFixedToFloating(
2252 src, cgf.getContext().getFixedPointSemantics(srcTy),
2253 cgf.convertType(dstTy));
2254 } else {
2255 llvm::FixedPointSemantics srcFPSema =
2257 llvm::FixedPointSemantics dstFPSema =
2259
2260 if (dstTy->isIntegerType())
2261 result = fpBuilder.createFixedToInteger(
2262 src, srcFPSema, dstFPSema.getWidth(), dstFPSema.isSigned());
2263 else if (srcTy->isIntegerType())
2264 result =
2265 fpBuilder.createIntegerToFixed(src, srcFPSema.isSigned(), dstFPSema);
2266 else {
2267 assert(srcTy->isFixedPointType() && dstTy->isFixedPointType());
2268 result = fpBuilder.createFixedToFixed(src, srcFPSema, dstFPSema);
2269 }
2270 }
2271 return result;
2272}
2273
2274mlir::Value ScalarExprEmitter::emitMul(const BinOpInfo &ops) {
2275 const mlir::Location loc = cgf.getLoc(ops.loc);
2276 if (!isIntegerVectorBinOp(ops.lhs.getType()) &&
2277 ops.compType->isSignedIntegerOrEnumerationType()) {
2278 switch (cgf.getLangOpts().getSignedOverflowBehavior()) {
2279 case LangOptions::SOB_Defined:
2280 if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
2281 return builder.createMul(loc, ops.lhs, ops.rhs);
2282 [[fallthrough]];
2283 case LangOptions::SOB_Undefined:
2284 if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
2285 return builder.createNSWMul(loc, ops.lhs, ops.rhs);
2286 [[fallthrough]];
2287 case LangOptions::SOB_Trapping:
2288 if (canElideOverflowCheck(cgf.getContext(), ops))
2289 return builder.createNSWMul(loc, ops.lhs, ops.rhs);
2290 cgf.cgm.errorNYI("sanitizers");
2291 }
2292 }
2293
2294 if (ops.fullType->isConstantMatrixType()) {
2295 CIRGenFunction::CIRGenFPOptionsRAII fpOptsRAII(cgf, ops.fpFeatures);
2296
2297 if (isa<cir::MatrixType>(ops.lhs.getType()) &&
2298 isa<cir::MatrixType>(ops.rhs.getType()))
2299 return builder.createMatrixMultiply(loc, ops.lhs, ops.rhs);
2300
2301 auto [lhs, rhs] =
2302 builder.splatMatrixOpOperandsIfNecessary(loc, ops.lhs, ops.rhs);
2303 if (cir::isFPOrVectorOrMatrixOfFPType(lhs.getType()))
2304 return builder.createFMul(loc, lhs, rhs);
2305 return builder.createMul(loc, lhs, rhs);
2306 }
2307
2308 if (ops.compType->isUnsignedIntegerType() &&
2309 cgf.sanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
2310 !canElideOverflowCheck(cgf.getContext(), ops))
2311 cgf.cgm.errorNYI("unsigned int overflow sanitizer");
2312
2313 if (cir::isFPOrVectorOfFPType(ops.lhs.getType())) {
2314 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, ops.fpFeatures);
2315 return builder.createFMul(loc, ops.lhs, ops.rhs);
2316 }
2317
2318 if (ops.isFixedPointOp())
2319 return emitFixedPointBinOp(ops);
2320
2321 return cir::MulOp::create(builder, cgf.getLoc(ops.loc),
2322 cgf.convertType(ops.fullType), ops.lhs, ops.rhs);
2323}
2324mlir::Value ScalarExprEmitter::emitDiv(const BinOpInfo &ops) {
2325 const mlir::Location loc = cgf.getLoc(ops.loc);
2326 if (cir::isFPOrVectorOfFPType(ops.lhs.getType())) {
2327 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, ops.fpFeatures);
2328 return builder.createFDiv(loc, ops.lhs, ops.rhs);
2329 }
2330
2331 if (ops.fullType->isConstantMatrixType()) {
2332 assert(mlir::isa<cir::MatrixType>(ops.lhs.getType()) &&
2333 "first operand must be a matrix");
2334 assert(cir::isAnyIntegerOrFloatingPointType(ops.rhs.getType()) &&
2335 "second operand must be an arithmetic type");
2336
2337 auto [lhs, rhs] =
2338 builder.splatMatrixOpOperandsIfNecessary(loc, ops.lhs, ops.rhs);
2339
2340 CIRGenFunction::CIRGenFPOptionsRAII fpOptsRAII(cgf, ops.fpFeatures);
2341 if (cir::isFPOrVectorOrMatrixOfFPType(lhs.getType()))
2342 return builder.createFDiv(loc, lhs, rhs);
2343 return builder.createDiv(loc, lhs, rhs);
2344 }
2345
2346 if (ops.isFixedPointOp())
2347 return emitFixedPointBinOp(ops);
2348
2349 return cir::DivOp::create(builder, loc, cgf.convertType(ops.fullType),
2350 ops.lhs, ops.rhs);
2351}
2352mlir::Value ScalarExprEmitter::emitRem(const BinOpInfo &ops) {
2353 const mlir::Location loc = cgf.getLoc(ops.loc);
2354 if (cir::isFPOrVectorOfFPType(ops.lhs.getType())) {
2355 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, ops.fpFeatures);
2356 return builder.createFRem(loc, ops.lhs, ops.rhs);
2357 }
2358 return cir::RemOp::create(builder, loc, cgf.convertType(ops.fullType),
2359 ops.lhs, ops.rhs);
2360}
2361
2362mlir::Value ScalarExprEmitter::emitFixedPointBinOp(const BinOpInfo &ops) {
2363 // This is either a binary operation where at least one of the operands is
2364 // a fixed-point type, or a unary operation where the operand is a fixed-point
2365 // type. The result type of a binary operation is determined by
2366 // Sema::handleFixedPointConversions().
2367 QualType resultTy = ops.compType;
2368 QualType lhsTy, rhsTy;
2369 if (const auto *binOp = dyn_cast<BinaryOperator>(ops.e)) {
2370 rhsTy = binOp->getRHS()->getType();
2371 if (const auto *cao = dyn_cast<CompoundAssignOperator>(binOp)) {
2372 // For compound assignment, the effective type of the LHS at this point
2373 // is the computation LHS type, not the actual LHS type, and the final
2374 // result type is not the type of the expression but rather the
2375 // computation result type.
2376 lhsTy = cao->getComputationLHSType();
2377 resultTy = cao->getComputationResultType();
2378 } else {
2379 lhsTy = binOp->getLHS()->getType();
2380 }
2381 } else if (const auto *unOp = dyn_cast<UnaryOperator>(ops.e)) {
2382 lhsTy = unOp->getSubExpr()->getType();
2383 rhsTy = unOp->getSubExpr()->getType();
2384 }
2385 ASTContext &ctx = cgf.getContext();
2386 mlir::Value lhs = ops.lhs;
2387 mlir::Value rhs = ops.rhs;
2388
2389 auto lhsFixedSema = ctx.getFixedPointSemantics(lhsTy);
2390 auto rhsFixedSema = ctx.getFixedPointSemantics(rhsTy);
2391 auto resultFixedSema = ctx.getFixedPointSemantics(resultTy);
2392 auto commonFixedSema = lhsFixedSema.getCommonSemantics(rhsFixedSema);
2393
2394 // Perform the actual operation.
2395 mlir::Value result;
2396 CIRGenFixedPointBuilder fpbuilder(builder, cgf.getLoc(ops.loc));
2397 switch (ops.opcode) {
2398 case BO_AddAssign:
2399 case BO_Add:
2400 result = fpbuilder.createAdd(lhs, lhsFixedSema, rhs, rhsFixedSema);
2401 break;
2402 case BO_SubAssign:
2403 case BO_Sub:
2404 result = fpbuilder.createSub(lhs, lhsFixedSema, rhs, rhsFixedSema);
2405 break;
2406 case BO_MulAssign:
2407 case BO_Mul:
2408 result = fpbuilder.createMul(lhs, lhsFixedSema, rhs, rhsFixedSema);
2409 break;
2410 case BO_DivAssign:
2411 case BO_Div:
2412 result = fpbuilder.createDiv(lhs, lhsFixedSema, rhs, rhsFixedSema);
2413 break;
2414 case BO_ShlAssign:
2415 case BO_Shl:
2416 result = fpbuilder.createShl(lhs, lhsFixedSema, rhs);
2417 break;
2418 case BO_ShrAssign:
2419 case BO_Shr:
2420 result = fpbuilder.createShr(lhs, rhs);
2421 break;
2422 case BO_LT:
2423 case BO_GT:
2424 case BO_LE:
2425 case BO_GE:
2426 case BO_EQ:
2427 case BO_NE:
2428 return fpbuilder.createCmp(lhs, lhsFixedSema, rhs, rhsFixedSema,
2429 clangCmpToCIRCmp(ops.opcode));
2430 case BO_Cmp:
2431 case BO_LAnd:
2432 case BO_LOr:
2433 llvm_unreachable("Found unimplemented fixed point binary operation");
2434 case BO_PtrMemD:
2435 case BO_PtrMemI:
2436 case BO_Rem:
2437 case BO_Xor:
2438 case BO_And:
2439 case BO_Or:
2440 case BO_Assign:
2441 case BO_RemAssign:
2442 case BO_AndAssign:
2443 case BO_XorAssign:
2444 case BO_OrAssign:
2445 case BO_Comma:
2446 llvm_unreachable(
2447 "Found unsupported binary operation for fixed point types.");
2448 }
2449
2450 bool isShift = BinaryOperator::isShiftOp(ops.opcode) ||
2452 // Convert to the result type.
2453 return fpbuilder.createFixedToFixed(
2454 result, isShift ? lhsFixedSema : commonFixedSema, resultFixedSema);
2455}
2456
2457mlir::Value ScalarExprEmitter::emitAdd(const BinOpInfo &ops) {
2458 if (mlir::isa<cir::PointerType>(ops.lhs.getType()) ||
2459 mlir::isa<cir::PointerType>(ops.rhs.getType()))
2460 return emitPointerArithmetic(cgf, ops, /*isSubtraction=*/
2461 false);
2462
2463 const mlir::Location loc = cgf.getLoc(ops.loc);
2464 if (!isIntegerVectorBinOp(ops.lhs.getType()) &&
2465 ops.compType->isSignedIntegerOrEnumerationType()) {
2466 switch (cgf.getLangOpts().getSignedOverflowBehavior()) {
2467 case LangOptions::SOB_Defined:
2468 if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
2469 return builder.createAdd(loc, ops.lhs, ops.rhs);
2470 [[fallthrough]];
2471 case LangOptions::SOB_Undefined:
2472 if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
2473 return builder.createNSWAdd(loc, ops.lhs, ops.rhs);
2474 [[fallthrough]];
2475 case LangOptions::SOB_Trapping:
2476 if (canElideOverflowCheck(cgf.getContext(), ops))
2477 return builder.createNSWAdd(loc, ops.lhs, ops.rhs);
2478 cgf.cgm.errorNYI("sanitizers");
2479 }
2480 }
2481 if (ops.fullType->isConstantMatrixType()) {
2482 // Like llvm::MatrixBuilder::CreateAdd, splat a scalar operand to the matrix
2483 // type before adding.
2484 auto [lhs, rhs] =
2485 builder.splatMatrixOpOperandsIfNecessary(loc, ops.lhs, ops.rhs);
2486
2487 CIRGenFunction::CIRGenFPOptionsRAII fpOptsRAII(cgf, ops.fpFeatures);
2488 if (cir::isFPOrVectorOrMatrixOfFPType(lhs.getType()))
2489 return builder.createFAdd(loc, lhs, rhs);
2490 return builder.createAdd(loc, lhs, rhs);
2491 }
2492
2493 if (ops.compType->isUnsignedIntegerType() &&
2494 cgf.sanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
2495 !canElideOverflowCheck(cgf.getContext(), ops))
2496 cgf.cgm.errorNYI("unsigned int overflow sanitizer");
2497
2498 if (cir::isFPOrVectorOfFPType(ops.lhs.getType())) {
2499 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, ops.fpFeatures);
2500 // Try to form an fmuladd.
2501 if (mlir::Value fmuladd = tryEmitFMulAdd(loc, ops, builder))
2502 return fmuladd;
2503 return builder.createFAdd(loc, ops.lhs, ops.rhs);
2504 }
2505
2506 if (ops.isFixedPointOp())
2507 return emitFixedPointBinOp(ops);
2508
2509 return builder.createAdd(loc, ops.lhs, ops.rhs);
2510}
2511
2512mlir::Value ScalarExprEmitter::emitSub(const BinOpInfo &ops) {
2513 const mlir::Location loc = cgf.getLoc(ops.loc);
2514 // The LHS is always a pointer if either side is.
2515 if (!mlir::isa<cir::PointerType>(ops.lhs.getType())) {
2516 if (!isIntegerVectorBinOp(ops.lhs.getType()) &&
2517 ops.compType->isSignedIntegerOrEnumerationType()) {
2518 switch (cgf.getLangOpts().getSignedOverflowBehavior()) {
2519 case LangOptions::SOB_Defined: {
2520 if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
2521 return builder.createSub(loc, ops.lhs, ops.rhs);
2522 [[fallthrough]];
2523 }
2524 case LangOptions::SOB_Undefined:
2525 if (!cgf.sanOpts.has(SanitizerKind::SignedIntegerOverflow))
2526 return builder.createNSWSub(loc, ops.lhs, ops.rhs);
2527 [[fallthrough]];
2528 case LangOptions::SOB_Trapping:
2529 if (canElideOverflowCheck(cgf.getContext(), ops))
2530 return builder.createNSWSub(loc, ops.lhs, ops.rhs);
2531 cgf.cgm.errorNYI("sanitizers");
2532 }
2533 }
2534
2535 if (ops.fullType->isConstantMatrixType()) {
2536 // Like llvm::MatrixBuilder::CreateSub, splat a scalar operand to the
2537 // matrix type before adding.
2538 auto [lhs, rhs] =
2539 builder.splatMatrixOpOperandsIfNecessary(loc, ops.lhs, ops.rhs);
2540
2541 CIRGenFunction::CIRGenFPOptionsRAII fpOptsRAII(cgf, ops.fpFeatures);
2542 if (cir::isFPOrVectorOrMatrixOfFPType(lhs.getType()))
2543 return builder.createFSub(loc, lhs, rhs);
2544 return builder.createSub(loc, lhs, rhs);
2545 }
2546
2547 if (ops.compType->isUnsignedIntegerType() &&
2548 cgf.sanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
2549 !canElideOverflowCheck(cgf.getContext(), ops))
2550 cgf.cgm.errorNYI("unsigned int overflow sanitizer");
2551
2552 if (cir::isFPOrVectorOfFPType(ops.lhs.getType())) {
2553 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, ops.fpFeatures);
2554 // Try to form an fmuladd.
2555 if (mlir::Value fmuladd =
2556 tryEmitFMulAdd(loc, ops, builder, /*isSub=*/true))
2557 return fmuladd;
2558 return builder.createFSub(loc, ops.lhs, ops.rhs);
2559 }
2560
2561 if (ops.isFixedPointOp())
2562 return emitFixedPointBinOp(ops);
2563
2564 return builder.createSub(loc, ops.lhs, ops.rhs);
2565 }
2566
2567 // If the RHS is not a pointer, then we have normal pointer
2568 // arithmetic.
2569 if (!mlir::isa<cir::PointerType>(ops.rhs.getType()))
2570 return emitPointerArithmetic(cgf, ops, /*isSubtraction=*/true);
2571
2572 // Otherwise, this is a pointer subtraction
2573
2574 // Do the raw subtraction part.
2575 //
2576 // TODO(cir): note for LLVM lowering out of this; when expanding this into
2577 // LLVM we shall take VLA's, division by element size, etc.
2578 //
2579 // See more in `EmitSub` in CGExprScalar.cpp.
2581 return cir::PtrDiffOp::create(builder, cgf.getLoc(ops.loc), cgf.ptrDiffTy,
2582 ops.lhs, ops.rhs);
2583}
2584
2585mlir::Value ScalarExprEmitter::emitShl(const BinOpInfo &ops) {
2586 // TODO: This misses out on the sanitizer check below.
2587 if (ops.isFixedPointOp())
2588 return emitFixedPointBinOp(ops);
2589
2590 // CIR accepts shift between different types, meaning nothing special
2591 // to be done here. OTOH, LLVM requires the LHS and RHS to be the same type:
2592 // promote or truncate the RHS to the same size as the LHS.
2593
2594 bool sanitizeSignedBase = cgf.sanOpts.has(SanitizerKind::ShiftBase) &&
2595 ops.compType->hasSignedIntegerRepresentation() &&
2597 !cgf.getLangOpts().CPlusPlus20;
2598 bool sanitizeUnsignedBase =
2599 cgf.sanOpts.has(SanitizerKind::UnsignedShiftBase) &&
2600 ops.compType->hasUnsignedIntegerRepresentation();
2601 bool sanitizeBase = sanitizeSignedBase || sanitizeUnsignedBase;
2602 bool sanitizeExponent = cgf.sanOpts.has(SanitizerKind::ShiftExponent);
2603
2604 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2605 if (cgf.getLangOpts().OpenCL)
2606 cgf.cgm.errorNYI("opencl");
2607 else if ((sanitizeBase || sanitizeExponent) &&
2608 mlir::isa<cir::IntType>(ops.lhs.getType()))
2609 cgf.cgm.errorNYI("sanitizers");
2610
2611 return builder.createShiftLeft(cgf.getLoc(ops.loc), ops.lhs, ops.rhs);
2612}
2613
2614mlir::Value ScalarExprEmitter::emitShr(const BinOpInfo &ops) {
2615 // TODO: This misses out on the sanitizer check below.
2616 if (ops.isFixedPointOp())
2617 return emitFixedPointBinOp(ops);
2618
2619 // CIR accepts shift between different types, meaning nothing special
2620 // to be done here. OTOH, LLVM requires the LHS and RHS to be the same type:
2621 // promote or truncate the RHS to the same size as the LHS.
2622
2623 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2624 if (cgf.getLangOpts().OpenCL)
2625 cgf.cgm.errorNYI("opencl");
2626 else if (cgf.sanOpts.has(SanitizerKind::ShiftExponent) &&
2627 mlir::isa<cir::IntType>(ops.lhs.getType()))
2628 cgf.cgm.errorNYI("sanitizers");
2629
2630 // Note that we don't need to distinguish unsigned treatment at this
2631 // point since it will be handled later by LLVM lowering.
2632 return builder.createShiftRight(cgf.getLoc(ops.loc), ops.lhs, ops.rhs);
2633}
2634
2635mlir::Value ScalarExprEmitter::emitAnd(const BinOpInfo &ops) {
2636 return cir::AndOp::create(builder, cgf.getLoc(ops.loc), ops.lhs, ops.rhs);
2637}
2638mlir::Value ScalarExprEmitter::emitXor(const BinOpInfo &ops) {
2639 return cir::XorOp::create(builder, cgf.getLoc(ops.loc), ops.lhs, ops.rhs);
2640}
2641mlir::Value ScalarExprEmitter::emitOr(const BinOpInfo &ops) {
2642 return cir::OrOp::create(builder, cgf.getLoc(ops.loc), ops.lhs, ops.rhs);
2643}
2644
2645// Emit code for an explicit or implicit cast. Implicit
2646// casts have to handle a more broad range of conversions than explicit
2647// casts, as they handle things like function to ptr-to-function decay
2648// etc.
2649mlir::Value ScalarExprEmitter::VisitCastExpr(CastExpr *ce) {
2650 Expr *subExpr = ce->getSubExpr();
2651 QualType destTy = ce->getType();
2652 CastKind kind = ce->getCastKind();
2653 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, ce);
2654
2655 // These cases are generally not written to ignore the result of evaluating
2656 // their sub-expressions, so we clear this now.
2657 ignoreResultAssign = false;
2658
2659 switch (kind) {
2660 case clang::CK_Dependent:
2661 llvm_unreachable("dependent cast kind in CIR gen!");
2662 case clang::CK_BuiltinFnToFnPtr:
2663 llvm_unreachable("builtin functions are handled elsewhere");
2664 case CK_LValueBitCast:
2665 case CK_LValueToRValueBitCast: {
2666 LValue sourceLVal = cgf.emitLValue(subExpr);
2667 Address sourceAddr = sourceLVal.getAddress();
2668
2669 mlir::Type destElemTy = cgf.convertTypeForMem(destTy);
2670 Address destAddr = sourceAddr.withElementType(cgf.getBuilder(), destElemTy);
2671 LValue destLVal = cgf.makeAddrLValue(destAddr, destTy);
2673 return emitLoadOfLValue(destLVal, ce->getExprLoc());
2674 }
2675
2676 case CK_CPointerToObjCPointerCast:
2677 case CK_BlockPointerToObjCPointerCast:
2678 case CK_AnyPointerToBlockPointerCast:
2679 case CK_BitCast: {
2680 mlir::Value src = Visit(const_cast<Expr *>(subExpr));
2681 mlir::Type dstTy = cgf.convertType(destTy);
2682
2683 // Function and object pointers may differ in address space.
2684 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(src.getType());
2685 auto dstPtrTy = mlir::dyn_cast<cir::PointerType>(dstTy);
2686 if (srcPtrTy && dstPtrTy &&
2687 srcPtrTy.getAddrSpace() != dstPtrTy.getAddrSpace())
2688 src = cgf.performAddrSpaceCast(
2689 src,
2690 builder.getPointerTo(srcPtrTy.getPointee(), dstPtrTy.getAddrSpace()));
2691
2692 if (cgf.sanOpts.has(SanitizerKind::CFIUnrelatedCast))
2693 cgf.getCIRGenModule().errorNYI(subExpr->getSourceRange(),
2694 "sanitizer support");
2695
2696 if (cgf.cgm.getCodeGenOpts().StrictVTablePointers)
2697 cgf.getCIRGenModule().errorNYI(subExpr->getSourceRange(),
2698 "strict vtable pointers");
2699
2700 // Update heapallocsite metadata when there is an explicit pointer cast.
2702
2703 // If Src is a fixed vector and Dst is a scalable vector, and both have the
2704 // same element type, use the llvm.vector.insert intrinsic to perform the
2705 // bitcast.
2707
2708 // If Src is a scalable vector and Dst is a fixed vector, and both have the
2709 // same element type, use the llvm.vector.extract intrinsic to perform the
2710 // bitcast.
2712
2713 // Perform VLAT <-> VLST bitcast through memory.
2714 // TODO: since the llvm.experimental.vector.{insert,extract} intrinsics
2715 // require the element types of the vectors to be the same, we
2716 // need to keep this around for bitcasts between VLAT <-> VLST where
2717 // the element types of the vectors are not the same, until we figure
2718 // out a better way of doing these casts.
2720
2721 return cgf.getBuilder().createBitcast(cgf.getLoc(subExpr->getSourceRange()),
2722 src, dstTy);
2723 }
2724 case CK_AddressSpaceConversion: {
2725 Expr::EvalResult result;
2726 if (subExpr->EvaluateAsRValue(result, cgf.getContext()) &&
2727 result.Val.isNullPointer()) {
2728 // If e has side effect, it is emitted even if its final result is a
2729 // null pointer. In that case, a DCE pass should be able to
2730 // eliminate the useless instructions emitted during translating E.
2731 if (result.HasSideEffects)
2732 Visit(subExpr);
2733 return cgf.cgm.getNullPointer(
2734 mlir::cast<cir::PointerType>(convertType(destTy)), destTy,
2735 cgf.getLoc(subExpr->getExprLoc()));
2736 }
2737 return cgf.performAddrSpaceCast(Visit(subExpr), convertType(destTy));
2738 }
2739
2740 case CK_AtomicToNonAtomic:
2741 case CK_NonAtomicToAtomic:
2742 case CK_UserDefinedConversion:
2743 return Visit(const_cast<Expr *>(subExpr));
2744 case CK_NoOp:
2745 return ce->changesVolatileQualification() ? emitLoadOfLValue(ce)
2746 : Visit(subExpr);
2747 case CK_IntegralToPointer: {
2748 mlir::Type destCIRTy = cgf.convertType(destTy);
2749 mlir::Value src = Visit(const_cast<Expr *>(subExpr));
2750
2751 // Properly resize by casting to an int of the same size as the pointer.
2752 // Clang's IntegralToPointer includes 'bool' as the source, but in CIR
2753 // 'bool' is not an integral type. So check the source type to get the
2754 // correct CIR conversion.
2755 mlir::Type middleTy = cgf.cgm.getDataLayout().getIntPtrType(destCIRTy);
2756 mlir::Value middleVal = builder.createCast(
2757 subExpr->getType()->isBooleanType() ? cir::CastKind::bool_to_int
2758 : cir::CastKind::integral,
2759 src, middleTy);
2760
2761 if (cgf.cgm.getCodeGenOpts().StrictVTablePointers) {
2762 cgf.cgm.errorNYI(subExpr->getSourceRange(),
2763 "IntegralToPointer: strict vtable pointers");
2764 return {};
2765 }
2766
2767 return builder.createIntToPtr(middleVal, destCIRTy);
2768 }
2769
2770 case CK_BaseToDerived: {
2771 const CXXRecordDecl *derivedClassDecl = destTy->getPointeeCXXRecordDecl();
2772 assert(derivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
2773 Address base = cgf.emitPointerWithAlignment(subExpr);
2774 Address derived = cgf.getAddressOfDerivedClass(
2775 cgf.getLoc(ce->getSourceRange()), base, derivedClassDecl, ce->path(),
2777
2778 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
2779 // performed and the object is not of the derived type.
2781
2782 return cgf.getAsNaturalPointerTo(derived, ce->getType()->getPointeeType());
2783 }
2784 case CK_UncheckedDerivedToBase:
2785 case CK_DerivedToBase: {
2786 // The EmitPointerWithAlignment path does this fine; just discard
2787 // the alignment.
2789 ce->getType()->getPointeeType());
2790 }
2791 case CK_Dynamic: {
2792 Address v = cgf.emitPointerWithAlignment(subExpr);
2793 const auto *dce = cast<CXXDynamicCastExpr>(ce);
2794 return cgf.emitDynamicCast(v, dce);
2795 }
2796 case CK_ArrayToPointerDecay:
2797 return cgf.emitArrayToPointerDecay(subExpr).getPointer();
2798
2799 case CK_NullToPointer: {
2800 if (mustVisitNullValue(subExpr))
2801 cgf.emitIgnoredExpr(subExpr);
2802
2803 // Note that DestTy is used as the MLIR type instead of a custom
2804 // nullptr type.
2805 auto ty = mlir::cast<cir::PointerType>(cgf.convertType(destTy));
2806 return cgf.cgm.getNullPointer(ty, destTy,
2807 cgf.getLoc(subExpr->getExprLoc()));
2808 }
2809
2810 case CK_NullToMemberPointer: {
2811 if (mustVisitNullValue(subExpr))
2812 cgf.emitIgnoredExpr(subExpr);
2813
2815
2816 const MemberPointerType *mpt = ce->getType()->getAs<MemberPointerType>();
2817 mlir::Location loc = cgf.getLoc(subExpr->getExprLoc());
2818 return cgf.getBuilder().getConstant(
2819 loc, cgf.cgm.emitNullMemberAttr(destTy, mpt));
2820 }
2821
2822 case CK_ReinterpretMemberPointer: {
2823 mlir::Value src = Visit(subExpr);
2824 return builder.createBitcast(cgf.getLoc(subExpr->getExprLoc()), src,
2825 cgf.convertType(destTy));
2826 }
2827 case CK_BaseToDerivedMemberPointer:
2828 case CK_DerivedToBaseMemberPointer: {
2829 mlir::Value src = Visit(subExpr);
2830
2832
2833 QualType derivedTy =
2834 kind == CK_DerivedToBaseMemberPointer ? subExpr->getType() : destTy;
2835 const auto *mpType = derivedTy->castAs<MemberPointerType>();
2836 NestedNameSpecifier qualifier = mpType->getQualifier();
2837 assert(qualifier && "member pointer without class qualifier");
2838 const Type *qualifierType = qualifier.getAsType();
2839 assert(qualifierType && "member pointer qualifier is not a type");
2840 const CXXRecordDecl *derivedClass = qualifierType->getAsCXXRecordDecl();
2841 CharUnits offset =
2842 cgf.cgm.computeNonVirtualBaseClassOffset(derivedClass, ce->path());
2843
2844 mlir::Location loc = cgf.getLoc(subExpr->getExprLoc());
2845 mlir::Type resultTy = cgf.convertType(destTy);
2846 mlir::IntegerAttr offsetAttr = builder.getIndexAttr(offset.getQuantity());
2847
2848 if (subExpr->getType()->isMemberFunctionPointerType()) {
2849 if (kind == CK_BaseToDerivedMemberPointer)
2850 return cir::DerivedMethodOp::create(builder, loc, resultTy, src,
2851 offsetAttr);
2852 return cir::BaseMethodOp::create(builder, loc, resultTy, src, offsetAttr);
2853 }
2854
2855 if (kind == CK_BaseToDerivedMemberPointer)
2856 return cir::DerivedDataMemberOp::create(builder, loc, resultTy, src,
2857 offsetAttr);
2858 return cir::BaseDataMemberOp::create(builder, loc, resultTy, src,
2859 offsetAttr);
2860 }
2861
2862 case CK_LValueToRValue:
2863 assert(cgf.getContext().hasSameUnqualifiedType(subExpr->getType(), destTy));
2864 assert(subExpr->isGLValue() && "lvalue-to-rvalue applied to r-value!");
2865 return Visit(const_cast<Expr *>(subExpr));
2866
2867 case CK_IntegralCast: {
2868 ScalarConversionOpts opts;
2869 if (auto *ice = dyn_cast<ImplicitCastExpr>(ce)) {
2870 if (!ice->isPartOfExplicitCast())
2871 opts = ScalarConversionOpts(cgf.sanOpts);
2872 }
2873 return emitScalarConversion(Visit(subExpr), subExpr->getType(), destTy,
2874 ce->getExprLoc(), opts);
2875 }
2876
2877 case CK_FloatingComplexToReal:
2878 case CK_IntegralComplexToReal:
2879 case CK_FloatingComplexToBoolean:
2880 case CK_IntegralComplexToBoolean: {
2881 mlir::Value value = cgf.emitComplexExpr(subExpr);
2882 return emitComplexToScalarConversion(cgf.getLoc(ce->getExprLoc()), value,
2883 kind, destTy);
2884 }
2885
2886 case CK_FloatingRealToComplex:
2887 case CK_FloatingComplexCast:
2888 case CK_IntegralRealToComplex:
2889 case CK_IntegralComplexCast:
2890 case CK_IntegralComplexToFloatingComplex:
2891 case CK_FloatingComplexToIntegralComplex:
2892 llvm_unreachable("scalar cast to non-scalar value");
2893
2894 case CK_PointerToIntegral: {
2895 assert(!destTy->isBooleanType() && "bool should use PointerToBool");
2896 if (cgf.cgm.getCodeGenOpts().StrictVTablePointers)
2897 cgf.getCIRGenModule().errorNYI(subExpr->getSourceRange(),
2898 "strict vtable pointers");
2899 return builder.createPtrToInt(Visit(subExpr), cgf.convertType(destTy));
2900 }
2901 case CK_ToVoid:
2902 cgf.emitIgnoredExpr(subExpr);
2903 return {};
2904
2905 case CK_FixedPointCast:
2906 return emitScalarConversion(Visit(subExpr), subExpr->getType(), destTy,
2907 ce->getExprLoc());
2908
2909 case CK_FixedPointToBoolean:
2910 assert(subExpr->getType()->isFixedPointType() &&
2911 "Expected src type to be fixed point type");
2912 assert(destTy->isBooleanType() && "Expected dest type to be boolean type");
2913 return emitScalarConversion(Visit(subExpr), subExpr->getType(), destTy,
2914 ce->getExprLoc());
2915
2916 case CK_FixedPointToIntegral:
2917 assert(subExpr->getType()->isFixedPointType() &&
2918 "Expected src type to be fixed point type");
2919 assert(destTy->isIntegerType() && "Expected dest type to be an integer");
2920 return emitScalarConversion(Visit(subExpr), subExpr->getType(), destTy,
2921 ce->getExprLoc());
2922
2923 case CK_IntegralToFixedPoint:
2924 assert(subExpr->getType()->isIntegerType() &&
2925 "Expected src type to be an integer");
2926 assert(destTy->isFixedPointType() &&
2927 "Expected dest type to be fixed point type");
2928 return emitScalarConversion(Visit(subExpr), subExpr->getType(), destTy,
2929 ce->getExprLoc());
2930
2931 case CK_IntegralToFloating:
2932 case CK_FloatingToIntegral:
2933 case CK_FloatingCast:
2934 case CK_FixedPointToFloating:
2935 case CK_FloatingToFixedPoint: {
2936 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, ce);
2937 return emitScalarConversion(Visit(subExpr), subExpr->getType(), destTy,
2938 ce->getExprLoc());
2939 }
2940
2941 case CK_IntegralToBoolean:
2942 return emitIntToBoolConversion(Visit(subExpr),
2943 cgf.getLoc(ce->getSourceRange()));
2944
2945 case CK_PointerToBoolean:
2946 return emitPointerToBoolConversion(Visit(subExpr), subExpr->getType());
2947 case CK_FloatingToBoolean:
2948 return emitFloatToBoolConversion(Visit(subExpr),
2949 cgf.getLoc(subExpr->getExprLoc()));
2950 case CK_MemberPointerToBoolean: {
2951 mlir::Value memPtr = Visit(subExpr);
2952 return builder.createCast(cgf.getLoc(ce->getSourceRange()),
2953 cir::CastKind::member_ptr_to_bool, memPtr,
2954 cgf.convertType(destTy));
2955 }
2956
2957 case CK_HLSLAggregateSplatCast:
2958 case CK_VectorSplat: {
2959 // Splat the element across to all elements
2960 mlir::Type destCIRTy = cgf.convertType(destTy);
2961 return cir::VecSplatOp::create(builder,
2962 cgf.getLoc(subExpr->getSourceRange()),
2963 destCIRTy, Visit(subExpr));
2964 }
2965 case CK_FunctionToPointerDecay:
2966 return cgf.emitLValue(subExpr).getPointer();
2967
2968 case CK_HLSLVectorTruncation: {
2969 assert((destTy->isVectorType() || destTy->isBuiltinType()) &&
2970 "Destination type must be a vector or builtin type.");
2971 mlir::Value vec = Visit(subExpr);
2972 mlir::Location loc = cgf.getLoc(subExpr->getSourceRange());
2973 if (auto *vecTy = destTy->getAs<VectorType>()) {
2974 unsigned numElts = vecTy->getNumElements();
2975 llvm::SmallVector<int64_t, 4> mask(numElts);
2976 std::iota(mask.begin(), mask.end(), 0);
2977 return builder.createVecShuffle(loc, vec, mask);
2978 }
2979 return builder.createExtractElement(loc, vec, /*idx=*/0);
2980 }
2981 case CK_HLSLMatrixTruncation: {
2982 assert((destTy->isMatrixType() || destTy->isBuiltinType()) &&
2983 "Destination type must be a matrix or builtin type.");
2984 mlir::Value matrix = Visit(subExpr);
2985 mlir::Location loc = cgf.getLoc(subExpr->getSourceRange());
2986 if (const auto *matTy = destTy->getAs<ConstantMatrixType>()) {
2987 llvm::SmallVector<int64_t> mask(matTy->getNumElementsFlattened());
2988 unsigned numCols = matTy->getNumColumns();
2989 unsigned numRows = matTy->getNumRows();
2990
2991 auto *srcMatTy = subExpr->getType()->getAs<ConstantMatrixType>();
2992 assert(srcMatTy && "Source type must be a matrix type.");
2993 assert(numRows <= srcMatTy->getNumRows());
2994 assert(numCols <= srcMatTy->getNumColumns());
2995
2996 for (unsigned row = 0; row < numRows; row++)
2997 for (unsigned column = 0; column < numCols; column++)
2998 mask[matTy->getColumnMajorFlattenedIndex(row, column)] =
2999 srcMatTy->getColumnMajorFlattenedIndex(row, column);
3000
3001 auto elementTy =
3002 mlir::cast<cir::MatrixType>(matrix.getType()).getElementType();
3003 auto resultTy = cir::MatrixType::get(builder.getContext(), elementTy,
3004 numRows, numCols);
3005 return builder.createVecShuffle(loc, matrix, resultTy, mask);
3006 }
3007
3008 cgf.getCIRGenModule().errorNYI(subExpr->getSourceRange(),
3009 "ScalarExprEmitter::VisitCastExpr: HLSL "
3010 "Matrix truncation with non-matrix dest");
3011 return {};
3012 }
3013 default:
3014 cgf.getCIRGenModule().errorNYI(subExpr->getSourceRange(),
3015 "CastExpr: ", ce->getCastKindName());
3016 }
3017 return {};
3018}
3019
3020mlir::Value ScalarExprEmitter::VisitCallExpr(const CallExpr *e) {
3022 return emitLoadOfLValue(e);
3023
3024 auto v = cgf.emitCallExpr(e).getValue();
3026 return v;
3027}
3028
3029mlir::Value ScalarExprEmitter::VisitMemberExpr(MemberExpr *e) {
3030 if (CIRGenFunction::ConstantEmission constant = cgf.tryEmitAsConstant(e)) {
3031 cgf.emitIgnoredExpr(e->getBase());
3032 return cgf.emitScalarConstant(constant, e);
3033 } else {
3034 Expr::EvalResult result;
3035 if (e->EvaluateAsInt(result, cgf.getContext(), Expr::SE_AllowSideEffects)) {
3036 llvm::APSInt value = result.Val.getInt();
3037 cgf.emitIgnoredExpr(e->getBase());
3038 mlir::Location loc = cgf.getLoc(e->getExprLoc());
3039 // The constant is folded from an APSInt with the source-type's bit width
3040 // (1 for bool), but the AST's expression type is what later consumers of
3041 // this value see. For a bool member we have to emit a !cir.bool constant
3042 // -- otherwise downstream ops (cir.call into a bool parameter, cir.if /
3043 // cir.ternary on the value, ...) would all reject the !cir.int<u, 1> the
3044 // raw APSInt would produce.
3045 if (e->getType()->isBooleanType())
3046 return builder.getBool(value.getBoolValue(), loc);
3047 return builder.getConstInt(loc, value);
3048 }
3049 }
3050
3051 return emitLoadOfLValue(e);
3052}
3053
3054mlir::Value
3055ScalarExprEmitter::emitVectorInitWithSubvectors(mlir::Location loc,
3056 cir::VectorType vectorType,
3057 ArrayRef<mlir::Value> inits) {
3058 const unsigned resElts = vectorType.getFixedSize();
3059 mlir::Value result =
3060 builder.getConstant(loc, cir::PoisonAttr::get(vectorType));
3061 unsigned curIdx = 0;
3062 for (mlir::Value init : inits) {
3063 auto initType = mlir::dyn_cast<cir::VectorType>(init.getType());
3064 if (!initType) {
3065 result = builder.createInsertElement(loc, result, init, curIdx++);
3066 continue;
3067 }
3068
3069 const unsigned initElts = initType.getFixedSize();
3070 assert(curIdx + initElts <= resElts &&
3071 "Sema should reject excess elements");
3072 SmallVector<int64_t, 16> mask(resElts, -1);
3073 std::iota(mask.begin(), mask.begin() + initElts, 0);
3074 mlir::Value ext = builder.createVecShuffle(loc, init, mask);
3075
3076 // Poison stays on the RHS of the first shuffle, matching classic codegen.
3077 const unsigned offset = curIdx == 0 ? 0 : resElts;
3078 std::iota(mask.begin(), mask.begin() + curIdx, 0);
3079 std::iota(mask.begin() + curIdx, mask.begin() + curIdx + initElts, offset);
3080 if (curIdx == 0)
3081 std::swap(result, ext);
3082 result = builder.createVecShuffle(loc, result, ext, mask);
3083 curIdx += initElts;
3084 }
3085
3086 if (curIdx < resElts) {
3087 const mlir::Value zeroValue =
3088 builder.getNullValue(vectorType.getElementType(), loc);
3089 for (; curIdx < resElts; ++curIdx)
3090 result = builder.createInsertElement(loc, result, zeroValue, curIdx);
3091 }
3092 return result;
3093}
3094
3095mlir::Value ScalarExprEmitter::VisitInitListExpr(InitListExpr *e) {
3096 const unsigned numInitElements = e->getNumInits();
3097
3098 [[maybe_unused]] const bool ignore = std::exchange(ignoreResultAssign, false);
3099 assert((ignore == false ||
3100 (numInitElements == 0 && e->getType()->isVoidType())) &&
3101 "init list ignored");
3102
3103 if (e->hadArrayRangeDesignator()) {
3104 cgf.cgm.errorNYI(e->getSourceRange(), "ArrayRangeDesignator");
3105 return {};
3106 }
3107
3108 if (e->getType()->isVectorType()) {
3109 const auto vectorType =
3110 mlir::cast<cir::VectorType>(cgf.convertType(e->getType()));
3111
3112 SmallVector<mlir::Value, 16> elements;
3113 bool hasVectorInit = false;
3114 for (Expr *init : e->inits()) {
3115 elements.push_back(Visit(init));
3116 hasVectorInit |= mlir::isa<cir::VectorType>(elements.back().getType());
3117 }
3118
3119 if (hasVectorInit)
3120 return emitVectorInitWithSubvectors(cgf.getLoc(e->getSourceRange()),
3121 vectorType, elements);
3122
3123 // Zero-initialize any remaining values.
3124 const uint64_t vectorSize = vectorType.getFixedSize();
3125 if (numInitElements < vectorSize) {
3126 const mlir::Value zeroValue = cgf.getBuilder().getNullValue(
3127 vectorType.getElementType(), cgf.getLoc(e->getSourceRange()));
3128 std::fill_n(std::back_inserter(elements), vectorSize - numInitElements,
3129 zeroValue);
3130 }
3131
3132 return cir::VecCreateOp::create(cgf.getBuilder(),
3133 cgf.getLoc(e->getSourceRange()), vectorType,
3134 elements);
3135 }
3136
3138
3139 if (e->getType()->isVoidType())
3140 return {};
3141
3142 // C++11 value-initialization for the scalar.
3143 if (numInitElements == 0)
3144 return emitNullValue(e->getType(), cgf.getLoc(e->getExprLoc()));
3145
3146 return Visit(e->getInit(0));
3147}
3148
3149mlir::Value CIRGenFunction::emitScalarConversion(mlir::Value src,
3150 QualType srcTy, QualType dstTy,
3151 SourceLocation loc) {
3154 "Invalid scalar expression to emit");
3155 return ScalarExprEmitter(*this, builder)
3156 .emitScalarConversion(src, srcTy, dstTy, loc);
3157}
3158
3160 QualType srcTy,
3161 QualType dstTy,
3162 SourceLocation loc) {
3163 assert(srcTy->isAnyComplexType() && hasScalarEvaluationKind(dstTy) &&
3164 "Invalid complex -> scalar conversion");
3165
3166 QualType complexElemTy = srcTy->castAs<ComplexType>()->getElementType();
3167 if (dstTy->isBooleanType()) {
3168 auto kind = complexElemTy->isFloatingType()
3169 ? cir::CastKind::float_complex_to_bool
3170 : cir::CastKind::int_complex_to_bool;
3171 return builder.createCast(getLoc(loc), kind, src, convertType(dstTy));
3172 }
3173
3174 auto kind = complexElemTy->isFloatingType()
3175 ? cir::CastKind::float_complex_to_real
3176 : cir::CastKind::int_complex_to_real;
3177 mlir::Value real =
3178 builder.createCast(getLoc(loc), kind, src, convertType(complexElemTy));
3179 return emitScalarConversion(real, complexElemTy, dstTy, loc);
3180}
3181
3182mlir::Value ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *e) {
3183 // Perform vector logical not on comparison with zero vector.
3184 if (e->getType()->isVectorType() &&
3185 e->getType()->castAs<VectorType>()->getVectorKind() ==
3187 mlir::Value oper = Visit(e->getSubExpr());
3188 mlir::Location loc = cgf.getLoc(e->getExprLoc());
3189 auto operVecTy = mlir::cast<cir::VectorType>(oper.getType());
3190 mlir::Value zeroVec = builder.getNullValue(operVecTy, loc);
3191 auto resultTy = mlir::cast<cir::VectorType>(cgf.convertType(e->getType()));
3192 if (cir::isFPOrVectorOfFPType(operVecTy.getElementType())) {
3193 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, e);
3194 return builder.createVecFCompare(loc, resultTy, cir::FCmpOpKind::oeq,
3195 oper, zeroVec);
3196 }
3197
3198 return builder.createVecCompare(loc, resultTy, cir::CmpOpKind::eq, oper,
3199 zeroVec);
3200 }
3201
3202 // Compare operand to zero.
3203 mlir::Value boolVal = cgf.evaluateExprAsBool(e->getSubExpr());
3204
3205 // Invert value.
3206 boolVal = builder.createNot(boolVal);
3207
3208 // ZExt result to the expr type.
3209 return maybePromoteBoolResult(boolVal, cgf.convertType(e->getType()));
3210}
3211
3212mlir::Value ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *e) {
3213 // Try folding the offsetof to a constant.
3214 Expr::EvalResult evalResult;
3215 if (e->EvaluateAsInt(evalResult, cgf.getContext())) {
3216 mlir::Type type = cgf.convertType(e->getType());
3217 llvm::APSInt value = evalResult.Val.getInt();
3218 return builder.getConstAPInt(cgf.getLoc(e->getExprLoc()), type, value);
3219 }
3220
3222 e->getSourceRange(),
3223 "ScalarExprEmitter::VisitOffsetOfExpr Can't eval expr as int");
3224 return {};
3225}
3226
3227mlir::Value ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *e) {
3228 QualType promotionTy = getPromotionType(e->getSubExpr()->getType());
3229 mlir::Value result = VisitRealImag(e, promotionTy);
3230 if (result && !promotionTy.isNull())
3231 result = emitUnPromotedValue(result, e->getType());
3232 return result;
3233}
3234
3235mlir::Value ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *e) {
3236 QualType promotionTy = getPromotionType(e->getSubExpr()->getType());
3237 mlir::Value result = VisitRealImag(e, promotionTy);
3238 if (result && !promotionTy.isNull())
3239 result = emitUnPromotedValue(result, e->getType());
3240 return result;
3241}
3242
3243mlir::Value ScalarExprEmitter::VisitRealImag(const UnaryOperator *e,
3244 QualType promotionTy) {
3245 assert(
3246 (e->getOpcode() == clang::UO_Real || e->getOpcode() == clang::UO_Imag) &&
3247 "Invalid UnaryOp kind for ComplexType Real or Imag");
3248
3249 Expr *op = e->getSubExpr();
3250 mlir::Location loc = cgf.getLoc(e->getExprLoc());
3251 if (op->getType()->isAnyComplexType()) {
3252 // If it's an l-value, load through the appropriate subobject l-value.
3253 // Note that we have to ask `e` because `op` might be an l-value that
3254 // this won't work for, e.g. an Obj-C property
3255 mlir::Value complex = cgf.emitComplexExpr(op);
3256 if (e->isGLValue() && !promotionTy.isNull()) {
3257 promotionTy = promotionTy->isAnyComplexType()
3258 ? promotionTy
3259 : cgf.getContext().getComplexType(promotionTy);
3260 complex = cgf.emitPromotedValue(complex, promotionTy);
3261 }
3262
3263 return e->getOpcode() == clang::UO_Real
3264 ? builder.createComplexReal(loc, complex)
3265 : builder.createComplexImag(loc, complex);
3266 }
3267
3268 if (e->getOpcode() == UO_Real) {
3269 mlir::Value operand = promotionTy.isNull()
3270 ? Visit(op)
3271 : cgf.emitPromotedScalarExpr(op, promotionTy);
3272 return builder.createComplexReal(loc, operand);
3273 }
3274
3275 // __imag on a scalar returns zero. Emit the subexpr to ensure side
3276 // effects are evaluated, but not the actual value.
3277 mlir::Value operand;
3278 if (op->isGLValue()) {
3279 operand = cgf.emitLValue(op).getPointer();
3280 operand = cir::LoadOp::create(builder, loc, operand);
3281 } else if (!promotionTy.isNull()) {
3282 operand = cgf.emitPromotedScalarExpr(op, promotionTy);
3283 } else {
3284 operand = cgf.emitScalarExpr(op);
3285 }
3286 return builder.createComplexImag(loc, operand);
3287}
3288
3289/// Return the size or alignment of the type of argument of the sizeof
3290/// expression as an integer.
3291mlir::Value ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
3292 const UnaryExprOrTypeTraitExpr *e) {
3293 const QualType typeToSize = e->getTypeOfArgument();
3294 const mlir::Location loc = cgf.getLoc(e->getSourceRange());
3295 if (auto kind = e->getKind();
3296 kind == UETT_SizeOf || kind == UETT_DataSizeOf || kind == UETT_CountOf) {
3297 if (const VariableArrayType *vat =
3298 cgf.getContext().getAsVariableArrayType(typeToSize)) {
3299 // For _Countof, we only want to evaluate if the extent is actually
3300 // variable as opposed to a multi-dimensional array whose extent is
3301 // constant but whose element type is variable.
3302 bool evaluateExtent = true;
3303 if (kind == UETT_CountOf && vat->getElementType()->isArrayType()) {
3304 evaluateExtent =
3305 !vat->getSizeExpr()->isIntegerConstantExpr(cgf.getContext());
3306 }
3307
3308 if (evaluateExtent) {
3309 if (e->isArgumentType()) {
3310 // sizeof(type) - make sure to emit the VLA size.
3311 cgf.emitVariablyModifiedType(typeToSize);
3312 } else {
3313 // C99 6.5.3.4p2: If the argument is an expression of type
3314 // VLA, it is evaluated.
3316 }
3317
3318 // For _Countof, we just want to return the size of a single dimension.
3319 if (kind == UETT_CountOf)
3320 return cgf.getVLAElements1D(vat).numElts;
3321
3322 // For sizeof and __datasizeof, we need to scale the number of elements
3323 // by the size of the array element type.
3324 CIRGenFunction::VlaSizePair vlaSize = cgf.getVLASize(vat);
3325 mlir::Value numElts = vlaSize.numElts;
3326
3327 // Scale the number of non-VLA elements by the non-VLA element size.
3328 CharUnits eltSize = cgf.getContext().getTypeSizeInChars(vlaSize.type);
3329 if (!eltSize.isOne()) {
3330 mlir::Location loc = cgf.getLoc(e->getSourceRange());
3331 mlir::Value eltSizeValue =
3332 builder.getConstAPInt(numElts.getLoc(), numElts.getType(),
3333 cgf.cgm.getSize(eltSize).getValue());
3334 return builder.createMul(loc, eltSizeValue, numElts,
3335 cir::OverflowFlags::NoUnsignedWrap);
3336 }
3337
3338 return numElts;
3339 }
3340 }
3341 } else if (e->getKind() == UETT_OpenMPRequiredSimdAlign) {
3343 cgf.getContext()
3346 .getQuantity();
3347 return builder.getConstantInt(loc, cgf.cgm.sizeTy, alignment);
3348 } else if (e->getKind() == UETT_VectorElements) {
3349 auto vecTy = cast<cir::VectorType>(convertType(e->getTypeOfArgument()));
3350 if (vecTy.isScalable()) {
3352 e->getSourceRange(),
3353 "VisitUnaryExprOrTypeTraitExpr: sizeOf scalable vector");
3354 return builder.getConstant(
3355 loc, cir::IntAttr::get(cgf.cgm.sizeTy,
3357 }
3358
3359 return builder.getConstant(
3360 loc, cir::IntAttr::get(cgf.cgm.sizeTy, vecTy.getFixedSize()));
3361 }
3362
3363 // The result type is size_t (target-dependent width); use it so the IntAttr
3364 // width matches the APInt from EvaluateKnownConstInt.
3365 return builder.getConstant(
3366 loc, cir::IntAttr::get(cgf.cgm.sizeTy,
3368}
3369
3370mlir::Value ScalarExprEmitter::VisitAbstractConditionalOperator(
3371 const AbstractConditionalOperator *e) {
3372 CIRGenBuilderTy &builder = cgf.getBuilder();
3373 mlir::Location loc = cgf.getLoc(e->getSourceRange());
3374 ignoreResultAssign = false;
3375
3376 // Bind the common expression if necessary.
3377 CIRGenFunction::OpaqueValueMapping binding(cgf, e);
3378
3379 Expr *condExpr = e->getCond();
3380 Expr *lhsExpr = e->getTrueExpr();
3381 Expr *rhsExpr = e->getFalseExpr();
3382
3383 // If the condition constant folds and can be elided, try to avoid emitting
3384 // the condition and the dead arm.
3385 bool condExprBool;
3386 if (cgf.constantFoldsToBool(condExpr, condExprBool)) {
3387 Expr *live = lhsExpr, *dead = rhsExpr;
3388 if (!condExprBool)
3389 std::swap(live, dead);
3390
3391 // If the dead side doesn't have labels we need, just emit the Live part.
3392 if (!cgf.containsLabel(dead)) {
3393 if (condExprBool)
3395 mlir::Value result = Visit(live);
3396
3397 // If the live part is a throw expression, it acts like it has a void
3398 // type, so evaluating it returns a null Value. However, a conditional
3399 // with non-void type must return a non-null Value.
3400 if (!result && !e->getType()->isVoidType()) {
3401 result = builder.getConstant(
3402 loc, cir::PoisonAttr::get(builder.getContext(),
3403 cgf.convertType(e->getType())));
3404 }
3405
3406 return result;
3407 }
3408 }
3409
3410 QualType condType = condExpr->getType();
3411
3412 // OpenCL: If the condition is a vector, we can treat this condition like
3413 // the select function.
3414 if (cgf.getLangOpts().OpenCL &&
3415 (condType->isVectorType() || condType->isExtVectorType())) {
3417
3418 mlir::Value condValue = cgf.emitScalarExpr(condExpr);
3419 mlir::Value lhsValue = Visit(lhsExpr);
3420 mlir::Value rhsValue = Visit(rhsExpr);
3421
3422 // Test the MSB with a signed compare, as classic codegen does.
3423 mlir::Type vecTy =
3424 convertType(cgf.getContext().getCorrespondingSignedType(condType));
3425 condValue = builder.createBitcast(condValue, vecTy);
3426 mlir::Value zeroVec = builder.getNullValue(vecTy, loc);
3427 auto testMSB = cir::VecCmpOp::create(
3428 builder, loc, vecTy, cir::CmpOpKind::lt, condValue, zeroVec);
3429 mlir::Value tmp = builder.createIntCast(testMSB, vecTy);
3430 mlir::Value tmp2 = builder.createNot(tmp);
3431
3432 // Bitcast float or differently signed operands to the condition type.
3433 mlir::Value rhsTmp = rhsValue;
3434 mlir::Value lhsTmp = lhsValue;
3435 bool wasCast = false;
3436 if (rhsValue.getType() != vecTy) {
3437 rhsTmp = builder.createBitcast(rhsValue, tmp2.getType());
3438 lhsTmp = builder.createBitcast(lhsValue, tmp.getType());
3439 wasCast = true;
3440 }
3441
3442 mlir::Value tmp3 = builder.createAnd(loc, rhsTmp, tmp2);
3443 mlir::Value tmp4 = builder.createAnd(loc, lhsTmp, tmp);
3444 mlir::Value tmp5 = builder.createOr(loc, tmp3, tmp4);
3445 if (wasCast)
3446 tmp5 = builder.createBitcast(tmp5, rhsValue.getType());
3447 return tmp5;
3448 }
3449
3450 if (condType->isVectorType() || condType->isSveVLSBuiltinType()) {
3451 if (!condType->isVectorType()) {
3453 cgf.cgm.errorNYI(loc, "TernaryOp for SVE vector");
3454 return {};
3455 }
3456
3457 mlir::Value condValue = Visit(condExpr);
3458 mlir::Value lhsValue = Visit(lhsExpr);
3459 mlir::Value rhsValue = Visit(rhsExpr);
3460 return cir::VecTernaryOp::create(builder, loc, condValue, lhsValue,
3461 rhsValue);
3462 }
3463
3464 // If this is a really simple expression (like x ? 4 : 5), emit this as a
3465 // select instead of as control flow. We can only do this if it is cheap
3466 // and safe to evaluate the LHS and RHS unconditionally.
3468 cgf.getContext()) &&
3470 cgf.getContext())) {
3471 mlir::Value condV = cgf.evaluateExprAsBool(condExpr);
3473
3474 mlir::Value lhs = Visit(lhsExpr);
3475 mlir::Value rhs = Visit(rhsExpr);
3476 if (!lhs) {
3477 // If the conditional has void type, make sure we return a null Value.
3478 assert(!rhs && "lhs and rhs types must match");
3479 return {};
3480 }
3481
3482 return builder.createSelect(loc, condV, lhs, rhs);
3483 }
3484
3485 mlir::Value condV = cgf.emitOpOnBoolExpr(loc, condExpr);
3486 CIRGenFunction::ConditionalEvaluation eval(cgf, loc);
3487
3488 auto emitBranch = [&](mlir::OpBuilder &b, mlir::Location loc, Expr *expr) {
3489 CIRGenFunction::LexicalScope lexScope{cgf, loc, b.getInsertionBlock()};
3491
3492 mlir::Value branch;
3493 {
3494 // Emit any cleanups that were needed on this branch so we can spill
3495 // and reload the return value.
3496 CIRGenFunction::RunCleanupsScope branchCleanups(cgf);
3498 eval.beginEvaluation();
3499 branch = Visit(expr);
3500 eval.endEvaluation();
3501 branchCleanups.forceCleanup({&branch});
3502 }
3503
3504 if (branch)
3505 cir::YieldOp::create(b, loc, branch);
3506 };
3507
3508 cir::TernaryOp ternary = cir::TernaryOp::create(
3509 builder, loc, condV,
3510 /*trueBuilder=*/
3511 [&](mlir::OpBuilder &b, mlir::Location loc) {
3512 emitBranch(b, loc, lhsExpr);
3513 },
3514 /*falseBuilder=*/
3515 [&](mlir::OpBuilder &b, mlir::Location loc) {
3516 emitBranch(b, loc, rhsExpr);
3517 });
3518
3519 // Only a void arm can be left unterminated (a noreturn arm already ends
3520 // in cir.unreachable); close it with an empty cir.yield.
3521 for (mlir::Region *region :
3522 {&ternary.getTrueRegion(), &ternary.getFalseRegion()}) {
3523 mlir::Block &lastBlock = region->back();
3524 if (lastBlock.empty() ||
3525 !lastBlock.back().hasTrait<mlir::OpTrait::IsTerminator>()) {
3526 mlir::OpBuilder::InsertionGuard guard(builder);
3527 builder.setInsertionPointToEnd(&lastBlock);
3528 cir::YieldOp::create(builder, loc);
3529 }
3530 }
3531
3532 return ternary.getResult();
3533}
3534
3536 LValue lv) {
3537 return ScalarExprEmitter(*this, builder).emitScalarPrePostIncDec(e, lv);
3538}
static Value * createCastsForTypeOfSameSize(CGBuilderTy &Builder, const llvm::DataLayout &DL, Value *Src, llvm::Type *DstTy, StringRef Name="")
#define HANDLE_BINOP(OP)
static bool mustVisitNullValue(const Expr *e)
#define COMPOUND_OP(Op)
#define HANDLEBINOP(OP)
static bool isWidenedIntegerOp(const ASTContext &astContext, const Expr *e)
Check if e is a widened promoted integer.
static mlir::Value emitPointerArithmetic(CIRGenFunction &cgf, const BinOpInfo &op, bool isSubtraction)
Emit pointer + index arithmetic.
static mlir::Value tryEmitFMulAdd(mlir::Location loc, const BinOpInfo &op, CIRGenBuilderTy &builder, bool isSub=false)
static mlir::Value buildFMulAdd(mlir::Location addLoc, cir::FMulOp mulOp, mlir::Value addend, CIRGenBuilderTy &builder, bool negMul, bool negAdd)
static bool canElideOverflowCheck(const ASTContext &astContext, const BinOpInfo &op)
Check if we can skip the overflow check for Op.
static std::optional< QualType > getUnwidenedIntegerType(const ASTContext &astContext, const Expr *e)
If e is a widened promoted integer, get its base (unpromoted) type.
#define VISITCOMP(CODE)
static bool isIntegerVectorBinOp(mlir::Type ty)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
mlir::Value createNSWSub(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
cir::ConstantOp getBool(bool state, mlir::Location loc)
mlir::Value createDiv(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
mlir::Value createAdd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs, OverflowFlags flags=OverflowFlags::None)
mlir::Value getConstAPInt(mlir::Location loc, mlir::Type typ, const llvm::APInt &val)
mlir::Value createSub(mlir::Location loc, mlir::Value lhs, mlir::Value rhs, OverflowFlags flags=OverflowFlags::None)
mlir::Value createNSWAdd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
cir::ConstantOp getNullValue(mlir::Type ty, mlir::Location loc)
cir::ConstantOp getConstant(mlir::Location loc, mlir::TypedAttr attr)
mlir::Value createOr(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
mlir::Value createCast(mlir::Location loc, cir::CastKind kind, mlir::Value src, mlir::Type newTy)
mlir::Value createIntToPtr(mlir::Value src, mlir::Type newTy)
mlir::Value createPtrToInt(mlir::Value src, mlir::Type newTy)
mlir::Value createFDiv(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
cir::PointerType getPointerTo(mlir::Type ty)
cir::VecFCmpOp createVecFCompare(mlir::Location loc, cir::FCmpOpKind kind, mlir::Value lhs, mlir::Value rhs, bool signaling=false)
Compares lhs and rhs element-wise.
mlir::Value createFNeg(mlir::Location loc, mlir::Value operand)
mlir::Value createMul(mlir::Location loc, mlir::Value lhs, mlir::Value rhs, OverflowFlags flags=OverflowFlags::None)
mlir::Value createFAdd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
mlir::Value createComplexImag(mlir::Location loc, mlir::Value operand)
mlir::Value createNSWMul(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
cir::GetGlobalOp createGetGlobal(mlir::Location loc, cir::GlobalOp global, bool threadLocal=false)
mlir::Value createShiftLeft(mlir::Location loc, mlir::Value lhs, unsigned bits)
mlir::Value createAnd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
mlir::Value createExtractElement(mlir::Location loc, mlir::Value vec, uint64_t idx)
cir::VecCmpOp createVecCompare(mlir::Location loc, cir::CmpOpKind kind, mlir::Value lhs, mlir::Value rhs)
Compares lhs and rhs element-wise.
mlir::Value createIntCast(mlir::Value src, mlir::Type newTy)
mlir::Value createInsertElement(mlir::Location loc, mlir::Value vec, mlir::Value newElt, uint64_t idx)
cir::FastMathFlagsAttr getFastMathFlagsAttr()
Returns a null attribute when no fast-math flags are set.
mlir::Value createBitcast(mlir::Value src, mlir::Type newTy)
mlir::Value createFMul(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
mlir::Value createNot(mlir::Location loc, mlir::Value value)
mlir::Value createSelect(mlir::Location loc, mlir::Value condition, mlir::Value trueValue, mlir::Value falseValue)
cir::ConstantOp getConstantInt(mlir::Location loc, mlir::Type ty, int64_t value)
mlir::Value createFRem(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
mlir::Value createShiftRight(mlir::Location loc, mlir::Value lhs, unsigned bits)
mlir::Value createFSub(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
mlir::Value createComplexReal(mlir::Location loc, mlir::Value operand)
mlir::Type getIntPtrType(mlir::Type ty) const
llvm::APInt getValue() const
APSInt & getInt()
Definition APValue.h:577
bool isNullPointer() const
Definition APValue.cpp:1173
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
CanQualType FloatTy
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
QualType getCorrespondingSignedType(QualType T) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4600
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4606
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4612
LabelDecl * getLabel() const
Definition Expr.h:4642
uint64_t getValue() const
Definition ExprCXX.h:3059
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:6838
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
Expr * getLHS() const
Definition Expr.h:4157
SourceLocation getExprLoc() const
Definition Expr.h:4148
bool isShiftOp() const
Definition Expr.h:4196
Expr * getRHS() const
Definition Expr.h:4159
bool isShiftAssignOp() const
Definition Expr.h:4265
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4320
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, const Expr *LHS, const Expr *RHS)
Return true if a binary operator using the specified opcode and operands would match the 'p = (i8*)nu...
Definition Expr.cpp:2242
Opcode getOpcode() const
Definition Expr.h:4152
BinaryOperatorKind Opcode
Definition Expr.h:4112
mlir::Value getPointer() const
Definition Address.h:98
Address withElementType(CIRGenBuilderTy &builder, mlir::Type ElemTy) const
Return address with different element type, a bitcast pointer, and the same alignment.
std::pair< mlir::Value, mlir::Value > splatMatrixOpOperandsIfNecessary(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
cir::VecShuffleOp createVecShuffle(mlir::Location loc, mlir::Value vec1, mlir::Value vec2, llvm::ArrayRef< mlir::Attribute > maskAttrs)
mlir::Value createNeg(mlir::Location loc, mlir::Value value, bool nsw=false)
cir::MatrixMultiplyOp createMatrixMultiply(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
Multiply an MxK matrix by a KxN matrix, producing an MxN matrix.
cir::ConstantOp getConstInt(mlir::Location loc, llvm::APSInt intVal)
void forceCleanup(ArrayRef< mlir::Value * > valuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
static bool hasScalarEvaluationKind(clang::QualType type)
mlir::Value emitComplexToScalarConversion(mlir::Value src, QualType srcTy, QualType dstTy, SourceLocation loc)
Emit a conversion from the specified complex type to the specified destination type,...
mlir::Type convertType(clang::QualType t)
mlir::Value emitPromotedValue(mlir::Value result, QualType promotionType)
Address emitPointerWithAlignment(const clang::Expr *expr, LValueBaseInfo *baseInfo=nullptr)
Given an expression with a pointer type, emit the value and compute our best estimate of the alignmen...
void emitVariablyModifiedType(QualType ty)
const clang::LangOptions & getLangOpts() const
VlaSizePair getVLASize(const VariableArrayType *type)
Returns an MLIR::Value+QualType pair that corresponds to the size, in non-variably-sized elements,...
LValue emitScalarCompoundAssignWithComplex(const CompoundAssignOperator *e, mlir::Value &result)
mlir::Value emitComplexExpr(const Expr *e)
Emit the computation of the specified expression of complex type, returning the result.
RValue emitCallExpr(const clang::CallExpr *e, ReturnValueSlot returnValue=ReturnValueSlot())
LValue emitLValue(const clang::Expr *e)
Emit code to compute a designator that specifies the location of the expression.
mlir::Value evaluateExprAsBool(const clang::Expr *e)
Perform the usual unary conversions on the specified expression and compare the result against zero,...
mlir::Location getLoc(clang::SourceLocation srcLoc)
Helpers to convert Clang's SourceLocation to a MLIR Location.
bool constantFoldsToBool(const clang::Expr *cond, bool &resultBool, bool allowLabels=false)
If the specified expression does not fold to a constant, or if it does but contains a label,...
mlir::Value emitOpOnBoolExpr(mlir::Location loc, const clang::Expr *cond)
TODO(cir): see EmitBranchOnBoolExpr for extra ideas).
VlaSizePair getVLAElements1D(const VariableArrayType *vla)
Return the number of elements for a single dimension for the given array type.
mlir::Value performAddrSpaceCast(mlir::Value v, mlir::Type destTy) const
mlir::Value emitScalarConversion(mlir::Value src, clang::QualType srcType, clang::QualType dstType, clang::SourceLocation loc)
Emit a conversion from the specified type to the specified destination type, both of which are CIR sc...
Address getAddressOfDerivedClass(mlir::Location loc, Address baseAddr, const CXXRecordDecl *derived, llvm::iterator_range< CastExpr::path_const_iterator > path, bool nullCheckValue)
clang::SanitizerSet sanOpts
Sanitizers enabled for this function.
mlir::Type convertTypeForMem(QualType t)
LValue emitCompoundAssignmentLValue(const clang::CompoundAssignOperator *e)
mlir::Value getAsNaturalPointerTo(Address addr, QualType pointeeType)
mlir::Value emitScalarExpr(const clang::Expr *e, bool ignoreResultAssign=false)
Emit the computation of the specified expression of scalar type.
mlir::Value emitPromotedScalarExpr(const Expr *e, QualType promotionType)
bool shouldNullCheckClassCastValue(const CastExpr *ce)
CIRGenBuilderTy & getBuilder()
mlir::Value emitScalarPrePostIncDec(const UnaryOperator *e, LValue lv)
bool containsLabel(const clang::Stmt *s, bool ignoreCaseStmts=false)
Return true if the statement contains a label in it.
ConstantEmission tryEmitAsConstant(const DeclRefExpr *refExpr)
Try to emit a reference to the given value without producing it as an l-value.
LValue makeAddrLValue(Address addr, QualType ty, AlignmentSource source=AlignmentSource::Type)
Address emitArrayToPointerDecay(const Expr *e, LValueBaseInfo *baseInfo=nullptr)
mlir::Value emitStoreThroughBitfieldLValue(RValue src, LValue dstresult)
clang::ASTContext & getContext() const
mlir::Value emitScalarConstant(const ConstantEmission &constant, Expr *e)
void emitNullabilityCheck(LValue lhs, mlir::Value rhs, clang::SourceLocation loc)
Given an assignment *lhs = rhs, emit a test that checks if rhs is nonnull, if 1LHS is marked _Nonnull...
void emitStoreThroughLValue(RValue src, LValue dst, bool isInit=false)
Store the specified rvalue into the specified lvalue, where both are guaranteed to the have the same ...
void emitIgnoredExpr(const clang::Expr *e)
Emit code to compute the specified expression, ignoring the result.
mlir::Value emitDynamicCast(Address thisAddr, const CXXDynamicCastExpr *dce)
mlir::Value getNullPointer(cir::PointerType ptrTy, QualType qt, mlir::Location loc)
Get target specific null pointer.
CharUnits computeNonVirtualBaseClassOffset(const CXXRecordDecl *derivedClass, llvm::iterator_range< CastExpr::path_const_iterator > path)
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
mlir::IntegerAttr getSize(CharUnits size)
cir::GlobalOp createGlobalString(mlir::Location loc, llvm::StringRef str, llvm::StringRef name)
Create a private constant global holding the null-terminated string str, mirroring llvm::IRBuilder::C...
const cir::CIRDataLayout & getDataLayout() const
const clang::CodeGenOptions & getCodeGenOpts() const
mlir::TypedAttr emitNullMemberAttr(QualType t, const MemberPointerType *mpt)
Returns a null attribute to represent either a null method or null data member, depending on the type...
mlir::Value getPointer() const
static RValue get(mlir::Value v)
Definition CIRGenValue.h:83
mlir::Value getValue() const
Return the value of this scalar value.
Definition CIRGenValue.h:57
bool getValue() const
Definition ExprCXX.h:745
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1137
bool getValue() const
Definition ExprCXX.h:4386
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:309
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1635
CastKind getCastKind() const
Definition Expr.h:3789
llvm::iterator_range< path_iterator > path()
Path through the class hierarchy taken by casts between base and derived classes (see implementation ...
Definition Expr.h:3832
bool changesVolatileQualification() const
Return.
Definition Expr.h:3879
static const char * getCastKindName(CastKind CK)
Definition Expr.cpp:1987
Expr * getSubExpr()
Definition Expr.h:3795
int64_t QuantityType
Definition CharUnits.h:40
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
bool isOne() const
Test whether the quantity equals one.
Definition CharUnits.h:104
unsigned getValue() const
Definition Expr.h:1674
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4953
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3362
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4369
QualType getComputationLHSType() const
Definition Expr.h:4403
QualType getComputationResultType() const
Definition Expr.h:4406
SourceLocation getExprLoc() const LLVM_READONLY
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4878
ChildElementIter< false > begin()
Definition Expr.h:5310
size_t getDataElementCount() const
Definition Expr.h:5226
This represents one expression.
Definition Expr.h:114
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isGLValue() const
Definition Expr.h:289
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:703
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3109
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
bool allowFPContractWithinStatement() const
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1620
llvm::APFloat getValue() const
Definition Expr.h:1711
const Expr * getSubExpr() const
Definition Expr.h:1107
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6554
unsigned getNumInits() const
Definition Expr.h:5410
bool hadArrayRangeDesignator() const
Definition Expr.h:5569
const Expr * getInit(unsigned Init) const
Definition Expr.h:5443
ArrayRef< Expr * > inits() const
Definition Expr.h:5441
bool isSignedOverflowDefined() const
Expr * getBase() const
Definition Expr.h:3510
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3628
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
SourceRange getSourceRange() const LLVM_READONLY
Definition ExprObjC.h:247
SourceRange getSourceRange() const
Definition ExprObjC.h:1754
SourceRange getSourceRange() const LLVM_READONLY
Definition ExprObjC.h:189
SourceRange getSourceRange() const LLVM_READONLY
Definition ExprObjC.h:414
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:1253
Expr * getSelectedExpr() const
Definition ExprCXX.h:4693
const Expr * getSubExpr() const
Definition Expr.h:2268
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8578
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getCanonicalType() const
Definition TypeBase.h:8630
bool UseExcessPrecision(const ASTContext &Ctx)
Definition Type.cpp:1775
bool isCanonical() const
Definition TypeBase.h:8635
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
bool isSatisfied() const
Whether or not the requires clause is satisfied.
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:597
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4745
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4751
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4569
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition Expr.cpp:2319
SourceLocation getLocation() const
Definition Expr.h:5139
Encodes a location in the source.
SourceLocation getBegin() const
CompoundStmt * getSubStmt()
Definition Expr.h:4681
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
const char * getStmtClassName() const
Definition Stmt.cpp:86
bool getBoolValue() const
Definition ExprCXX.h:2962
const APValue & getAPValue() const
Definition ExprCXX.h:2967
bool isStoredAsBoolean() const
Definition ExprCXX.h:2954
bool isVoidType() const
Definition TypeBase.h:9200
bool isBooleanType() const
Definition TypeBase.h:9341
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2415
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2392
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantMatrixType() const
Definition TypeBase.h:8982
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isReferenceType() const
Definition TypeBase.h:8839
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:2080
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2829
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition Type.cpp:2504
bool isExtVectorType() const
Definition TypeBase.h:8958
bool isExtVectorBoolType() const
Definition TypeBase.h:8962
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8938
bool isAnyComplexType() const
Definition TypeBase.h:8950
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9264
bool isHalfType() const
Definition TypeBase.h:9208
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9280
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2436
bool isMatrixType() const
Definition TypeBase.h:8978
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2881
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8900
bool isVectorType() const
Definition TypeBase.h:8954
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2533
bool isFloatingType() const
Definition Type.cpp:2517
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2460
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
bool isNullPtrType() const
Definition TypeBase.h:9241
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2763
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2726
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
SourceLocation getExprLoc() const
Definition Expr.h:2437
Expr * getSubExpr() const
Definition Expr.h:2354
Opcode getOpcode() const
Definition Expr.h:2349
static bool isIncrementOp(Opcode Op)
Definition Expr.h:2395
static bool isDecrementOp(Opcode Op)
Definition Expr.h:2402
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:2469
static bool isPrefix(Opcode Op)
isPrefix - Return true if this is a prefix operation, like –x.
Definition Expr.h:2388
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2367
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4064
Represents a GCC generic vector type.
Definition TypeBase.h:4398
VectorKind getVectorKind() const
Definition TypeBase.h:4418
bool isCheapEnoughToEvaluateUnconditionally(const Expr *E, const ASTContext &Ctx)
Check whether E is cheap enough and side-effect-free enough to evaluate unconditionally instead of co...
Definition ExprUtils.cpp:87
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::ArgumentAdaptingMatcherFunc< internal::HasMatcher > has
Matches AST nodes that have child AST nodes that match the provided matcher.
const AstTypeMatcher< PointerType > pointerType
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
void info(bool Verbose, unsigned Level, const char *Fmt, Ts &&...Args)
Prints an indented note to stderr when Verbose is set.
Definition Utils.h:57
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
CastKind
CastKind - The kind of operation required for a conversion.
inits_range inits()
@ Generic
not a target-specific vector type
Definition TypeBase.h:4234
U cast(CodeGen::Address addr)
Definition Address.h:327
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 __builtin_riscv_nclipu_u32 int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
#define false
Definition stdbool.h:26
static bool instrumentation()
static bool dataMemberType()
static bool objCLifetime()
static bool vecTernaryOp()
static bool addHeapAllocSiteMetadata()
static bool mayHaveIntegerOverflow()
static bool emitMatrixIndexAssumption()
static bool openMPLastprivateConditional()
static bool llvmLoweringPtrDiffConsidersPointee()
static bool scalableVectors()
static bool memberFuncPtrAuthInfo()
static bool emitLValueAlignmentAssumption()
static bool incrementProfileCounter()
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:626
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition Sanitizers.h:174