clang 24.0.0git
CIRGenBuiltin.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// This contains code to emit Builtin calls as CIR or a function call to be
10// later resolved.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CIRGenCall.h"
15#include "CIRGenFunction.h"
16#include "CIRGenModule.h"
17#include "CIRGenValue.h"
18#include "mlir/IR/BuiltinAttributes.h"
19#include "mlir/IR/Value.h"
20#include "mlir/Support/LLVM.h"
21#include "clang/AST/DeclBase.h"
22#include "clang/AST/Expr.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/Support/ErrorHandling.h"
34
35using namespace clang;
36using namespace clang::CIRGen;
37using namespace llvm;
38
39static bool shouldEmitBuiltinAsIR(unsigned builtinID,
40 const Builtin::Context &bi,
41 const CIRGenFunction &cgf) {
42 if (!cgf.cgm.getLangOpts().MathErrno &&
46 switch (builtinID) {
47 default:
48 return false;
49 case Builtin::BIlogbf:
50 case Builtin::BI__builtin_logbf:
51 case Builtin::BIlogb:
52 case Builtin::BI__builtin_logb:
53 case Builtin::BIscalbnf:
54 case Builtin::BI__builtin_scalbnf:
55 case Builtin::BIscalbn:
56 case Builtin::BI__builtin_scalbn:
57 return true;
58 }
59 }
60 return false;
61}
62
64 const CallExpr *e, mlir::Operation *calleeValue) {
65 CIRGenCallee callee = CIRGenCallee::forDirect(calleeValue, GlobalDecl(fd));
66 return cgf.emitCall(e->getCallee()->getType(), callee, e, ReturnValueSlot());
67}
68
69template <typename Op, typename... Args>
70static mlir::Value createBuiltinBitOp(CIRGenFunction &cgf, const CallExpr *e,
71 mlir::Value arg, Args... args) {
72 CIRGenBuilderTy &builder = cgf.getBuilder();
73 mlir::Location loc = cgf.getLoc(e->getSourceRange());
74 auto op = Op::create(builder, loc, arg, args...);
75 mlir::Value result = op.getResult();
76 mlir::Type resultTy = cgf.convertType(e->getType());
77 if (resultTy != result.getType())
78 result = builder.createIntCast(result, resultTy);
79 return result;
80}
81
82template <typename Op, typename... Args>
84 Args... args) {
85 mlir::Value arg = cgf.emitScalarExpr(e->getArg(0));
86 return RValue::get(createBuiltinBitOp<Op>(cgf, e, arg, args...));
87}
88
89template <typename Op>
91 const CallExpr *e) {
92 mlir::Value input = cgf.emitScalarExpr(e->getArg(0));
93 return RValue::get(
94 Op::create(cgf.getBuilder(), cgf.getLoc(e->getExprLoc()), input)
95 .getResult());
96}
97
98/// Emit a clz/ctz bit op with optional fallback for __builtin_c[lt]zg.
99/// When a fallback is present, the result is the fallback value if the input is
100/// zero, otherwise the bit count.
101template <typename Op>
103 const CallExpr *e) {
104 bool hasFallback = e->getNumArgs() > 1;
105 bool poisonZero = hasFallback || cgf.getTarget().isCLZForZeroUndef();
106
107 if (!hasFallback) {
109 return emitBuiltinBitOp<Op>(cgf, e, poisonZero);
110 }
111
113 mlir::Value arg = cgf.emitScalarExpr(e->getArg(0));
114 mlir::Value result = createBuiltinBitOp<Op>(cgf, e, arg, poisonZero);
115
116 CIRGenBuilderTy &builder = cgf.getBuilder();
117 mlir::Location loc = cgf.getLoc(e->getSourceRange());
118 mlir::Value zero = builder.getNullValue(arg.getType(), loc);
119 mlir::Value isZero =
120 builder.createCompare(loc, cir::CmpOpKind::eq, arg, zero);
121 mlir::Value fallbackValue = cgf.emitScalarExpr(e->getArg(1));
122 return RValue::get(builder.createSelect(loc, isZero, fallbackValue, result));
123}
124
125static bool isStdcBitOpWidthSupported(cir::IntType intTy) {
126 switch (intTy.getWidth()) {
127 case 8:
128 case 16:
129 case 32:
130 case 64:
131 case 128:
132 return true;
133 default:
134 return false;
135 }
136}
137
139 cgf.cgm.errorNYI(e->getSourceRange(),
140 "stdc bit builtin with unsupported argument integer width");
141 return cgf.getUndefRValue(e->getType());
142}
143
144template <typename Op, typename... Args>
146 bool invertArg, Args... args) {
147 CIRGenBuilderTy &builder = cgf.getBuilder();
148 mlir::Location loc = cgf.getLoc(e->getSourceRange());
149 mlir::Value arg = cgf.emitScalarExpr(e->getArg(0));
150 auto argTy = mlir::cast<cir::IntType>(arg.getType());
151 if (!isStdcBitOpWidthSupported(argTy))
152 return errorStdcBitOpWidthNYI(cgf, e);
153
154 mlir::Value actualArg = invertArg ? builder.createNot(loc, arg) : arg;
155 mlir::Value count = Op::create(builder, loc, actualArg, args...).getResult();
156
157 mlir::Value zero = builder.getNullValue(argTy, loc);
158 mlir::Value one = builder.getConstInt(loc, argTy, 1);
159 mlir::Value countPlusOne = builder.createAdd(loc, count, one);
160 mlir::Value isZero =
161 builder.createCompare(loc, cir::CmpOpKind::eq, actualArg, zero);
162 mlir::Value result = builder.createSelect(loc, isZero, zero, countPlusOne);
163
164 mlir::Type resultTy = cgf.convertType(e->getType());
165 if (result.getType() != resultTy)
166 result = builder.createIntCast(result, resultTy);
167
168 return RValue::get(result);
169}
170
172 CIRGenBuilderTy &builder = cgf.getBuilder();
173 mlir::Location loc = cgf.getLoc(e->getSourceRange());
174 mlir::Value arg = cgf.emitScalarExpr(e->getArg(0));
175 auto argTy = mlir::cast<cir::IntType>(arg.getType());
176 if (!isStdcBitOpWidthSupported(argTy))
177 return errorStdcBitOpWidthNYI(cgf, e);
178
179 mlir::Value one = builder.getConstInt(loc, argTy, 1);
180 mlir::Value argMinusOne = builder.createSub(loc, arg, one);
181 mlir::Value lz =
182 cir::BitClzOp::create(builder, loc, argMinusOne, /*poisonZero=*/false)
183 .getResult();
184 mlir::Value widthMinusOne =
185 builder.getConstInt(loc, argTy, argTy.getWidth() - 1);
186 mlir::Value shiftAmt = builder.createSub(loc, widthMinusOne, lz);
187 mlir::Value isLeOne =
188 builder.createCompare(loc, cir::CmpOpKind::le, arg, one);
189 mlir::Value two = builder.createShiftLeft(loc, one, one);
190 mlir::Value ceil = builder.createShiftLeft(loc, two, shiftAmt);
191 mlir::Value result = builder.createSelect(loc, isLeOne, one, ceil);
192 return RValue::get(result);
193}
194
195// stdc_{leading,trailing}_{zeros,ones} and stdc_count_ones: counts bits using
196// clz, ctz, or popcount. InvertArg flips the input to count the opposite bit
197// value.
198template <typename Op, typename... Args>
200 bool invertArg, Args... args) {
201 CIRGenBuilderTy &builder = cgf.getBuilder();
202 mlir::Location loc = cgf.getLoc(e->getSourceRange());
203 mlir::Value arg = cgf.emitScalarExpr(e->getArg(0));
204 if (!isStdcBitOpWidthSupported(mlir::cast<cir::IntType>(arg.getType())))
205 return errorStdcBitOpWidthNYI(cgf, e);
206 mlir::Value actualArg = invertArg ? builder.createNot(loc, arg) : arg;
207 mlir::Value result = Op::create(builder, loc, actualArg, args...).getResult();
208
209 mlir::Type resultTy = cgf.convertType(e->getType());
210 if (result.getType() != resultTy)
211 result = builder.createIntCast(result, resultTy);
212 return RValue::get(result);
213}
214
215// stdc_count_zeros (BitWidth - popcount) and stdc_bit_width (BitWidth - clz).
216// The subtract is performed in the argument type and cast once at the end.
217template <typename Op, typename... Args>
219 Args... args) {
220 CIRGenBuilderTy &builder = cgf.getBuilder();
221 mlir::Location loc = cgf.getLoc(e->getSourceRange());
222 mlir::Value arg = cgf.emitScalarExpr(e->getArg(0));
223 auto argTy = mlir::cast<cir::IntType>(arg.getType());
224 if (!isStdcBitOpWidthSupported(argTy))
225 return errorStdcBitOpWidthNYI(cgf, e);
226
227 mlir::Value cnt = Op::create(builder, loc, arg, args...).getResult();
228 mlir::Value width = builder.getConstInt(loc, argTy, argTy.getWidth());
229 mlir::Value result = builder.createSub(loc, width, cnt);
230
231 mlir::Type resultTy = cgf.convertType(e->getType());
232 if (result.getType() != resultTy)
233 result = builder.createIntCast(result, resultTy);
234
235 return RValue::get(result);
236}
237
239 CIRGenBuilderTy &builder = cgf.getBuilder();
240 mlir::Location loc = cgf.getLoc(e->getSourceRange());
241 mlir::Value arg = cgf.emitScalarExpr(e->getArg(0));
242 if (!isStdcBitOpWidthSupported(mlir::cast<cir::IntType>(arg.getType())))
243 return errorStdcBitOpWidthNYI(cgf, e);
244
245 mlir::Value popCount =
246 cir::BitPopcountOp::create(builder, loc, arg).getResult();
247 mlir::Value one = builder.getConstInt(loc, popCount.getType(), 1);
248 mlir::Value result =
249 builder.createCompare(loc, cir::CmpOpKind::eq, popCount, one);
250 return RValue::get(result);
251}
252
254 CIRGenBuilderTy &builder = cgf.getBuilder();
255 mlir::Location loc = cgf.getLoc(e->getSourceRange());
256 mlir::Value arg = cgf.emitScalarExpr(e->getArg(0));
257 auto argTy = mlir::cast<cir::IntType>(arg.getType());
258 if (!isStdcBitOpWidthSupported(argTy))
259 return errorStdcBitOpWidthNYI(cgf, e);
260
261 mlir::Value widthMinusOne =
262 builder.getConstInt(loc, argTy, argTy.getWidth() - 1);
263 mlir::Value one = builder.getConstInt(loc, argTy, 1);
264 mlir::Value lz =
265 cir::BitClzOp::create(builder, loc, arg, /*poisonZero=*/true).getResult();
266 mlir::Value shiftAmt = builder.createSub(loc, widthMinusOne, lz);
267 mlir::Value zero = builder.getNullValue(argTy, loc);
268 mlir::Value isZero =
269 builder.createCompare(loc, cir::CmpOpKind::eq, arg, zero);
270 mlir::Value floor = builder.createShiftLeft(loc, one, shiftAmt);
271 mlir::Value result = builder.createSelect(loc, isZero, zero, floor);
272 return RValue::get(result);
273}
274
275/// Emit the conversions required to turn the given value into an
276/// integer of the given size.
277static mlir::Value emitToInt(CIRGenFunction &cgf, mlir::Value v, QualType t,
278 cir::IntType intType) {
279 v = cgf.emitToMemory(v, t);
280
281 if (mlir::isa<cir::PointerType>(v.getType()))
282 return cgf.getBuilder().createPtrToInt(v, intType);
283
284 assert(v.getType() == intType);
285 return v;
286}
287
288static mlir::Value emitFromInt(CIRGenFunction &cgf, mlir::Value v, QualType t,
289 mlir::Type resultType) {
290 v = cgf.emitFromMemory(v, t);
291
292 if (mlir::isa<cir::PointerType>(resultType))
293 return cgf.getBuilder().createIntToPtr(v, resultType);
294
295 assert(v.getType() == resultType);
296 return v;
297}
298
299static mlir::Value emitSignBit(mlir::Location loc, CIRGenFunction &cgf,
300 mlir::Value val) {
302 cir::SignBitOp returnValue = cgf.getBuilder().createSignBit(loc, val);
303 return returnValue->getResult(0);
304}
305
307 ASTContext &astContext = cgf.getContext();
308 Address ptr = cgf.emitPointerWithAlignment(e->getArg(0));
309 unsigned bytes =
310 mlir::isa<cir::PointerType>(ptr.getElementType())
311 ? astContext.getTypeSizeInChars(astContext.VoidPtrTy).getQuantity()
314
315 unsigned align = ptr.getAlignment().getQuantity();
316 if (align % bytes != 0) {
317 DiagnosticsEngine &diags = cgf.cgm.getDiags();
318 diags.Report(e->getBeginLoc(), diag::warn_sync_op_misaligned);
319 // Force address to be at least naturally-aligned.
321 }
322 return ptr;
323}
324
325/// Utility to insert an atomic instruction based on Intrinsic::ID
326/// and the expression node.
327mlir::Value CIRGenFunction::makeBinaryAtomicValue(cir::AtomicFetchKind kind,
328 const CallExpr *expr,
329 mlir::Type *originalArgType,
330 mlir::Value *emittedArgValue,
331 cir::MemOrder ordering) {
332 CIRGenFunction &cgf = *this;
333
334 QualType type = expr->getType();
335 QualType ptrType = expr->getArg(0)->getType();
336
337 assert(ptrType->isPointerType());
338 assert(
341 expr->getArg(1)->getType()));
342
343 Address destAddr = checkAtomicAlignment(cgf, expr);
344 CIRGenBuilderTy &builder = cgf.getBuilder();
345
346 mlir::Value val = cgf.emitScalarExpr(expr->getArg(1));
347 mlir::Type valueType = val.getType();
348 mlir::Value destValue = destAddr.emitRawPointer();
349
350 if (ptrType->getPointeeType()->isPointerType()) {
351 // Pointer to pointer
352 // `cir.atomic.fetch` expects a pointer to an integer type, so we cast
353 // ptr<ptr<T>> to ptr<intPtrSize>
354 cir::IntType ptrSizeInt =
355 builder.getSIntNTy(cgf.getContext().getTypeSize(ptrType));
356 destValue =
357 builder.createBitcast(destValue, builder.getPointerTo(ptrSizeInt));
358 val = emitToInt(cgf, val, type, ptrSizeInt);
359 } else {
360 // Pointer to integer type
361 cir::IntType intType =
363 ? builder.getUIntNTy(cgf.getContext().getTypeSize(type))
364 : builder.getSIntNTy(cgf.getContext().getTypeSize(type));
365 val = emitToInt(cgf, val, type, intType);
366 }
367
368 // This output argument is needed for post atomic fetch operations
369 // that calculate the result of the operation as return value of
370 // <binop>_and_fetch builtins. The `AtomicFetch` operation only updates the
371 // memory location and returns the old value.
372 if (emittedArgValue) {
373 *emittedArgValue = val;
374 assert(originalArgType != nullptr &&
375 "originalArgType must be provided when emittedArgValue is set");
376 *originalArgType = valueType;
377 }
378
379 auto rmwi = cir::AtomicFetchOp::create(
380 builder, cgf.getLoc(expr->getSourceRange()), destValue, val, kind,
381 ordering, cir::SyncScopeKind::System, /*alignment=*/nullptr,
382 /*is_volatile=*/false, /*fetch_first=*/true);
383 return rmwi->getResult(0);
384}
385
387 cir::AtomicFetchKind atomicOpkind,
388 const CallExpr *e) {
389 return RValue::get(cgf.makeBinaryAtomicValue(atomicOpkind, e));
390}
391
392template <typename BinOp>
394 cir::AtomicFetchKind atomicOpkind,
395 const CallExpr *e, bool invert = false) {
396 mlir::Value emittedArgValue;
397 mlir::Type originalArgType;
398 clang::QualType typ = e->getType();
399 mlir::Value result = cgf.makeBinaryAtomicValue(
400 atomicOpkind, e, &originalArgType, &emittedArgValue);
402 result = BinOp::create(builder, result.getLoc(), result, emittedArgValue);
403
404 if (invert)
405 result = builder.createNot(result);
406
407 result = emitFromInt(cgf, result, typ, originalArgType);
408 return RValue::get(result);
409}
410
412 bool returnBool,
413 cir::MemOrder successOrder,
414 cir::MemOrder failureOrder,
415 cir::SyncScopeKind scope) {
416 Address destAddr = checkAtomicAlignment(*this, e);
417 CIRGenBuilderTy &builder = getBuilder();
418 mlir::Value destValue = destAddr.emitRawPointer();
419 mlir::Value expected = emitScalarExpr(e->getArg(1));
420 mlir::Value desired = emitScalarExpr(e->getArg(2));
421
422 auto cmpxchg = cir::AtomicCmpXchgOp::create(
423 builder, getLoc(e->getSourceRange()), destValue, expected, desired,
424 successOrder, failureOrder, scope,
425 /*alignment=*/nullptr, /*weak=*/false, /*is_volatile=*/false);
426
427 if (returnBool)
428 return cmpxchg.getSuccess();
429 return cmpxchg.getOld();
430}
431
432/// Emit a `cir.atomic.xchg` for __sync_swap_N and __sync_lock_test_and_set_N.
434 cir::MemOrder ordering) {
435 Address destAddr = checkAtomicAlignment(cgf, e);
436 CIRGenBuilderTy &builder = cgf.getBuilder();
437 mlir::Value destValue = destAddr.emitRawPointer();
438 mlir::Value val = cgf.emitScalarExpr(e->getArg(1));
439
440 auto xchg = cir::AtomicXchgOp::create(
441 builder, cgf.getLoc(e->getSourceRange()), destValue, val, ordering,
442 cir::SyncScopeKind::System, /*alignment=*/nullptr,
443 /*is_volatile=*/false);
444 return RValue::get(xchg.getResult());
445}
446
447/// Emit a release store of 0 for __sync_lock_release_N.
448static void emitAtomicLockRelease(CIRGenFunction &cgf, const CallExpr *e) {
449 CIRGenBuilderTy &builder = cgf.getBuilder();
450 Address destAddr = checkAtomicAlignment(cgf, e);
451 mlir::Location loc = cgf.getLoc(e->getSourceRange());
452 mlir::Type elemTy = destAddr.getElementType();
453 mlir::Value zero = builder.getConstant(loc, builder.getZeroInitAttr(elemTy));
454 auto orderAttr =
455 cir::MemOrderAttr::get(&cgf.getMLIRContext(), cir::MemOrder::Release);
456 auto scopeAttr = cir::SyncScopeKindAttr::get(&cgf.getMLIRContext(),
457 cir::SyncScopeKind::System);
458 builder.createStore(loc, zero, destAddr, /*isVolatile=*/false,
459 /*isNontemporal=*/false,
460 /*align=*/mlir::IntegerAttr{}, scopeAttr, orderAttr);
461}
462
464 cir::SyncScopeKind syncScope) {
465 CIRGenBuilderTy &builder = cgf.getBuilder();
466 mlir::Location loc = cgf.getLoc(expr->getSourceRange());
467
468 auto emitAtomicOpCallBackFn = [&](cir::MemOrder memOrder) {
469 cir::AtomicFenceOp::create(
470 builder, loc, memOrder,
471 cir::SyncScopeKindAttr::get(&cgf.getMLIRContext(), syncScope));
472 };
473
474 CIRGenFunction::EmittedOrderOrScope order(cgf, expr->getArg(0));
475 cgf.emitAtomicExprWithMemOrder(order, /*isStore*/ false,
476 /*isLoad*/ false, /*isFence*/ true,
477 emitAtomicOpCallBackFn);
478}
479
480// Emit a runtime call to bool __atomic_is_lock_free(size_t size, void *ptr).
481// For the __c11 builtin the pointer is null, since an _Atomic object is always
482// suitably aligned.
484 unsigned builtinID) {
485 CIRGenBuilderTy &builder = cgf.getBuilder();
486 mlir::Location loc = cgf.getLoc(e->getExprLoc());
487
488 mlir::Type sizeTy = cgf.convertType(cgf.getContext().getSizeType());
489 mlir::Value size = cgf.emitScalarExpr(e->getArg(0));
490 mlir::Value ptr;
491 if (builtinID == Builtin::BI__atomic_is_lock_free)
492 ptr = builder.createBitcast(cgf.emitScalarExpr(e->getArg(1)),
493 builder.getVoidPtrTy());
494 else
495 ptr = builder.getNullPtr(builder.getVoidPtrTy(), loc);
496
497 cir::FuncOp func = cgf.cgm.createRuntimeFunction(
498 cir::FuncType::get({sizeTy, builder.getVoidPtrTy()}, builder.getBoolTy()),
499 "__atomic_is_lock_free");
500 // TODO(cir): set the runtime calling convention to this call.
502 return RValue::get(
503 builder.createCallOp(loc, func, mlir::ValueRange{size, ptr}).getResult());
504}
505
506namespace {
507struct WidthAndSignedness {
508 unsigned width;
509 bool isSigned;
510};
511} // namespace
512
513static WidthAndSignedness
515 const clang::QualType type) {
516 assert(type->isIntegerType() && "Given type is not an integer.");
517 unsigned width = type->isBooleanType() ? 1
518 : type->isBitIntType() ? astContext.getIntWidth(type)
519 : astContext.getTypeInfo(type).Width;
520 bool isSigned = type->isSignedIntegerType();
521 return {width, isSigned};
522}
523
524/// Create a checked overflow arithmetic op and return its result and overflow
525/// flag.
526template <typename OpTy>
527static std::pair<mlir::Value, mlir::Value>
528emitOverflowOp(CIRGenBuilderTy &builder, mlir::Location loc,
529 mlir::Type resultTy, mlir::Value lhs, mlir::Value rhs) {
530 auto op = OpTy::create(builder, loc, resultTy, lhs, rhs);
531 return {op.getResult(), op.getOverflow()};
532}
533
534// Given one or more integer types, this function produces an integer type that
535// encompasses them: any value in one of the given types could be expressed in
536// the encompassing type.
537static struct WidthAndSignedness
538EncompassingIntegerType(ArrayRef<struct WidthAndSignedness> types) {
539 assert(types.size() > 0 && "Empty list of types.");
540
541 // If any of the given types is signed, we must return a signed type.
542 bool isSigned = llvm::any_of(types, [](const auto &t) { return t.isSigned; });
543
544 // The encompassing type must have a width greater than or equal to the width
545 // of the specified types. Additionally, if the encompassing type is signed,
546 // its width must be strictly greater than the width of any unsigned types
547 // given.
548 unsigned width = 0;
549 for (const auto &type : types)
550 width = std::max(width, type.width + (isSigned && !type.isSigned));
551
552 return {width, isSigned};
553}
554
555RValue CIRGenFunction::emitRotate(const CallExpr *e, bool isRotateLeft) {
556 mlir::Value input = emitScalarExpr(e->getArg(0));
557 mlir::Value amount = emitScalarExpr(e->getArg(1));
558
559 if (amount.getType() != input.getType())
560 amount = builder.createIntCast(amount, input.getType());
561
562 auto r = cir::RotateOp::create(builder, getLoc(e->getSourceRange()), input,
563 amount, isRotateLeft);
564 return RValue::get(r);
565}
566
567template <class Operation>
569 const CallExpr &e) {
570 mlir::Value arg = cgf.emitScalarExpr(e.getArg(0));
571
572 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, &e);
573
574 auto call = Operation::create(cgf.getBuilder(), arg.getLoc(), arg.getType(),
575 arg, cgf.getBuilder().getConstrainedFPAttr());
576 return RValue::get(call->getResult(0));
577}
578
579template <class Operation>
581 mlir::Value arg = cgf.emitScalarExpr(e.getArg(0));
582 auto call = Operation::create(cgf.getBuilder(), arg.getLoc(), arg);
583 return RValue::get(call->getResult(0));
584}
585
586template <typename Op>
588 const CallExpr &e) {
589 mlir::Type resultType = cgf.convertType(e.getType());
590 mlir::Value src = cgf.emitScalarExpr(e.getArg(0));
591
592 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, &e);
593
594 auto call = Op::create(cgf.getBuilder(), src.getLoc(), resultType, src,
596 return RValue::get(call->getResult(0));
597}
598
599template <typename Op>
601 mlir::Value arg0 = cgf.emitScalarExpr(e.getArg(0));
602 mlir::Value arg1 = cgf.emitScalarExpr(e.getArg(1));
603
604 mlir::Location loc = cgf.getLoc(e.getExprLoc());
605 auto call = Op::create(cgf.getBuilder(), loc, arg0, arg1);
606
607 return RValue::get(call->getResult(0));
608}
609
610template <typename Op>
612 const CallExpr &e) {
613 mlir::Value arg0 = cgf.emitScalarExpr(e.getArg(0));
614 mlir::Value arg1 = cgf.emitScalarExpr(e.getArg(1));
615 mlir::Value arg2 = cgf.emitScalarExpr(e.getArg(2));
616
617 mlir::Location loc = cgf.getLoc(e.getExprLoc());
618 mlir::Type ty = cgf.convertType(e.getType());
619 auto call = Op::create(cgf.getBuilder(), loc, ty, arg0, arg1, arg2);
620
621 return RValue::get(call->getResult(0));
622}
623
624template <typename Op>
626 const CallExpr &e) {
627 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, &e);
628
629 mlir::Value arg0 = cgf.emitScalarExpr(e.getArg(0));
630 mlir::Value arg1 = cgf.emitScalarExpr(e.getArg(1));
631 mlir::Value arg2 = cgf.emitScalarExpr(e.getArg(2));
632
633 mlir::Location loc = cgf.getLoc(e.getExprLoc());
634 mlir::Type ty = cgf.convertType(e.getType());
635
636 auto call = Op::create(cgf.getBuilder(), loc, ty, arg0, arg1, arg2,
639 return RValue::get(call->getResult(0));
640}
641
642template <typename Op>
644 const CallExpr &e) {
645 mlir::Value arg0 = cgf.emitScalarExpr(e.getArg(0));
646 mlir::Value arg1 = cgf.emitScalarExpr(e.getArg(1));
647
648 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(cgf, &e);
649
650 mlir::Location loc = cgf.getLoc(e.getExprLoc());
651 auto call = Op::create(cgf.getBuilder(), loc, arg0, arg1,
653 return call->getResult(0);
654}
655
657 unsigned builtinID) {
658
659 if (cgf.getContext().BuiltinInfo.isLibFunction(builtinID)) {
660 cgf.cgm.errorNYI(
661 e->getSourceRange(),
662 std::string("unimplemented library function builtin call: ") +
663 cgf.getContext().BuiltinInfo.getName(builtinID));
664 } else {
665 cgf.cgm.errorNYI(e->getSourceRange(),
666 std::string("unimplemented builtin call: ") +
667 cgf.getContext().BuiltinInfo.getName(builtinID));
668 }
669
670 return cgf.getUndefRValue(e->getType());
671}
672
674 unsigned builtinID) {
675 assert(builtinID == Builtin::BI__builtin_alloca ||
676 builtinID == Builtin::BI__builtin_alloca_uninitialized ||
677 builtinID == Builtin::BIalloca || builtinID == Builtin::BI_alloca);
678
679 // Get alloca size input
680 mlir::Value size = cgf.emitScalarExpr(e->getArg(0));
681
682 // The alignment of the alloca should correspond to __BIGGEST_ALIGNMENT__.
683 const TargetInfo &ti = cgf.getContext().getTargetInfo();
684 const CharUnits suitableAlignmentInBytes =
686
687 // Emit the alloca op with type `u8 *` to match the semantics of
688 // `llvm.alloca`. We later bitcast the type to `void *` to match the
689 // semantics of C/C++
690 // FIXME(cir): It may make sense to allow AllocaOp of type `u8` to return a
691 // pointer of type `void *`. This will require a change to the allocaOp
692 // verifier.
693 CIRGenBuilderTy &builder = cgf.getBuilder();
694 mlir::Value allocaAddr = builder.createAlloca(
695 cgf.getLoc(e->getSourceRange()), builder.getUInt8PtrTy(),
696 builder.getUInt8Ty(), "bi_alloca", suitableAlignmentInBytes, size);
697
698 // Initialize the allocated buffer if required.
699 if (builtinID != Builtin::BI__builtin_alloca_uninitialized) {
700 // Initialize the alloca with the given size and alignment according to
701 // the lang opts. Only the trivial non-initialization is supported for
702 // now.
703
704 switch (cgf.getLangOpts().getTrivialAutoVarInit()) {
706 // Nothing to initialize.
707 break;
710 cgf.cgm.errorNYI("trivial auto var init");
711 break;
712 }
713 }
714
715 // An alloca will always return a pointer to the alloca (stack) address
716 // space. This address space need not be the same as the AST / Language
717 // default (e.g. in C / C++ auto vars are in the generic address space). At
718 // the AST level this is handled within CreateTempAlloca et al., but for the
719 // builtin / dynamic alloca we have to handle it here.
720
724 cgf.cgm.errorNYI(e->getSourceRange(),
725 "Address Space Cast for builtin alloca");
726 }
727
728 // Bitcast the alloca to the expected type.
729 return RValue::get(builder.createBitcast(
730 allocaAddr, builder.getVoidPtrTy(cgf.getCIRAllocaAddressSpace())));
731}
732
734 unsigned builtinID) {
735 std::optional<bool> errnoOverriden;
736 // ErrnoOverriden is true if math-errno is overriden via the
737 // '#pragma float_control(precise, on)'. This pragma disables fast-math,
738 // which implies math-errno.
739 if (e->hasStoredFPFeatures()) {
741 if (op.hasMathErrnoOverride())
742 errnoOverriden = op.getMathErrnoOverride();
743 }
744 // True if 'attribute__((optnone))' is used. This attribute overrides
745 // fast-math which implies math-errno.
746 bool optNone =
747 cgf.curFuncDecl && cgf.curFuncDecl->hasAttr<OptimizeNoneAttr>();
748 bool isOptimizationEnabled = cgf.cgm.getCodeGenOpts().OptimizationLevel != 0;
749 bool generateFPMathIntrinsics =
751 builtinID, cgf.cgm.getTriple(), errnoOverriden,
752 cgf.getLangOpts().MathErrno, optNone, isOptimizationEnabled);
753 return generateFPMathIntrinsics;
754}
755
757 unsigned builtinID) {
759 switch (builtinID) {
760 case Builtin::BIacos:
761 case Builtin::BIacosf:
762 case Builtin::BIacosl:
763 case Builtin::BI__builtin_acos:
764 case Builtin::BI__builtin_acosf:
765 case Builtin::BI__builtin_acosf16:
766 case Builtin::BI__builtin_acosl:
767 case Builtin::BI__builtin_acosf128:
768 case Builtin::BI__builtin_elementwise_acos:
770 case Builtin::BIasin:
771 case Builtin::BIasinf:
772 case Builtin::BIasinl:
773 case Builtin::BI__builtin_asin:
774 case Builtin::BI__builtin_asinf:
775 case Builtin::BI__builtin_asinf16:
776 case Builtin::BI__builtin_asinl:
777 case Builtin::BI__builtin_asinf128:
778 case Builtin::BI__builtin_elementwise_asin:
780 case Builtin::BIatan:
781 case Builtin::BIatanf:
782 case Builtin::BIatanl:
783 case Builtin::BI__builtin_atan:
784 case Builtin::BI__builtin_atanf:
785 case Builtin::BI__builtin_atanf16:
786 case Builtin::BI__builtin_atanl:
787 case Builtin::BI__builtin_atanf128:
788 case Builtin::BI__builtin_elementwise_atan:
790 case Builtin::BIatan2:
791 case Builtin::BIatan2f:
792 case Builtin::BIatan2l:
793 case Builtin::BI__builtin_atan2:
794 case Builtin::BI__builtin_atan2f:
795 case Builtin::BI__builtin_atan2f16:
796 case Builtin::BI__builtin_atan2l:
797 case Builtin::BI__builtin_atan2f128:
798 case Builtin::BI__builtin_elementwise_atan2:
799 return RValue::get(
801 case Builtin::BIceil:
802 case Builtin::BIceilf:
803 case Builtin::BIceill:
804 case Builtin::BI__builtin_ceil:
805 case Builtin::BI__builtin_ceilf:
806 case Builtin::BI__builtin_ceilf16:
807 case Builtin::BI__builtin_ceill:
808 case Builtin::BI__builtin_ceilf128:
809 case Builtin::BI__builtin_elementwise_ceil:
811 case Builtin::BIcopysign:
812 case Builtin::BIcopysignf:
813 case Builtin::BIcopysignl:
814 case Builtin::BI__builtin_copysign:
815 case Builtin::BI__builtin_copysignf:
816 case Builtin::BI__builtin_copysignf16:
817 case Builtin::BI__builtin_copysignl:
818 case Builtin::BI__builtin_copysignf128:
820 case Builtin::BIcos:
821 case Builtin::BIcosf:
822 case Builtin::BIcosl:
823 case Builtin::BI__builtin_cos:
824 case Builtin::BI__builtin_cosf:
825 case Builtin::BI__builtin_cosf16:
826 case Builtin::BI__builtin_cosl:
827 case Builtin::BI__builtin_cosf128:
828 case Builtin::BI__builtin_elementwise_cos:
830 case Builtin::BIcosh:
831 case Builtin::BIcoshf:
832 case Builtin::BIcoshl:
833 case Builtin::BI__builtin_cosh:
834 case Builtin::BI__builtin_coshf:
835 case Builtin::BI__builtin_coshf16:
836 case Builtin::BI__builtin_coshl:
837 case Builtin::BI__builtin_coshf128:
838 case Builtin::BI__builtin_elementwise_cosh:
840 case Builtin::BIexp:
841 case Builtin::BIexpf:
842 case Builtin::BIexpl:
843 case Builtin::BI__builtin_exp:
844 case Builtin::BI__builtin_expf:
845 case Builtin::BI__builtin_expf16:
846 case Builtin::BI__builtin_expl:
847 case Builtin::BI__builtin_expf128:
848 case Builtin::BI__builtin_elementwise_exp:
850 case Builtin::BIexp2:
851 case Builtin::BIexp2f:
852 case Builtin::BIexp2l:
853 case Builtin::BI__builtin_exp2:
854 case Builtin::BI__builtin_exp2f:
855 case Builtin::BI__builtin_exp2f16:
856 case Builtin::BI__builtin_exp2l:
857 case Builtin::BI__builtin_exp2f128:
858 case Builtin::BI__builtin_elementwise_exp2:
860 case Builtin::BI__builtin_exp10:
861 case Builtin::BI__builtin_exp10f:
862 case Builtin::BI__builtin_exp10f16:
863 case Builtin::BI__builtin_exp10l:
864 case Builtin::BI__builtin_exp10f128:
865 case Builtin::BI__builtin_elementwise_exp10:
867 case Builtin::BIfabs:
868 case Builtin::BIfabsf:
869 case Builtin::BIfabsl:
870 case Builtin::BI__builtin_fabs:
871 case Builtin::BI__builtin_fabsf:
872 case Builtin::BI__builtin_fabsf16:
873 case Builtin::BI__builtin_fabsl:
874 case Builtin::BI__builtin_fabsf128:
876 case Builtin::BIfloor:
877 case Builtin::BIfloorf:
878 case Builtin::BIfloorl:
879 case Builtin::BI__builtin_floor:
880 case Builtin::BI__builtin_floorf:
881 case Builtin::BI__builtin_floorf16:
882 case Builtin::BI__builtin_floorl:
883 case Builtin::BI__builtin_floorf128:
884 case Builtin::BI__builtin_elementwise_floor:
886 case Builtin::BIfma:
887 case Builtin::BIfmaf:
888 case Builtin::BIfmal:
889 case Builtin::BI__builtin_fma:
890 case Builtin::BI__builtin_fmaf:
891 case Builtin::BI__builtin_fmaf16:
892 case Builtin::BI__builtin_fmal:
893 case Builtin::BI__builtin_fmaf128:
894 case Builtin::BI__builtin_elementwise_fma:
896 case Builtin::BIfmax:
897 case Builtin::BIfmaxf:
898 case Builtin::BIfmaxl:
899 case Builtin::BI__builtin_fmax:
900 case Builtin::BI__builtin_fmaxf:
901 case Builtin::BI__builtin_fmaxf16:
902 case Builtin::BI__builtin_fmaxl:
903 case Builtin::BI__builtin_fmaxf128:
904 return RValue::get(
906 case Builtin::BIfmin:
907 case Builtin::BIfminf:
908 case Builtin::BIfminl:
909 case Builtin::BI__builtin_fmin:
910 case Builtin::BI__builtin_fminf:
911 case Builtin::BI__builtin_fminf16:
912 case Builtin::BI__builtin_fminl:
913 case Builtin::BI__builtin_fminf128:
914 return RValue::get(
916 case Builtin::BIfmaximum_num:
917 case Builtin::BIfmaximum_numf:
918 case Builtin::BIfmaximum_numl:
919 case Builtin::BI__builtin_fmaximum_num:
920 case Builtin::BI__builtin_fmaximum_numf:
921 case Builtin::BI__builtin_fmaximum_numf16:
922 case Builtin::BI__builtin_fmaximum_numl:
923 case Builtin::BI__builtin_fmaximum_numf128:
924 case Builtin::BIfminimum_num:
925 case Builtin::BIfminimum_numf:
926 case Builtin::BIfminimum_numl:
927 case Builtin::BI__builtin_fminimum_num:
928 case Builtin::BI__builtin_fminimum_numf:
929 case Builtin::BI__builtin_fminimum_numf16:
930 case Builtin::BI__builtin_fminimum_numl:
931 case Builtin::BI__builtin_fminimum_numf128:
932 return errorBuiltinNYI(cgf, e, builtinID);
933 case Builtin::BIfmod:
934 case Builtin::BIfmodf:
935 case Builtin::BIfmodl:
936 case Builtin::BI__builtin_fmod:
937 case Builtin::BI__builtin_fmodf:
938 case Builtin::BI__builtin_fmodf16:
939 case Builtin::BI__builtin_fmodl:
940 case Builtin::BI__builtin_fmodf128:
941 case Builtin::BI__builtin_elementwise_fmod:
942 return RValue::get(
944 case Builtin::BIlog:
945 case Builtin::BIlogf:
946 case Builtin::BIlogl:
947 case Builtin::BI__builtin_log:
948 case Builtin::BI__builtin_logf:
949 case Builtin::BI__builtin_logf16:
950 case Builtin::BI__builtin_logl:
951 case Builtin::BI__builtin_logf128:
952 case Builtin::BI__builtin_elementwise_log:
954 case Builtin::BIlog10:
955 case Builtin::BIlog10f:
956 case Builtin::BIlog10l:
957 case Builtin::BI__builtin_log10:
958 case Builtin::BI__builtin_log10f:
959 case Builtin::BI__builtin_log10f16:
960 case Builtin::BI__builtin_log10l:
961 case Builtin::BI__builtin_log10f128:
962 case Builtin::BI__builtin_elementwise_log10:
964 case Builtin::BIlog2:
965 case Builtin::BIlog2f:
966 case Builtin::BIlog2l:
967 case Builtin::BI__builtin_log2:
968 case Builtin::BI__builtin_log2f:
969 case Builtin::BI__builtin_log2f16:
970 case Builtin::BI__builtin_log2l:
971 case Builtin::BI__builtin_log2f128:
972 case Builtin::BI__builtin_elementwise_log2:
974 case Builtin::BInearbyint:
975 case Builtin::BInearbyintf:
976 case Builtin::BInearbyintl:
977 case Builtin::BI__builtin_nearbyint:
978 case Builtin::BI__builtin_nearbyintf:
979 case Builtin::BI__builtin_nearbyintl:
980 case Builtin::BI__builtin_nearbyintf128:
981 case Builtin::BI__builtin_elementwise_nearbyint:
983 case Builtin::BIpow:
984 case Builtin::BIpowf:
985 case Builtin::BIpowl:
986 case Builtin::BI__builtin_pow:
987 case Builtin::BI__builtin_powf:
988 case Builtin::BI__builtin_powf16:
989 case Builtin::BI__builtin_powl:
990 case Builtin::BI__builtin_powf128:
991 return RValue::get(
993 case Builtin::BI__builtin_elementwise_pow:
994 return errorBuiltinNYI(cgf, e, builtinID);
995 case Builtin::BIrint:
996 case Builtin::BIrintf:
997 case Builtin::BIrintl:
998 case Builtin::BI__builtin_rint:
999 case Builtin::BI__builtin_rintf:
1000 case Builtin::BI__builtin_rintf16:
1001 case Builtin::BI__builtin_rintl:
1002 case Builtin::BI__builtin_rintf128:
1003 case Builtin::BI__builtin_elementwise_rint:
1005 case Builtin::BIround:
1006 case Builtin::BIroundf:
1007 case Builtin::BIroundl:
1008 case Builtin::BI__builtin_round:
1009 case Builtin::BI__builtin_roundf:
1010 case Builtin::BI__builtin_roundf16:
1011 case Builtin::BI__builtin_roundl:
1012 case Builtin::BI__builtin_roundf128:
1013 case Builtin::BI__builtin_elementwise_round:
1015 case Builtin::BIroundeven:
1016 case Builtin::BIroundevenf:
1017 case Builtin::BIroundevenl:
1018 case Builtin::BI__builtin_roundeven:
1019 case Builtin::BI__builtin_roundevenf:
1020 case Builtin::BI__builtin_roundevenf16:
1021 case Builtin::BI__builtin_roundevenl:
1022 case Builtin::BI__builtin_roundevenf128:
1023 case Builtin::BI__builtin_elementwise_roundeven:
1025 case Builtin::BIsin:
1026 case Builtin::BIsinf:
1027 case Builtin::BIsinl:
1028 case Builtin::BI__builtin_sin:
1029 case Builtin::BI__builtin_sinf:
1030 case Builtin::BI__builtin_sinf16:
1031 case Builtin::BI__builtin_sinl:
1032 case Builtin::BI__builtin_sinf128:
1033 case Builtin::BI__builtin_elementwise_sin:
1035 case Builtin::BIsinh:
1036 case Builtin::BIsinhf:
1037 case Builtin::BIsinhl:
1038 case Builtin::BI__builtin_sinh:
1039 case Builtin::BI__builtin_sinhf:
1040 case Builtin::BI__builtin_sinhf16:
1041 case Builtin::BI__builtin_sinhl:
1042 case Builtin::BI__builtin_sinhf128:
1043 case Builtin::BI__builtin_elementwise_sinh:
1045 case Builtin::BI__builtin_sincospi:
1046 case Builtin::BI__builtin_sincospif:
1047 case Builtin::BI__builtin_sincospil:
1048 case Builtin::BIsincos:
1049 case Builtin::BIsincosf:
1050 case Builtin::BIsincosl:
1051 case Builtin::BI__builtin_sincos:
1052 case Builtin::BI__builtin_sincosf:
1053 case Builtin::BI__builtin_sincosf16:
1054 case Builtin::BI__builtin_sincosl:
1055 case Builtin::BI__builtin_sincosf128:
1056 return errorBuiltinNYI(cgf, e, builtinID);
1057 case Builtin::BIsqrt:
1058 case Builtin::BIsqrtf:
1059 case Builtin::BIsqrtl:
1060 case Builtin::BI__builtin_sqrt:
1061 case Builtin::BI__builtin_sqrtf:
1062 case Builtin::BI__builtin_sqrtf16:
1063 case Builtin::BI__builtin_sqrtl:
1064 case Builtin::BI__builtin_sqrtf128:
1065 case Builtin::BI__builtin_elementwise_sqrt:
1067 case Builtin::BItan:
1068 case Builtin::BItanf:
1069 case Builtin::BItanl:
1070 case Builtin::BI__builtin_tan:
1071 case Builtin::BI__builtin_tanf:
1072 case Builtin::BI__builtin_tanf16:
1073 case Builtin::BI__builtin_tanl:
1074 case Builtin::BI__builtin_tanf128:
1075 case Builtin::BI__builtin_elementwise_tan:
1077 case Builtin::BItanh:
1078 case Builtin::BItanhf:
1079 case Builtin::BItanhl:
1080 case Builtin::BI__builtin_tanh:
1081 case Builtin::BI__builtin_tanhf:
1082 case Builtin::BI__builtin_tanhf16:
1083 case Builtin::BI__builtin_tanhl:
1084 case Builtin::BI__builtin_tanhf128:
1085 case Builtin::BI__builtin_elementwise_tanh:
1087 case Builtin::BItrunc:
1088 case Builtin::BItruncf:
1089 case Builtin::BItruncl:
1090 case Builtin::BI__builtin_trunc:
1091 case Builtin::BI__builtin_truncf:
1092 case Builtin::BI__builtin_truncf16:
1093 case Builtin::BI__builtin_truncl:
1094 case Builtin::BI__builtin_truncf128:
1095 case Builtin::BI__builtin_elementwise_trunc:
1097 case Builtin::BIlround:
1098 case Builtin::BIlroundf:
1099 case Builtin::BIlroundl:
1100 case Builtin::BI__builtin_lround:
1101 case Builtin::BI__builtin_lroundf:
1102 case Builtin::BI__builtin_lroundl:
1103 case Builtin::BI__builtin_lroundf128:
1105 case Builtin::BIllround:
1106 case Builtin::BIllroundf:
1107 case Builtin::BIllroundl:
1108 case Builtin::BI__builtin_llround:
1109 case Builtin::BI__builtin_llroundf:
1110 case Builtin::BI__builtin_llroundl:
1111 case Builtin::BI__builtin_llroundf128:
1113 case Builtin::BIlrint:
1114 case Builtin::BIlrintf:
1115 case Builtin::BIlrintl:
1116 case Builtin::BI__builtin_lrint:
1117 case Builtin::BI__builtin_lrintf:
1118 case Builtin::BI__builtin_lrintl:
1119 case Builtin::BI__builtin_lrintf128:
1121 case Builtin::BIllrint:
1122 case Builtin::BIllrintf:
1123 case Builtin::BIllrintl:
1124 case Builtin::BI__builtin_llrint:
1125 case Builtin::BI__builtin_llrintf:
1126 case Builtin::BI__builtin_llrintl:
1127 case Builtin::BI__builtin_llrintf128:
1129 case Builtin::BI__builtin_ldexp:
1130 case Builtin::BI__builtin_ldexpf:
1131 case Builtin::BI__builtin_ldexpl:
1132 case Builtin::BI__builtin_ldexpf16:
1133 case Builtin::BI__builtin_ldexpf128:
1134 case Builtin::BI__builtin_elementwise_ldexp:
1135 return RValue::get(
1137 default:
1138 break;
1139 }
1140
1141 return RValue::getIgnored();
1142}
1143
1144// FIXME: Remove cgf parameter when all descriptor kinds are implemented
1145static mlir::Type
1148 ArrayRef<mlir::Type> overloadTys, mlir::MLIRContext *context) {
1149 using namespace llvm::Intrinsic;
1150
1151 IITDescriptor descriptor = infos.front();
1152 infos = infos.slice(1);
1153
1154 switch (descriptor.Kind) {
1155 case IITDescriptor::Overloaded:
1156 case IITDescriptor::Match:
1157 if (descriptor.getOverloadIndex() < overloadTys.size())
1158 return overloadTys[descriptor.getOverloadIndex()];
1159 cgf.cgm.errorNYI("Overloaded intrinsic type without overload types");
1160 return cir::VoidType::get(context);
1161 case IITDescriptor::Void:
1162 return cir::VoidType::get(context);
1163 case IITDescriptor::Half:
1164 return cir::FP16Type::get(context);
1165 case IITDescriptor::BFloat:
1166 return cir::BF16Type::get(context);
1167 case IITDescriptor::Float:
1168 return cir::SingleType::get(context);
1169 case IITDescriptor::Double:
1170 return cir::DoubleType::get(context);
1171 case IITDescriptor::Quad:
1172 return cir::FP128Type::get(context);
1173 // If the intrinsic expects unsigned integers, the signedness is corrected in
1174 // correctIntegerSignedness()
1175 case IITDescriptor::Integer:
1176 return cir::IntType::get(context, descriptor.IntegerWidth,
1177 /*isSigned=*/true);
1178 case IITDescriptor::Vector: {
1179 mlir::Type elementType = decodeFixedType(cgf, infos, overloadTys, context);
1180 unsigned numElements = descriptor.VectorWidth.getFixedValue();
1181 return cir::VectorType::getFixed(elementType, numElements);
1182 }
1183 case IITDescriptor::Struct: {
1185 for (unsigned i = 0; i < descriptor.StructNumElements; ++i)
1186 members.push_back(decodeFixedType(cgf, infos, overloadTys, context));
1187 return cgf.getBuilder().getAnonRecordTy(
1188 members, /*packed=*/false, cir::RecordType::getAllDataKinds(members));
1189 }
1190 case IITDescriptor::Pointer: {
1191 mlir::Builder builder(context);
1192 auto addrSpace = cir::TargetAddressSpaceAttr::get(
1193 context, descriptor.PointerAddressSpace);
1194 return cir::PointerType::get(cir::VoidType::get(context), addrSpace);
1195 }
1196 default:
1197 cgf.cgm.errorNYI("Unimplemented intrinsic type descriptor");
1198 return cir::VoidType::get(context);
1199 }
1200}
1201
1202/// Helper function to correct integer signedness for intrinsic arguments and
1203/// return type. IIT always returns signed integers, but the actual intrinsic
1204/// may expect unsigned integers based on the AST FunctionDecl parameter types.
1205static mlir::Type correctIntegerSignedness(mlir::Type iitType, QualType astType,
1206 mlir::MLIRContext *context) {
1207 auto intTy = dyn_cast<cir::IntType>(iitType);
1208 if (!intTy)
1209 return iitType;
1210
1211 if (astType->isUnsignedIntegerType())
1212 return cir::IntType::get(context, intTy.getWidth(), /*isSigned=*/false);
1213
1214 return iitType;
1215}
1216
1217/// Helper function to correct the return type for intrinsic calls. This is
1218/// needed because the AST FunctionDecl may have a different return type than
1219/// the intrinsic's IIT descriptor. For example, builtins may need their
1220/// signedness corrected, or a builtin may return a bool while the intrinsic
1221/// returns an i1.
1222static mlir::Type correctReturnType(mlir::Type iitType,
1223 const FunctionDecl *funcDecl,
1224 mlir::MLIRContext *context) {
1225 if (!funcDecl)
1226 return iitType;
1227 QualType astType = funcDecl->getReturnType();
1228
1229 // Relabel the return type to cir.bool if the builtin returns a bool and
1230 // the intrinsic returns an i1.
1231 auto intTy = mlir::dyn_cast<cir::IntType>(iitType);
1232 if (intTy && intTy.getWidth() == 1 && astType->isBooleanType())
1233 return cir::BoolType::get(context);
1234
1235 return correctIntegerSignedness(iitType, astType, context);
1236}
1237
1238static mlir::Value getCorrectedPtr(mlir::Value argValue, mlir::Type expectedTy,
1239 CIRGenBuilderTy &builder) {
1240 auto ptrType = mlir::cast<cir::PointerType>(argValue.getType());
1241
1242 auto expectedPtrType = mlir::cast<cir::PointerType>(expectedTy);
1243 assert(ptrType != expectedPtrType && "types should not match");
1244
1245 if (ptrType.getAddrSpace() != expectedPtrType.getAddrSpace()) {
1247 "address space handling not yet implemented");
1248 auto newPtrType = cir::PointerType::get(ptrType.getPointee(),
1249 expectedPtrType.getAddrSpace());
1250 return builder.createAddrSpaceCast(argValue, newPtrType);
1251 }
1252
1253 return builder.createBitcast(argValue, expectedTy);
1254}
1255
1256cir::FuncType
1258 ArrayRef<mlir::Type> overloadTys) {
1259 using namespace llvm::Intrinsic;
1260
1261 mlir::MLIRContext *context = &getMLIRContext();
1263 auto [tableRef, _, isVarArg] = getIntrinsicInfoTableEntries(id, table);
1264
1265 mlir::Type resultTy = decodeFixedType(*this, tableRef, overloadTys, context);
1266
1268 while (!tableRef.empty())
1269 argTypes.push_back(decodeFixedType(*this, tableRef, overloadTys, context));
1270
1271 // CIR convention: no explicit void return type
1272 if (isa<cir::VoidType>(resultTy))
1273 return cir::FuncType::get(context, argTypes, /*optionalReturnType=*/nullptr,
1274 isVarArg);
1275
1276 return cir::FuncType::get(context, argTypes, resultTy, isVarArg);
1277}
1278
1280 const FunctionDecl *targetDecl) {
1281 const FunctionDecl *fd = dyn_cast_or_null<FunctionDecl>(curCodeDecl);
1283 e, fd, targetDecl);
1284}
1285
1287 const FunctionDecl *targetDecl) {
1288 const FunctionDecl *fd = dyn_cast_or_null<FunctionDecl>(curCodeDecl);
1290 loc, fd, targetDecl);
1291}
1292
1294 const CallExpr *e,
1296 mlir::Location loc = getLoc(e->getSourceRange());
1297
1298 // See if we can constant fold this builtin. If so, don't emit it at all.
1299 // TODO: Extend this handling to all builtin calls that we can constant-fold.
1300 // Do not constant-fold immediate (target-specific) builtins; their ASTs can
1301 // trigger the constant evaluator in cases it cannot safely handle.
1302 // Skip EvaluateAsRValue for those.
1303 Expr::EvalResult result;
1304 if (e->isPRValue() && !getContext().BuiltinInfo.isImmediate(builtinID) &&
1305 e->EvaluateAsRValue(result, cgm.getASTContext()) &&
1306 !result.hasSideEffects()) {
1307 if (result.Val.isInt()) {
1308 QualType type = e->getType();
1309 if (type->isBooleanType())
1310 return RValue::get(
1311 builder.getBool(result.Val.getInt().getBoolValue(), loc));
1312 return RValue::get(builder.getConstInt(loc, result.Val.getInt()));
1313 }
1314 if (result.Val.isFloat()) {
1315 // Note: we are using result type of CallExpr to determine the type of
1316 // the constant. Classic codegen uses the result value to determine the
1317 // type. We feel it should be Ok to use expression type because it is
1318 // hard to imagine a builtin function evaluates to a value that
1319 // over/underflows its own defined type.
1320 mlir::Type type = convertType(e->getType());
1321 return RValue::get(builder.getConstFP(loc, type, result.Val.getFloat()));
1322 }
1323 }
1324
1325 const FunctionDecl *fd = gd.getDecl()->getAsFunction();
1326
1328
1329 // If the builtin has been declared explicitly with an assembler label,
1330 // disable the specialized emitting below. Ideally we should communicate the
1331 // rename in IR, or at least avoid generating the intrinsic calls that are
1332 // likely to get lowered to the renamed library functions.
1333 unsigned builtinIDIfNoAsmLabel = fd->hasAttr<AsmLabelAttr>() ? 0 : builtinID;
1334
1335 bool generateFPMathIntrinsics =
1336 shouldCIREmitFPMathIntrinsic(*this, e, builtinID);
1337
1338 if (generateFPMathIntrinsics) {
1339 // Try to match the builtinID with a floating point math builtin.
1340 RValue rv = tryEmitFPMathIntrinsic(*this, e, builtinIDIfNoAsmLabel);
1341
1342 // Return the result directly if a math intrinsic was generated.
1343 if (!rv.isIgnored()) {
1344 return rv;
1345 }
1346 }
1347
1349
1350 switch (builtinIDIfNoAsmLabel) {
1351 default:
1352 break;
1353
1354 // C stdarg builtins.
1355 case Builtin::BI__builtin_stdarg_start:
1356 case Builtin::BI__builtin_va_start:
1357 case Builtin::BI__va_start:
1358 case Builtin::BI__builtin_c23_va_start: {
1359 mlir::Value vaList = builtinID == Builtin::BI__va_start
1360 ? emitScalarExpr(e->getArg(0))
1361 : emitVAListRef(e->getArg(0)).getPointer();
1362 emitVAStart(vaList);
1363 return {};
1364 }
1365
1366 case Builtin::BI__builtin_va_end:
1368 return {};
1369 case Builtin::BI__builtin_va_copy: {
1370 mlir::Value dstPtr = emitVAListRef(e->getArg(0)).getPointer();
1371 mlir::Value srcPtr = emitVAListRef(e->getArg(1)).getPointer();
1372 cir::VACopyOp::create(builder, dstPtr.getLoc(), dstPtr, srcPtr);
1373 return {};
1374 }
1375
1376 case Builtin::BIabs:
1377 case Builtin::BIlabs:
1378 case Builtin::BIllabs:
1379 case Builtin::BI__builtin_abs:
1380 case Builtin::BI__builtin_labs:
1381 case Builtin::BI__builtin_llabs: {
1382 bool sanitizeOverflow = sanOpts.has(SanitizerKind::SignedIntegerOverflow);
1383 mlir::Value arg = emitScalarExpr(e->getArg(0));
1384 mlir::Value result;
1385 switch (getLangOpts().getSignedOverflowBehavior()) {
1387 result = cir::AbsOp::create(builder, loc, arg.getType(), arg,
1388 /*minIsPoison=*/false);
1389 break;
1391 if (!sanitizeOverflow) {
1392 result = cir::AbsOp::create(builder, loc, arg.getType(), arg,
1393 /*minIsPoison=*/true);
1394 break;
1395 }
1396 [[fallthrough]];
1398 cgm.errorNYI(e->getSourceRange(), "abs with overflow handling");
1399 return RValue::get(nullptr);
1400 }
1401 return RValue::get(result);
1402 }
1403
1404 case Builtin::BI__builtin_complex: {
1405 mlir::Value real = emitScalarExpr(e->getArg(0));
1406 mlir::Value imag = emitScalarExpr(e->getArg(1));
1407 mlir::Value complex = builder.createComplexCreate(loc, real, imag);
1408 return RValue::getComplex(complex);
1409 }
1410
1411 case Builtin::BI__builtin_conj:
1412 case Builtin::BI__builtin_conjf:
1413 case Builtin::BI__builtin_conjl:
1414 case Builtin::BIconj:
1415 case Builtin::BIconjf:
1416 case Builtin::BIconjl: {
1417 mlir::Value complex = emitComplexExpr(e->getArg(0));
1418 mlir::Value conj = builder.createComplexConj(loc, complex);
1419 return RValue::getComplex(conj);
1420 }
1421
1422 case Builtin::BI__builtin_creal:
1423 case Builtin::BI__builtin_crealf:
1424 case Builtin::BI__builtin_creall:
1425 case Builtin::BIcreal:
1426 case Builtin::BIcrealf:
1427 case Builtin::BIcreall: {
1428 mlir::Value complex = emitComplexExpr(e->getArg(0));
1429 mlir::Value real = builder.createComplexReal(loc, complex);
1430 return RValue::get(real);
1431 }
1432
1433 case Builtin::BI__builtin_cimag:
1434 case Builtin::BI__builtin_cimagf:
1435 case Builtin::BI__builtin_cimagl:
1436 case Builtin::BIcimag:
1437 case Builtin::BIcimagf:
1438 case Builtin::BIcimagl: {
1439 mlir::Value complex = emitComplexExpr(e->getArg(0));
1440 mlir::Value imag = builder.createComplexImag(loc, complex);
1441 return RValue::get(imag);
1442 }
1443
1444 case Builtin::BI__builtin_clrsb:
1445 case Builtin::BI__builtin_clrsbl:
1446 case Builtin::BI__builtin_clrsbll:
1447 return emitBuiltinBitOp<cir::BitClrsbOp>(*this, e);
1448
1449 case Builtin::BI__builtin_ctzs:
1450 case Builtin::BI__builtin_ctz:
1451 case Builtin::BI__builtin_ctzl:
1452 case Builtin::BI__builtin_ctzll:
1454 return emitBuiltinBitOp<cir::BitCtzOp>(*this, e,
1455 getTarget().isCLZForZeroUndef());
1456 case Builtin::BI__builtin_ctzg:
1458 case Builtin::BI__builtin_elementwise_ctzg:
1459 cgm.errorNYI(e->getSourceRange(), "__builtin_elementwise_ctzg");
1460 return RValue::get(nullptr);
1461
1462 case Builtin::BI__builtin_clzs:
1463 case Builtin::BI__builtin_clz:
1464 case Builtin::BI__builtin_clzl:
1465 case Builtin::BI__builtin_clzll:
1467 return emitBuiltinBitOp<cir::BitClzOp>(*this, e,
1468 getTarget().isCLZForZeroUndef());
1469 case Builtin::BI__builtin_clzg:
1471 case Builtin::BI__builtin_elementwise_clzg:
1472 cgm.errorNYI(e->getSourceRange(), "__builtin_elementwise_clzg");
1473 return RValue::get(nullptr);
1474
1475 case Builtin::BI__builtin_ffs:
1476 case Builtin::BI__builtin_ffsl:
1477 case Builtin::BI__builtin_ffsll:
1478 return emitBuiltinBitOp<cir::BitFfsOp>(*this, e);
1479
1480 case Builtin::BI__builtin_parity:
1481 case Builtin::BI__builtin_parityl:
1482 case Builtin::BI__builtin_parityll:
1483 return emitBuiltinBitOp<cir::BitParityOp>(*this, e);
1484
1485 case Builtin::BI__lzcnt16:
1486 case Builtin::BI__lzcnt:
1487 case Builtin::BI__lzcnt64:
1488 return emitBuiltinBitOp<cir::BitClzOp>(*this, e);
1489
1490 case Builtin::BI__popcnt16:
1491 case Builtin::BI__popcnt:
1492 case Builtin::BI__popcnt64:
1493 case Builtin::BI__builtin_popcount:
1494 case Builtin::BI__builtin_popcountl:
1495 case Builtin::BI__builtin_popcountll:
1496 case Builtin::BI__builtin_popcountg:
1497 return emitBuiltinBitOp<cir::BitPopcountOp>(*this, e);
1498
1499 // Always return the argument of __builtin_unpredictable. LLVM does not
1500 // have an intrinsic corresponding to this builtin. Metadata for this
1501 // builtin should be added directly to instructions such as branches or
1502 // switches that use it.
1503 case Builtin::BI__builtin_unpredictable: {
1504 return RValue::get(emitScalarExpr(e->getArg(0)));
1505 }
1506
1507 case Builtin::BI__builtin_expect:
1508 case Builtin::BI__builtin_expect_with_probability: {
1509 mlir::Value argValue = emitScalarExpr(e->getArg(0));
1510 if (cgm.getCodeGenOpts().OptimizationLevel == 0)
1511 return RValue::get(argValue);
1512
1513 mlir::Value expectedValue = emitScalarExpr(e->getArg(1));
1514
1515 mlir::FloatAttr probAttr;
1516 if (builtinIDIfNoAsmLabel == Builtin::BI__builtin_expect_with_probability) {
1517 llvm::APFloat probability(0.0);
1518 const Expr *probArg = e->getArg(2);
1519 [[maybe_unused]] bool evalSucceeded =
1520 probArg->EvaluateAsFloat(probability, cgm.getASTContext());
1521 assert(evalSucceeded &&
1522 "probability should be able to evaluate as float");
1523 bool loseInfo = false; // ignored
1524 probability.convert(llvm::APFloat::IEEEdouble(),
1525 llvm::RoundingMode::Dynamic, &loseInfo);
1526 probAttr = mlir::FloatAttr::get(mlir::Float64Type::get(&getMLIRContext()),
1527 probability);
1528 }
1529
1530 auto result = cir::ExpectOp::create(builder, loc, argValue.getType(),
1531 argValue, expectedValue, probAttr);
1532 return RValue::get(result);
1533 }
1534
1535 case Builtin::BI__builtin_assume_aligned: {
1536 const Expr *ptrExpr = e->getArg(0);
1537 mlir::Value ptrValue = emitScalarExpr(ptrExpr);
1538 mlir::Value offsetValue =
1539 (e->getNumArgs() > 2) ? emitScalarExpr(e->getArg(2)) : nullptr;
1540
1541 std::optional<llvm::APSInt> alignment =
1543 assert(alignment.has_value() &&
1544 "the second argument to __builtin_assume_aligned must be an "
1545 "integral constant expression");
1546
1547 mlir::Value result =
1548 emitAlignmentAssumption(ptrValue, ptrExpr, ptrExpr->getExprLoc(),
1549 alignment->getSExtValue(), offsetValue);
1550 return RValue::get(result);
1551 }
1552
1553 case Builtin::BI__builtin_assume_dereferenceable: {
1554 mlir::Value ptrValue = emitScalarExpr(e->getArg(0));
1555 mlir::Value sizeValue = emitScalarExpr(e->getArg(1));
1556 // The `dereferenceable` operand bundle expects a pointer-sized unsigned
1557 // integer; widen/narrow as needed.
1558 mlir::Type uintPtrTy = convertType(getContext().getUIntPtrType());
1559 if (sizeValue.getType() != uintPtrTy)
1560 sizeValue = builder.createIntCast(sizeValue, uintPtrTy);
1561 mlir::Value cond = builder.getBool(true, loc);
1562 cir::AssumeOp::create(builder, loc, cond,
1563 cir::AssumeBundleKind::Dereferenceable,
1564 mlir::ValueRange{ptrValue, sizeValue});
1565 return RValue::get(nullptr);
1566 }
1567
1568 case Builtin::BI__builtin_annotation: {
1569 mlir::Value value = emitScalarExpr(e->getArg(0));
1570 StringRef str =
1571 cast<StringLiteral>(e->getArg(1)->IgnoreParenCasts())->getString();
1572 auto annotation = cir::AnnotationAttr::get(
1573 &getMLIRContext(), builder.getStringAttr(str), /*args=*/{});
1574 return RValue::get(cir::AnnotationOp::create(
1575 builder, getLoc(e->getExprLoc()), value, annotation));
1576 }
1577
1578 case Builtin::BI__assume:
1579 case Builtin::BI__builtin_assume: {
1580 if (e->getArg(0)->HasSideEffects(getContext()))
1581 return RValue::get(nullptr);
1582
1583 mlir::Value argValue = emitCheckedArgForAssume(e->getArg(0));
1584 cir::AssumeOp::create(builder, loc, argValue, cir::AssumeBundleKind::None,
1585 mlir::ValueRange{});
1586 return RValue::get(nullptr);
1587 }
1588
1589 case Builtin::BI__builtin_assume_separate_storage: {
1590 mlir::Value value0 = emitScalarExpr(e->getArg(0));
1591 mlir::Value value1 = emitScalarExpr(e->getArg(1));
1592 mlir::Value cond = builder.getBool(true, loc);
1593 cir::AssumeOp::create(builder, loc, cond,
1594 cir::AssumeBundleKind::SeparateStorage,
1595 mlir::ValueRange{value0, value1});
1596 return RValue::get(nullptr);
1597 }
1598
1599 case Builtin::BI__arithmetic_fence: {
1601 QualType argType = e->getArg(0)->getType();
1602 FPOptions fpFeatures = e->getFPFeaturesInEffect(getLangOpts());
1603 if (fpFeatures.getAllowFPReassociate() &&
1604 getContext().getTargetInfo().checkArithmeticFenceSupported()) {
1605 cgm.errorNYI(e->getSourceRange(), "__arithmetic_fence with reassocc");
1606 }
1607 if (argType->isComplexType())
1609 return RValue::get(emitScalarExpr(e->getArg(0)));
1610 }
1611
1612 case Builtin::BI__builtin_bswapg: {
1613 mlir::Value arg = emitScalarExpr(e->getArg(0));
1614 // CIR models bool as cir.bool rather than an integer, so peel it off
1615 // before the cast below. Like classic codegen's i1 case, it byte-swaps
1616 // to itself.
1617 if (mlir::isa<cir::BoolType>(arg.getType()))
1618 return RValue::get(arg);
1619 auto argTy = mlir::cast<cir::IntType>(arg.getType());
1620 // A single bit or a single byte byte-swaps to itself.
1621 if (argTy.getWidth() == 1 || argTy.getWidth() == 8)
1622 return RValue::get(arg);
1623 assert(argTy.getWidth() % 16 == 0 &&
1624 "__builtin_bswapg requires a single byte or a multiple of 16 bits");
1625 // cir.byte_swap requires an unsigned operand. Reinterpret a signed
1626 // argument as unsigned of the same width; createBuiltinBitOp casts the
1627 // swapped result back to the builtin's (possibly signed) return type.
1628 if (argTy.isSigned())
1629 arg = builder.createIntCast(arg, builder.getUIntNTy(argTy.getWidth()));
1630 return RValue::get(createBuiltinBitOp<cir::ByteSwapOp>(*this, e, arg));
1631 }
1632
1633 case Builtin::BI__builtin_bswap16:
1634 case Builtin::BI__builtin_bswap32:
1635 case Builtin::BI__builtin_bswap64:
1636 case Builtin::BI_byteswap_ushort:
1637 case Builtin::BI_byteswap_ulong:
1638 case Builtin::BI_byteswap_uint64: {
1639 mlir::Value arg = emitScalarExpr(e->getArg(0));
1640 return RValue::get(cir::ByteSwapOp::create(builder, loc, arg));
1641 }
1642
1643 case Builtin::BI__builtin_bitreverse8:
1644 case Builtin::BI__builtin_bitreverse16:
1645 case Builtin::BI__builtin_bitreverse32:
1646 case Builtin::BI__builtin_bitreverse64: {
1647 mlir::Value arg = emitScalarExpr(e->getArg(0));
1648 return RValue::get(cir::BitReverseOp::create(builder, loc, arg));
1649 }
1650
1651 case Builtin::BI__builtin_rotateleft8:
1652 case Builtin::BI__builtin_rotateleft16:
1653 case Builtin::BI__builtin_rotateleft32:
1654 case Builtin::BI__builtin_rotateleft64:
1655 case Builtin::BI__builtin_stdc_rotate_left:
1656 case Builtin::BIstdc_rotate_left_uc:
1657 case Builtin::BIstdc_rotate_left_us:
1658 case Builtin::BIstdc_rotate_left_ui:
1659 case Builtin::BIstdc_rotate_left_ul:
1660 case Builtin::BIstdc_rotate_left_ull:
1661 return emitRotate(e, /*isRotateLeft=*/true);
1662
1663 case Builtin::BI__builtin_rotateright8:
1664 case Builtin::BI__builtin_rotateright16:
1665 case Builtin::BI__builtin_rotateright32:
1666 case Builtin::BI__builtin_rotateright64:
1667 case Builtin::BI__builtin_stdc_rotate_right:
1668 case Builtin::BIstdc_rotate_right_uc:
1669 case Builtin::BIstdc_rotate_right_us:
1670 case Builtin::BIstdc_rotate_right_ui:
1671 case Builtin::BIstdc_rotate_right_ul:
1672 case Builtin::BIstdc_rotate_right_ull:
1673 return emitRotate(e, /*isRotateLeft=*/false);
1674
1675 case Builtin::BIstdc_leading_zeros_uc:
1676 case Builtin::BIstdc_leading_zeros_us:
1677 case Builtin::BIstdc_leading_zeros_ui:
1678 case Builtin::BIstdc_leading_zeros_ul:
1679 case Builtin::BIstdc_leading_zeros_ull:
1680 case Builtin::BI__builtin_stdc_leading_zeros:
1681 return emitStdcCountOp<cir::BitClzOp>(*this, e, /*invertArg=*/false,
1682 /*poisonZero=*/false);
1683
1684 case Builtin::BIstdc_leading_ones_uc:
1685 case Builtin::BIstdc_leading_ones_us:
1686 case Builtin::BIstdc_leading_ones_ui:
1687 case Builtin::BIstdc_leading_ones_ul:
1688 case Builtin::BIstdc_leading_ones_ull:
1689 case Builtin::BI__builtin_stdc_leading_ones:
1690 return emitStdcCountOp<cir::BitClzOp>(*this, e, /*invertArg=*/true,
1691 /*poisonZero=*/false);
1692
1693 case Builtin::BIstdc_trailing_zeros_uc:
1694 case Builtin::BIstdc_trailing_zeros_us:
1695 case Builtin::BIstdc_trailing_zeros_ui:
1696 case Builtin::BIstdc_trailing_zeros_ul:
1697 case Builtin::BIstdc_trailing_zeros_ull:
1698 case Builtin::BI__builtin_stdc_trailing_zeros:
1699 return emitStdcCountOp<cir::BitCtzOp>(*this, e, /*invertArg=*/false,
1700 /*poisonZero=*/false);
1701
1702 case Builtin::BIstdc_trailing_ones_uc:
1703 case Builtin::BIstdc_trailing_ones_us:
1704 case Builtin::BIstdc_trailing_ones_ui:
1705 case Builtin::BIstdc_trailing_ones_ul:
1706 case Builtin::BIstdc_trailing_ones_ull:
1707 case Builtin::BI__builtin_stdc_trailing_ones:
1708 return emitStdcCountOp<cir::BitCtzOp>(*this, e, /*invertArg=*/true,
1709 /*poisonZero=*/false);
1710
1711 case Builtin::BIstdc_first_leading_zero_uc:
1712 case Builtin::BIstdc_first_leading_zero_us:
1713 case Builtin::BIstdc_first_leading_zero_ui:
1714 case Builtin::BIstdc_first_leading_zero_ul:
1715 case Builtin::BIstdc_first_leading_zero_ull:
1716 case Builtin::BI__builtin_stdc_first_leading_zero:
1717 return emitStdcFirstBit<cir::BitClzOp>(*this, e, /*invertArg=*/true,
1718 /*poisonZero=*/false);
1719
1720 case Builtin::BIstdc_first_leading_one_uc:
1721 case Builtin::BIstdc_first_leading_one_us:
1722 case Builtin::BIstdc_first_leading_one_ui:
1723 case Builtin::BIstdc_first_leading_one_ul:
1724 case Builtin::BIstdc_first_leading_one_ull:
1725 case Builtin::BI__builtin_stdc_first_leading_one:
1726 return emitStdcFirstBit<cir::BitClzOp>(*this, e, /*invertArg=*/false,
1727 /*poisonZero=*/false);
1728
1729 case Builtin::BIstdc_first_trailing_zero_uc:
1730 case Builtin::BIstdc_first_trailing_zero_us:
1731 case Builtin::BIstdc_first_trailing_zero_ui:
1732 case Builtin::BIstdc_first_trailing_zero_ul:
1733 case Builtin::BIstdc_first_trailing_zero_ull:
1734 case Builtin::BI__builtin_stdc_first_trailing_zero:
1735 return emitStdcFirstBit<cir::BitCtzOp>(*this, e, /*invertArg=*/true,
1736 /*poisonZero=*/false);
1737
1738 case Builtin::BIstdc_first_trailing_one_uc:
1739 case Builtin::BIstdc_first_trailing_one_us:
1740 case Builtin::BIstdc_first_trailing_one_ui:
1741 case Builtin::BIstdc_first_trailing_one_ul:
1742 case Builtin::BIstdc_first_trailing_one_ull:
1743 case Builtin::BI__builtin_stdc_first_trailing_one:
1744 return emitStdcFirstBit<cir::BitCtzOp>(*this, e, /*invertArg=*/false,
1745 /*poisonZero=*/false);
1746
1747 case Builtin::BIstdc_count_zeros_uc:
1748 case Builtin::BIstdc_count_zeros_us:
1749 case Builtin::BIstdc_count_zeros_ui:
1750 case Builtin::BIstdc_count_zeros_ul:
1751 case Builtin::BIstdc_count_zeros_ull:
1752 case Builtin::BI__builtin_stdc_count_zeros:
1754
1755 case Builtin::BIstdc_count_ones_uc:
1756 case Builtin::BIstdc_count_ones_us:
1757 case Builtin::BIstdc_count_ones_ui:
1758 case Builtin::BIstdc_count_ones_ul:
1759 case Builtin::BIstdc_count_ones_ull:
1760 case Builtin::BI__builtin_stdc_count_ones:
1762 /*invertArg=*/false);
1763
1764 case Builtin::BIstdc_has_single_bit_uc:
1765 case Builtin::BIstdc_has_single_bit_us:
1766 case Builtin::BIstdc_has_single_bit_ui:
1767 case Builtin::BIstdc_has_single_bit_ul:
1768 case Builtin::BIstdc_has_single_bit_ull:
1769 case Builtin::BI__builtin_stdc_has_single_bit:
1770 return emitStdcHasSingleBit(*this, e);
1771
1772 case Builtin::BIstdc_bit_width_uc:
1773 case Builtin::BIstdc_bit_width_us:
1774 case Builtin::BIstdc_bit_width_ui:
1775 case Builtin::BIstdc_bit_width_ul:
1776 case Builtin::BIstdc_bit_width_ull:
1777 case Builtin::BI__builtin_stdc_bit_width:
1779 /*poisonZero=*/false);
1780
1781 case Builtin::BIstdc_bit_floor_uc:
1782 case Builtin::BIstdc_bit_floor_us:
1783 case Builtin::BIstdc_bit_floor_ui:
1784 case Builtin::BIstdc_bit_floor_ul:
1785 case Builtin::BIstdc_bit_floor_ull:
1786 case Builtin::BI__builtin_stdc_bit_floor:
1787 return emitStdcBitFloor(*this, e);
1788
1789 case Builtin::BIstdc_bit_ceil_uc:
1790 case Builtin::BIstdc_bit_ceil_us:
1791 case Builtin::BIstdc_bit_ceil_ui:
1792 case Builtin::BIstdc_bit_ceil_ul:
1793 case Builtin::BIstdc_bit_ceil_ull:
1794 case Builtin::BI__builtin_stdc_bit_ceil:
1795 return emitStdcBitCeil(*this, e);
1796
1797 // stdc_memreverse8u8 is a no-op (single byte, nothing to swap).
1798 case Builtin::BIstdc_memreverse8u8:
1799 return RValue::get(emitScalarExpr(e->getArg(0)));
1800 case Builtin::BIstdc_memreverse8u16:
1801 case Builtin::BIstdc_memreverse8u32:
1802 case Builtin::BIstdc_memreverse8u64: {
1803 mlir::Value arg = emitScalarExpr(e->getArg(0));
1804 return RValue::get(cir::ByteSwapOp::create(builder, loc, arg));
1805 }
1806 case Builtin::BIstdc_memreverse8:
1807 case Builtin::BI__builtin_stdc_memreverse8: {
1808 Expr::EvalResult result;
1809 if (e->getArg(0)->EvaluateAsInt(result, getContext())) {
1810 uint64_t size = result.Val.getInt().getZExtValue();
1811 if (size <= 1) {
1812 emitIgnoredExpr(e->getArg(1));
1813 return RValue::get(nullptr);
1814 }
1815 if (size == 2 || size == 4 || size == 8) {
1816 mlir::Location loc = getLoc(e->getSourceRange());
1817 Address ptrAddr = emitPointerWithAlignment(e->getArg(1));
1818 mlir::Type intTy = builder.getUIntNTy(size * 8);
1819 Address addr = builder.createElementBitCast(loc, ptrAddr, intTy);
1820 mlir::Value val = builder.createLoad(loc, addr);
1821 mlir::Value swapped = cir::ByteSwapOp::create(builder, loc, val);
1822 builder.createStore(loc, swapped, addr);
1823 return RValue::get(nullptr);
1824 }
1825 }
1826 // General case: fall back to the library function stdc_memreverse8.
1827 break;
1828 }
1829
1830 case Builtin::BI__builtin_constant_p: {
1831 mlir::Type resultType = convertType(e->getType());
1832
1833 const Expr *arg = e->getArg(0);
1834 QualType argType = arg->getType();
1835 // FIXME: The allowance for Obj-C pointers and block pointers is historical
1836 // and likely a mistake.
1837 if (!argType->isIntegralOrEnumerationType() && !argType->isFloatingType() &&
1838 !argType->isObjCObjectPointerType() && !argType->isBlockPointerType()) {
1839 // Per the GCC documentation, only numeric constants are recognized after
1840 // inlining.
1841 return RValue::get(
1842 builder.getConstInt(getLoc(e->getSourceRange()),
1843 mlir::cast<cir::IntType>(resultType), 0));
1844 }
1845
1846 if (arg->HasSideEffects(getContext())) {
1847 // The argument is unevaluated, so be conservative if it might have
1848 // side-effects.
1849 return RValue::get(
1850 builder.getConstInt(getLoc(e->getSourceRange()),
1851 mlir::cast<cir::IntType>(resultType), 0));
1852 }
1853
1854 mlir::Value argValue = emitScalarExpr(arg);
1855 if (argType->isObjCObjectPointerType()) {
1856 cgm.errorNYI(e->getSourceRange(),
1857 "__builtin_constant_p: Obj-C object pointer");
1858 return {};
1859 }
1860 argValue = builder.createBitcast(argValue, convertType(argType));
1861
1862 mlir::Value result = cir::IsConstantOp::create(
1863 builder, getLoc(e->getSourceRange()), argValue);
1864 // IsConstantOp returns a bool, but __builtin_constant_p returns an int.
1865 result = builder.createBoolToInt(result, resultType);
1866 return RValue::get(result);
1867 }
1868 case Builtin::BI__builtin_dynamic_object_size:
1869 case Builtin::BI__builtin_object_size: {
1870 unsigned type =
1871 e->getArg(1)->EvaluateKnownConstInt(getContext()).getZExtValue();
1872 auto resType = mlir::cast<cir::IntType>(convertType(e->getType()));
1873
1874 // We pass this builtin onto the optimizer so that it can figure out the
1875 // object size in more complex cases.
1876 bool isDynamic = builtinID == Builtin::BI__builtin_dynamic_object_size;
1877 return RValue::get(emitBuiltinObjectSize(e->getArg(0), type, resType,
1878 /*EmittedE=*/nullptr, isDynamic));
1879 }
1880
1881 case Builtin::BI__builtin_prefetch: {
1882 auto evaluateOperandAsInt = [&](const Expr *arg) {
1883 Expr::EvalResult res;
1884 [[maybe_unused]] bool evalSucceed =
1885 arg->EvaluateAsInt(res, cgm.getASTContext());
1886 assert(evalSucceed && "expression should be able to evaluate as int");
1887 return res.Val.getInt().getZExtValue();
1888 };
1889
1890 bool isWrite = false;
1891 if (e->getNumArgs() > 1)
1892 isWrite = evaluateOperandAsInt(e->getArg(1));
1893
1894 int locality = 3;
1895 if (e->getNumArgs() > 2)
1896 locality = evaluateOperandAsInt(e->getArg(2));
1897
1898 mlir::Value address = emitScalarExpr(e->getArg(0));
1899 cir::PrefetchOp::create(builder, loc, address, locality, isWrite);
1900 return RValue::get(nullptr);
1901 }
1902 case Builtin::BI__builtin_readcyclecounter:
1903 return RValue::get(builder.emitIntrinsicCallOp(
1904 getLoc(e->getExprLoc()), "readcyclecounter", builder.getUInt64Ty()));
1905 case Builtin::BI__builtin_readsteadycounter:
1906 return RValue::get(builder.emitIntrinsicCallOp(
1907 getLoc(e->getExprLoc()), "readsteadycounter", builder.getUInt64Ty()));
1908 case Builtin::BI__builtin___clear_cache: {
1909 mlir::Value begin =
1910 builder.createPtrBitcast(emitScalarExpr(e->getArg(0)), cgm.voidTy);
1911 mlir::Value end =
1912 builder.createPtrBitcast(emitScalarExpr(e->getArg(1)), cgm.voidTy);
1913 cir::ClearCacheOp::create(builder, getLoc(e->getSourceRange()), begin, end);
1914 return RValue::get(nullptr);
1915 }
1916 case Builtin::BI__builtin_trap:
1917 emitTrap(loc, /*createNewBlock=*/true);
1918 return RValue::getIgnored();
1919 case Builtin::BI__builtin_verbose_trap:
1921 emitTrap(loc, /*createNewBlock=*/true);
1922 return RValue::getIgnored();
1923 case Builtin::BI__debugbreak:
1924 return errorBuiltinNYI(*this, e, builtinID);
1925 case Builtin::BI__builtin_unreachable:
1926 emitUnreachable(e->getExprLoc(), /*createNewBlock=*/true);
1927 return RValue::getIgnored();
1928 case Builtin::BI__builtin_powi:
1929 case Builtin::BI__builtin_powif:
1930 case Builtin::BI__builtin_powil: {
1931 mlir::Value src0 = emitScalarExpr(e->getArg(0));
1932 mlir::Value src1 = emitScalarExpr(e->getArg(1));
1933 return RValue::get(builder.emitIntrinsicCallOp(
1934 getLoc(e->getExprLoc()), "powi", src0.getType(),
1935 mlir::ValueRange{src0, src1}));
1936 }
1937 case Builtin::BI__builtin_frexpl:
1938 case Builtin::BI__builtin_frexp:
1939 case Builtin::BI__builtin_frexpf:
1940 case Builtin::BI__builtin_frexpf128:
1941 case Builtin::BI__builtin_frexpf16: {
1942 mlir::Value val = emitScalarExpr(e->getArg(0));
1943 mlir::Value ptr = emitScalarExpr(e->getArg(1));
1944 mlir::Type fpTy = val.getType();
1945 QualType intQualTy = e->getArg(1)->getType()->getPointeeType();
1946 mlir::Type intTy = convertType(intQualTy);
1947 mlir::Location callLoc = getLoc(e->getExprLoc());
1948 auto frexpOp = cir::FrexpOp::create(builder, callLoc, fpTy, intTy, val);
1949 LValue lv = makeNaturalAlignAddrLValue(ptr, intQualTy);
1950 emitStoreOfScalar(frexpOp.getExp(), lv, /*isInit=*/false);
1951 return RValue::get(frexpOp.getResult());
1952 }
1953 case Builtin::BImodf:
1954 case Builtin::BImodff:
1955 case Builtin::BImodfl:
1956 case Builtin::BI__builtin_modf:
1957 case Builtin::BI__builtin_modff:
1958 case Builtin::BI__builtin_modfl: {
1959 mlir::Value val = emitScalarExpr(e->getArg(0));
1960 mlir::Value ptr = emitScalarExpr(e->getArg(1));
1961 mlir::Type fpTy = val.getType();
1962 mlir::Location callLoc = getLoc(e->getExprLoc());
1963 auto modfOp = cir::ModfOp::create(builder, callLoc, fpTy, fpTy, val);
1964 QualType destPtrTy = e->getArg(1)->getType()->getPointeeType();
1965 LValue lv = makeNaturalAlignAddrLValue(ptr, destPtrTy);
1966 emitStoreOfScalar(modfOp.getIntegral(), lv, /*isInit=*/false);
1967 return RValue::get(modfOp.getFractional());
1968 }
1969 case Builtin::BI__builtin_isgreater:
1970 case Builtin::BI__builtin_isgreaterequal:
1971 case Builtin::BI__builtin_isless:
1972 case Builtin::BI__builtin_islessequal:
1973 case Builtin::BI__builtin_islessgreater:
1974 case Builtin::BI__builtin_isunordered: {
1975 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(*this, e);
1976 mlir::Value lhs = emitScalarExpr(e->getArg(0));
1977 mlir::Value rhs = emitScalarExpr(e->getArg(1));
1978 mlir::Location loc = getLoc(e->getBeginLoc());
1979 mlir::Type intTy = convertType(e->getType());
1980
1981 mlir::Value cmpResult;
1982 switch (builtinID) {
1983 case Builtin::BI__builtin_isgreater:
1984 cmpResult = builder.createFCompare(loc, cir::FCmpOpKind::ogt, lhs, rhs);
1985 break;
1986 case Builtin::BI__builtin_isgreaterequal:
1987 cmpResult = builder.createFCompare(loc, cir::FCmpOpKind::oge, lhs, rhs);
1988 break;
1989 case Builtin::BI__builtin_isless:
1990 cmpResult = builder.createFCompare(loc, cir::FCmpOpKind::olt, lhs, rhs);
1991 break;
1992 case Builtin::BI__builtin_islessequal:
1993 cmpResult = builder.createFCompare(loc, cir::FCmpOpKind::ole, lhs, rhs);
1994 break;
1995 case Builtin::BI__builtin_islessgreater:
1996 cmpResult = builder.createFCompare(loc, cir::FCmpOpKind::one, lhs, rhs);
1997 break;
1998 case Builtin::BI__builtin_isunordered:
1999 cmpResult = builder.createFCompare(loc, cir::FCmpOpKind::uno, lhs, rhs);
2000 break;
2001 default:
2002 llvm_unreachable("Unknown ordered comparison");
2003 }
2004 return RValue::get(builder.createBoolToInt(cmpResult, intTy));
2005 }
2006 // From https://clang.llvm.org/docs/LanguageExtensions.html#builtin-isfpclass
2007 //
2008 // The `__builtin_isfpclass()` builtin is a generalization of functions
2009 // isnan, isinf, isfinite and some others defined by the C standard. It tests
2010 // if the floating-point value, specified by the first argument, falls into
2011 // any of data classes, specified by the second argument.
2012 case Builtin::BI__builtin_isnan: {
2013 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(*this, e);
2014 mlir::Value v = emitScalarExpr(e->getArg(0));
2015 mlir::Location loc = getLoc(e->getBeginLoc());
2016 return RValue::get(builder.createBoolToInt(
2017 builder.createIsFPClass(loc, v, cir::FPClassTest::Nan),
2018 convertType(e->getType())));
2019 }
2020
2021 case Builtin::BI__builtin_issignaling: {
2022 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(*this, e);
2023 mlir::Value v = emitScalarExpr(e->getArg(0));
2024 mlir::Location loc = getLoc(e->getBeginLoc());
2025 return RValue::get(builder.createBoolToInt(
2026 builder.createIsFPClass(loc, v, cir::FPClassTest::SignalingNaN),
2027 convertType(e->getType())));
2028 }
2029
2030 case Builtin::BI__builtin_isinf: {
2031 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(*this, e);
2032 mlir::Value v = emitScalarExpr(e->getArg(0));
2033 mlir::Location loc = getLoc(e->getBeginLoc());
2034 return RValue::get(builder.createBoolToInt(
2035 builder.createIsFPClass(loc, v, cir::FPClassTest::Infinity),
2036 convertType(e->getType())));
2037 }
2038 case Builtin::BIfinite:
2039 case Builtin::BI__finite:
2040 case Builtin::BIfinitef:
2041 case Builtin::BI__finitef:
2042 case Builtin::BIfinitel:
2043 case Builtin::BI__finitel:
2044 case Builtin::BI__builtin_isfinite: {
2045 mlir::Value v = emitScalarExpr(e->getArg(0));
2046 mlir::Location loc = getLoc(e->getBeginLoc());
2047 return RValue::get(builder.createBoolToInt(
2048 builder.createIsFPClass(loc, v, cir::FPClassTest::Finite),
2049 convertType(e->getType())));
2050 }
2051
2052 case Builtin::BI__builtin_isnormal: {
2053 mlir::Value v = emitScalarExpr(e->getArg(0));
2054 mlir::Location loc = getLoc(e->getBeginLoc());
2055 return RValue::get(builder.createBoolToInt(
2056 builder.createIsFPClass(loc, v, cir::FPClassTest::Normal),
2057 convertType(e->getType())));
2058 }
2059
2060 case Builtin::BI__builtin_issubnormal: {
2061 mlir::Value v = emitScalarExpr(e->getArg(0));
2062 mlir::Location loc = getLoc(e->getBeginLoc());
2063 return RValue::get(builder.createBoolToInt(
2064 builder.createIsFPClass(loc, v, cir::FPClassTest::Subnormal),
2065 convertType(e->getType())));
2066 }
2067
2068 case Builtin::BI__builtin_iszero: {
2069 mlir::Value v = emitScalarExpr(e->getArg(0));
2070 mlir::Location loc = getLoc(e->getBeginLoc());
2071 return RValue::get(builder.createBoolToInt(
2072 builder.createIsFPClass(loc, v, cir::FPClassTest::Zero),
2073 convertType(e->getType())));
2074 }
2075 case Builtin::BI__builtin_isfpclass: {
2076 Expr::EvalResult result;
2077 if (!e->getArg(1)->EvaluateAsInt(result, cgm.getASTContext()))
2078 break;
2079
2080 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(*this, e);
2081 mlir::Value v = emitScalarExpr(e->getArg(0));
2082 uint64_t test = result.Val.getInt().getLimitedValue();
2083 mlir::Location loc = getLoc(e->getBeginLoc());
2084 return RValue::get(builder.createBoolToInt(
2085 builder.createIsFPClass(loc, v, cir::FPClassTest(test)),
2086 convertType(e->getType())));
2087 }
2088 case Builtin::BI__builtin_nondeterministic_value: {
2089 mlir::Type ty = convertType(e->getArg(0)->getType());
2090 mlir::Value result =
2091 cir::ConstantOp::create(builder, loc, ty, cir::PoisonAttr::get(ty));
2092 result = cir::FreezeOp::create(builder, loc, result);
2093 return RValue::get(result);
2094 }
2095 case Builtin::BI__builtin_elementwise_abs: {
2096 mlir::Type cirTy = convertType(e->getArg(0)->getType());
2097 bool isIntTy = cir::isIntOrVectorOfIntType(cirTy);
2098 if (!isIntTy)
2099 return emitUnaryFPBuiltin<cir::FAbsOp>(*this, *e);
2100 mlir::Value arg = emitScalarExpr(e->getArg(0));
2101 mlir::Value result = cir::AbsOp::create(builder, getLoc(e->getExprLoc()),
2102 arg.getType(), arg, false);
2103 return RValue::get(result);
2104 }
2105 case Builtin::BI__builtin_elementwise_bitreverse:
2106 case Builtin::BI__builtin_elementwise_popcount:
2107 case Builtin::BI__builtin_elementwise_canonicalize:
2108 case Builtin::BI__builtin_elementwise_copysign:
2109 return errorBuiltinNYI(*this, e, builtinID);
2110 case Builtin::BI__builtin_elementwise_fshl:
2112 case Builtin::BI__builtin_elementwise_fshr:
2114 case Builtin::BI__builtin_elementwise_clmul:
2115 case Builtin::BI__builtin_elementwise_pext:
2116 case Builtin::BI__builtin_elementwise_pdep:
2117 return errorBuiltinNYI(*this, e, builtinID);
2118 case Builtin::BI__builtin_elementwise_add_sat:
2119 case Builtin::BI__builtin_elementwise_sub_sat: {
2120 // The saturating ops have no !cir.bool form, and emitScalarExpr on a bool
2121 // vector hits the NYI bool-vector load and returns null, so bail first.
2122 QualType argTy = e->getArg(0)->getType();
2123 if (argTy->isBooleanType() || argTy->isExtVectorBoolType()) {
2124 cgm.errorNYI(e->getSourceRange(),
2125 "saturating add/sub on a boolean operand");
2126 return RValue::get(nullptr);
2127 }
2128 mlir::Location loc = getLoc(e->getExprLoc());
2129 mlir::Value op0 = emitScalarExpr(e->getArg(0));
2130 mlir::Value op1 = emitScalarExpr(e->getArg(1));
2131 assert(cir::isIntOrVectorOfIntType(op0.getType()) &&
2132 "elementwise saturating add/sub requires integer operands");
2133 mlir::Value val =
2134 builtinIDIfNoAsmLabel == Builtin::BI__builtin_elementwise_add_sat
2135 ? builder.createAddSat(loc, op0, op1)
2136 : builder.createSubSat(loc, op0, op1);
2137 return RValue::get(val);
2138 }
2139 case Builtin::BI__builtin_elementwise_max: {
2140 if (cir::isIntOrVectorOfIntType(convertType(e->getArg(0)->getType()))) {
2141 mlir::Location loc = getLoc(e->getExprLoc());
2142 mlir::Value op0 = emitScalarExpr(e->getArg(0));
2143 mlir::Value op1 = emitScalarExpr(e->getArg(1));
2144 return RValue::get(builder.createMax(loc, op0, op1));
2145 }
2146 return RValue::get(
2148 }
2149 case Builtin::BI__builtin_elementwise_min: {
2150 if (cir::isIntOrVectorOfIntType(convertType(e->getArg(0)->getType()))) {
2151 mlir::Location loc = getLoc(e->getExprLoc());
2152 mlir::Value op0 = emitScalarExpr(e->getArg(0));
2153 mlir::Value op1 = emitScalarExpr(e->getArg(1));
2154 return RValue::get(builder.createMin(loc, op0, op1));
2155 }
2156 return RValue::get(
2158 }
2159 case Builtin::BI__builtin_elementwise_maxnum:
2160 return RValue::get(
2162 case Builtin::BI__builtin_elementwise_minnum:
2163 return RValue::get(
2165 case Builtin::BI__builtin_elementwise_maximum:
2166 return RValue::get(
2168 case Builtin::BI__builtin_elementwise_minimum:
2169 return RValue::get(
2171
2172 case Builtin::BI__builtin_elementwise_maximumnum:
2173 case Builtin::BI__builtin_elementwise_minimumnum:
2174 return errorBuiltinNYI(*this, e, builtinID);
2175 case Builtin::BI__builtin_reduce_max:
2176 case Builtin::BI__builtin_reduce_min: {
2177 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(*this, e);
2178 QualType type = e->getArg(0)->getType();
2179 if (const auto *vecTy = type->getAs<VectorType>())
2180 type = vecTy->getElementType();
2181 else if (type->isSizelessVectorType())
2182 type = type->getSizelessVectorEltType(getContext());
2183
2184 mlir::Value input = emitScalarExpr(e->getArg(0));
2185 mlir::Location loc = getLoc(e->getExprLoc());
2186 const bool isMax = builtinIDIfNoAsmLabel == Builtin::BI__builtin_reduce_max;
2187
2188 if (type->isSignedIntegerType()) {
2189 if (isMax)
2190 return RValue::get(
2191 cir::VecReduceSMaxOp::create(builder, loc, input).getResult());
2192 return RValue::get(
2193 cir::VecReduceSMinOp::create(builder, loc, input).getResult());
2194 }
2195
2196 if (type->isUnsignedIntegerType()) {
2197 if (isMax)
2198 return RValue::get(
2199 cir::VecReduceUMaxOp::create(builder, loc, input).getResult());
2200 return RValue::get(
2201 cir::VecReduceUMinOp::create(builder, loc, input).getResult());
2202 }
2203
2204 assert(type->isFloatingType() && "must have a float here");
2205 cir::FastMathFlagsAttr fastMath =
2207 if (isMax)
2208 return RValue::get(
2209 cir::VecReduceFMaxOp::create(builder, loc, input, fastMath)
2210 .getResult());
2211 return RValue::get(
2212 cir::VecReduceFMinOp::create(builder, loc, input, fastMath)
2213 .getResult());
2214 }
2215 case Builtin::BI__builtin_reduce_add:
2217 case Builtin::BI__builtin_reduce_mul:
2219 case Builtin::BI__builtin_reduce_xor:
2221 case Builtin::BI__builtin_reduce_or:
2223 case Builtin::BI__builtin_reduce_and:
2225 case Builtin::BI__builtin_reduce_maximum:
2226 case Builtin::BI__builtin_reduce_minimum:
2227 return errorBuiltinNYI(*this, e, builtinID);
2228 case Builtin::BI__builtin_reduce_assoc_fadd:
2229 case Builtin::BI__builtin_reduce_in_order_fadd: {
2230 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(*this, e);
2231 bool isAssociative =
2232 builtinIDIfNoAsmLabel == Builtin::BI__builtin_reduce_assoc_fadd;
2233
2234 assert((isAssociative ? e->getNumArgs() == 1 || e->getNumArgs() == 2
2235 : e->getNumArgs() == 2) &&
2236 "invalid argument count for floating-point reduction");
2237 mlir::Value vector = emitScalarExpr(e->getArg(0));
2238 auto vectorTy = cast<cir::VectorType>(vector.getType());
2239 mlir::Type scalarTy = vectorTy.getElementType();
2240 mlir::Location loc = getLoc(e->getExprLoc());
2241 mlir::Value startValue;
2242 if (e->getNumArgs() == 2) {
2243 startValue = emitScalarExpr(e->getArg(1));
2244 if (startValue.getType() != scalarTy)
2245 startValue =
2246 builder.createCast(getLoc(e->getArg(1)->getExprLoc()),
2247 cir::CastKind::floating, startValue, scalarTy);
2248 } else {
2249 auto fpTy = cast<cir::FPTypeInterface>(scalarTy);
2250 startValue = cir::ConstantOp::create(
2251 builder, loc,
2252 cir::FPAttr::get(scalarTy,
2253 llvm::APFloat::getZero(fpTy.getFloatSemantics(),
2254 /*Negative=*/true)));
2255 }
2256
2257 cir::FastMathFlags fastMathFlags = getCurrentFastMathFlags();
2258 if (isAssociative)
2259 fastMathFlags |= cir::FastMathFlags::reassoc;
2260 cir::FastMathFlagsAttr fastMath = getFastMathFlagsAttr(fastMathFlags);
2261
2262 auto reduction = cir::VecReduceFAddOp::create(builder, loc, startValue,
2263 vector, fastMath);
2264 return RValue::get(reduction.getResult());
2265 }
2266 case Builtin::BI__builtin_matrix_transpose: {
2267 mlir::Value matrix = emitScalarExpr(e->getArg(0));
2268 mlir::Value result = builder.createMatrixTranspose(loc, matrix);
2269 return RValue::get(result);
2270 }
2271 case Builtin::BI__builtin_matrix_column_major_load: {
2272 // Emit everything that isn't dependent on the first parameter type
2273 mlir::Value stride = emitScalarExpr(e->getArg(3));
2274 const QualType resultTy = e->getType();
2275 mlir::Type resultType = convertType(resultTy);
2276 auto *ptrTy = e->getArg(0)->getType()->getAs<PointerType>();
2277 assert(ptrTy && "arg0 must be of pointer type");
2278 bool isVolatile = ptrTy->getPointeeType().isVolatileQualified();
2281 e->getArg(0)->getType(), e->getArg(0)->getExprLoc(), fd,
2282 0);
2283 mlir::Value dataPtr = src.emitRawPointer();
2284 mlir::Value result = builder.createMatrixColumnMajorLoad(
2285 loc, resultType, dataPtr, stride, isVolatile);
2286 return RValue::get(result);
2287 }
2288 case Builtin::BI__builtin_matrix_column_major_store: {
2289 mlir::Value matrix = emitScalarExpr(e->getArg(0));
2291 mlir::Value stride = emitScalarExpr(e->getArg(2));
2292
2293 auto *ptrTy = e->getArg(1)->getType()->getAs<PointerType>();
2294 assert(ptrTy && "arg1 must be of pointer type");
2295 bool isVolatile = ptrTy->getPointeeType().isVolatileQualified();
2296
2298 e->getArg(1)->getType(), e->getArg(1)->getExprLoc(), fd,
2299 0);
2300 builder.createMatrixColumnMajorStore(loc, matrix, dst.emitRawPointer(),
2301 stride, isVolatile);
2302 return RValue::get(nullptr);
2303 }
2304 case Builtin::BI__builtin_masked_load:
2305 case Builtin::BI__builtin_masked_expand_load:
2306 case Builtin::BI__builtin_masked_gather:
2307 case Builtin::BI__builtin_masked_store:
2308 case Builtin::BI__builtin_masked_compress_store:
2309 case Builtin::BI__builtin_masked_scatter:
2310 return errorBuiltinNYI(*this, e, builtinID);
2311 case Builtin::BI__builtin_isinf_sign: {
2312 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(*this, e);
2313 mlir::Location loc = getLoc(e->getBeginLoc());
2314 mlir::Value arg = emitScalarExpr(e->getArg(0));
2315 mlir::Value isInf =
2316 builder.createIsFPClass(loc, arg, cir::FPClassTest::Infinity);
2317 mlir::Value isNeg = emitSignBit(loc, *this, arg);
2318 mlir::Type intTy = convertType(e->getType());
2319 cir::ConstantOp zero = builder.getNullValue(intTy, loc);
2320 cir::ConstantOp one = builder.getConstant(loc, cir::IntAttr::get(intTy, 1));
2321 cir::ConstantOp negativeOne =
2322 builder.getConstant(loc, cir::IntAttr::get(intTy, -1));
2323 mlir::Value signResult = builder.createSelect(loc, isNeg, negativeOne, one);
2324 mlir::Value result = builder.createSelect(loc, isInf, signResult, zero);
2325 return RValue::get(result);
2326 }
2327 case Builtin::BI__builtin_flt_rounds: {
2328 mlir::Location loc = getLoc(e->getExprLoc());
2329 mlir::Type resultType = convertType(e->getType());
2330 mlir::Value result =
2331 builder.emitIntrinsicCallOp(loc, "get.rounding", resultType);
2332 if (result.getType() != resultType)
2333 result =
2334 builder.createCast(loc, cir::CastKind::integral, result, resultType);
2335 return RValue::get(result);
2336 }
2337 case Builtin::BI__builtin_set_flt_rounds: {
2338 mlir::Location loc = getLoc(e->getExprLoc());
2339 mlir::Value v = emitScalarExpr(e->getArg(0));
2340 builder.emitIntrinsicCallOp(loc, "set.rounding", builder.getVoidTy(),
2341 mlir::ValueRange{v});
2342 return RValue::get(nullptr);
2343 }
2344 case Builtin::BI__builtin_fpclassify: {
2345 CIRGenFunction::CIRGenFPOptionsRAII fPOptsRAII(*this, e);
2346 mlir::Location loc = getLoc(e->getBeginLoc());
2347 mlir::Value value = emitScalarExpr(e->getArg(5));
2348 mlir::Type resultTy = convertType(e->getType());
2349 // if isZero then
2350 // result = FP_ZERO
2351 // elseif isNan then
2352 // result = FP_NAN
2353 // elseif isInfinity then
2354 // result = FP_INFINITE
2355 // elseif isNormal then
2356 // result = FP_NORMAL
2357 // else
2358 // result = FP_SUBNORMAL
2359 auto isZero =
2360 cir::IsFPClassOp::create(builder, loc, value, cir::FPClassTest::Zero);
2361 mlir::Value result =
2362 cir::TernaryOp::create(
2363 builder, loc, isZero,
2364 /*thenBuilder=*/
2365 [&](mlir::OpBuilder &opBuilder, mlir::Location location) {
2366 mlir::Value zeroLiteral = emitScalarExpr(e->getArg(4));
2367 cir::YieldOp::create(opBuilder, location, zeroLiteral);
2368 },
2369 /*elseBuilder=*/
2370 [&](mlir::OpBuilder &opBuilder, mlir::Location location) {
2371 auto isNan = cir::IsFPClassOp::create(opBuilder, location, value,
2372 cir::FPClassTest::Nan);
2373 mlir::Value nanResult =
2374 cir::TernaryOp::create(
2375 opBuilder, location, isNan,
2376 /*thenBuilder=*/
2377 [&](mlir::OpBuilder &opBuilder, mlir::Location location) {
2378 mlir::Value nanLiteral = emitScalarExpr(e->getArg(0));
2379 cir::YieldOp::create(opBuilder, location, nanLiteral);
2380 },
2381 /*elseBuilder=*/
2382 [&](mlir::OpBuilder &opBuilder, mlir::Location location) {
2383 auto isInfinity = cir::IsFPClassOp::create(
2384 opBuilder, location, value,
2385 cir::FPClassTest::Infinity);
2386 mlir::Value infResult =
2387 cir::TernaryOp::create(
2388 opBuilder, location, isInfinity,
2389 /*thenBuilder=*/
2390 [&](mlir::OpBuilder &opBuilder,
2391 mlir::Location location) {
2392 mlir::Value infinityLiteral =
2393 emitScalarExpr(e->getArg(1));
2394 cir::YieldOp::create(opBuilder, location,
2395 infinityLiteral);
2396 },
2397 /*elseBuilder=*/
2398 [&](mlir::OpBuilder &opBuilder,
2399 mlir::Location location) {
2400 auto isNormal = cir::IsFPClassOp::create(
2401 opBuilder, location, value,
2402 cir::FPClassTest::Normal);
2403 mlir::Value fpNormal =
2404 emitScalarExpr(e->getArg(2));
2405 mlir::Value fpSubnormal =
2406 emitScalarExpr(e->getArg(3));
2407 mlir::Value returnValue =
2408 cir::SelectOp::create(
2409 opBuilder, location, resultTy,
2410 isNormal, fpNormal, fpSubnormal);
2411 cir::YieldOp::create(opBuilder, location,
2412 returnValue);
2413 })
2414 .getResult();
2415 cir::YieldOp::create(opBuilder, location, infResult);
2416 })
2417 .getResult();
2418 cir::YieldOp::create(opBuilder, location, nanResult);
2419 })
2420 .getResult();
2421 return RValue::get(result);
2422 }
2423 case Builtin::BIalloca:
2424 case Builtin::BI_alloca:
2425 case Builtin::BI__builtin_alloca_uninitialized:
2426 case Builtin::BI__builtin_alloca:
2427 return emitBuiltinAlloca(*this, e, builtinID);
2428 case Builtin::BI__builtin_alloca_with_align_uninitialized:
2429 case Builtin::BI__builtin_alloca_with_align:
2430 case Builtin::BI__builtin_infer_alloc_token:
2431 return errorBuiltinNYI(*this, e, builtinID);
2432 case Builtin::BIbzero:
2433 case Builtin::BI__builtin_bzero: {
2434 mlir::Location loc = getLoc(e->getSourceRange());
2435 Address destPtr = emitPointerWithAlignment(e->getArg(0));
2436 Address destPtrCast = destPtr.withElementType(builder, cgm.voidTy);
2437 mlir::Value size = emitScalarExpr(e->getArg(1));
2438 mlir::Value zero = builder.getNullValue(builder.getUInt8Ty(), loc);
2440 builder.createMemSet(loc, destPtrCast, zero, size);
2442 return RValue::getIgnored();
2443 }
2444 case Builtin::BIbcopy:
2445 case Builtin::BI__builtin_bcopy: {
2448 mlir::Value sizeVal = emitScalarExpr(e->getArg(2));
2450 e->getArg(0)->getExprLoc(), fd, 0);
2452 e->getArg(1)->getExprLoc(), fd, 0);
2453 builder.createMemMove(getLoc(e->getSourceRange()), dest, src, sizeVal);
2454 return RValue::get(nullptr);
2455 }
2456 case Builtin::BImemcpy:
2457 case Builtin::BI__builtin_memcpy:
2458 case Builtin::BImempcpy:
2459 case Builtin::BI__builtin_mempcpy: {
2460 mlir::Location loc = getLoc(e->getSourceRange());
2463 mlir::Value sizeVal = emitScalarExpr(e->getArg(2));
2464 Address destCast = dest.withElementType(builder, cgm.voidTy);
2465 Address srcCast = src.withElementType(builder, cgm.voidTy);
2467 builder.createMemCpy(loc, destCast, srcCast, sizeVal);
2469 if (builtinID == Builtin::BImempcpy ||
2470 builtinID == Builtin::BI__builtin_mempcpy) {
2471 mlir::Value destPtr = destCast.getPointer();
2472 mlir::Value end = builder.createPtrStride(loc, destPtr, sizeVal);
2473 return RValue::get(end);
2474 }
2475 return RValue::get(dest.getPointer());
2476 }
2477 case Builtin::BI__builtin_memcpy_inline:
2478 break; // Handled as library calls below.
2479 case Builtin::BI__builtin_char_memchr:
2480 case Builtin::BI__builtin_memchr: {
2481 Address srcPtr = emitPointerWithAlignment(e->getArg(0));
2482 mlir::Value src =
2483 builder.createBitcast(srcPtr.getPointer(), builder.getVoidPtrTy());
2484 mlir::Value pattern = emitScalarExpr(e->getArg(1));
2485 mlir::Value len = emitScalarExpr(e->getArg(2));
2486 mlir::Value res = cir::MemChrOp::create(builder, getLoc(e->getExprLoc()),
2487 src, pattern, len);
2488 // builtin_char_memchr needs its type converted to 'char', but MemChrOp is a
2489 // 'void' result type.
2490 res = builder.createBitcast(res, convertType(e->getType()));
2491 return RValue::get(res);
2492 }
2493 case Builtin::BI__builtin___memcpy_chk:
2494 case Builtin::BI__builtin_objc_memmove_collectable:
2495 case Builtin::BI__builtin___memmove_chk:
2496 break; // Handled as library calls below.
2497 case Builtin::BI__builtin_trivially_relocate:
2498 case Builtin::BImemmove:
2499 case Builtin::BI__builtin_memmove: {
2500 mlir::Location loc = getLoc(e->getSourceRange());
2503 mlir::Value sizeVal = emitScalarExpr(e->getArg(2));
2504 if (builtinIDIfNoAsmLabel == Builtin::BI__builtin_trivially_relocate) {
2505 QualType eltTy = e->getArg(0)->getType()->getPointeeType();
2506 CharUnits eltSize = getContext().getTypeSizeInChars(eltTy);
2507 mlir::Value eltSizeVal =
2508 builder.getConstInt(loc, sizeVal.getType(), eltSize.getQuantity());
2509 sizeVal = builder.createMul(loc, sizeVal, eltSizeVal);
2510 }
2512 e->getArg(0)->getExprLoc(), fd, 0);
2514 e->getArg(1)->getExprLoc(), fd, 1);
2516 Address destCast = dest.withElementType(builder, cgm.voidTy);
2517 Address srcCast = src.withElementType(builder, cgm.voidTy);
2518 builder.createMemMove(loc, destCast, srcCast, sizeVal);
2520 return RValue::get(dest.getPointer());
2521 }
2522 case Builtin::BImemset:
2523 case Builtin::BI__builtin_memset: {
2525 mlir::Value byteVal = builder.createIntCast(emitScalarExpr(e->getArg(1)),
2526 builder.getUInt8Ty());
2527 mlir::Value sizeVal = emitScalarExpr(e->getArg(2));
2529 e->getArg(0)->getExprLoc(), fd, 0);
2530 builder.createMemSet(getLoc(e->getSourceRange()), dest, byteVal, sizeVal);
2532 return RValue::get(dest.getPointer());
2533 }
2534 case Builtin::BI__builtin_memset_inline:
2535 case Builtin::BI__builtin___memset_chk:
2536 case Builtin::BI__builtin_wmemchr:
2537 case Builtin::BI__builtin_wmemcmp:
2538 break; // Handled as library calls below.
2539 case Builtin::BI__builtin_dwarf_cfa:
2540 return errorBuiltinNYI(*this, e, builtinID);
2541 case Builtin::BI__builtin_return_address: {
2542 llvm::APSInt level = e->getArg(0)->EvaluateKnownConstInt(getContext());
2543 return RValue::get(cir::ReturnAddrOp::create(
2544 builder, getLoc(e->getExprLoc()),
2545 builder.getConstAPInt(loc, builder.getUInt32Ty(), level)));
2546 }
2547 case Builtin::BI_ReturnAddress: {
2548 return RValue::get(cir::ReturnAddrOp::create(
2549 builder, getLoc(e->getExprLoc()),
2550 builder.getConstInt(loc, builder.getUInt32Ty(), 0)));
2551 }
2552 case Builtin::BI__builtin_frame_address: {
2553 llvm::APSInt level = e->getArg(0)->EvaluateKnownConstInt(getContext());
2554 mlir::Location loc = getLoc(e->getExprLoc());
2555 mlir::Value addr = cir::FrameAddrOp::create(
2556 builder, loc, allocaInt8PtrTy,
2557 builder.getConstAPInt(loc, builder.getUInt32Ty(), level));
2558 addr = builder.createBitcast(
2559 addr, builder.getVoidPtrTy(getCIRAllocaAddressSpace()));
2561 }
2562 case Builtin::BI__builtin_extract_return_addr:
2563 case Builtin::BI__builtin_frob_return_addr:
2564 case Builtin::BI__builtin_dwarf_sp_column:
2565 case Builtin::BI__builtin_init_dwarf_reg_size_table:
2566 case Builtin::BI__builtin_eh_return:
2567 case Builtin::BI__builtin_unwind_init:
2568 case Builtin::BI__builtin_extend_pointer:
2569 return errorBuiltinNYI(*this, e, builtinID);
2570 case Builtin::BI__builtin_setjmp: {
2572 mlir::Location loc = getLoc(e->getExprLoc());
2573
2574 cir::PointerType voidPtrTy = builder.getVoidPtrTy();
2575 cir::PointerType ppTy = builder.getPointerTo(voidPtrTy);
2576 Address castBuf = buf.withElementType(builder, voidPtrTy);
2577
2579 if (getTarget().getTriple().isSystemZ()) {
2580 cgm.errorNYI(e->getExprLoc(), "setjmp on SystemZ");
2581 return {};
2582 }
2583
2584 mlir::Value frameAddress =
2585 cir::FrameAddrOp::create(builder, loc, voidPtrTy,
2586 mlir::ValueRange{builder.getUInt32(0, loc)})
2587 .getResult();
2588
2589 builder.createStore(loc, frameAddress, castBuf);
2590
2591 mlir::Value stacksave =
2592 cir::StackSaveOp::create(builder, loc, voidPtrTy).getResult();
2593 cir::PtrStrideOp stackSaveSlot = cir::PtrStrideOp::create(
2594 builder, loc, ppTy, castBuf.getPointer(), builder.getSInt32(2, loc));
2595 llvm::TypeSize voidPtrTySize =
2596 cgm.getDataLayout().getTypeAllocSize(voidPtrTy);
2597 CharUnits slotAlign = castBuf.getAlignment().alignmentAtOffset(
2598 CharUnits().fromQuantity(2 * voidPtrTySize));
2599 Address slotAddr = Address(stackSaveSlot, voidPtrTy, slotAlign);
2600 builder.createStore(loc, stacksave, slotAddr);
2601 auto op = cir::EhSetjmpOp::create(builder, loc, castBuf.getPointer());
2602 return RValue::get(op);
2603 }
2604 case Builtin::BI__builtin_longjmp: {
2605 mlir::Value buf = emitScalarExpr(e->getArg(0));
2606 mlir::Location loc = getLoc(e->getExprLoc());
2607
2608 cir::EhLongjmpOp::create(builder, loc, buf);
2609 cir::UnreachableOp::create(builder, loc);
2610 return RValue::get(nullptr);
2611 }
2612 case Builtin::BI__builtin_launder: {
2613 const Expr *arg = e->getArg(0);
2614 QualType argTy = arg->getType()->getPointeeType();
2615 mlir::Value ptr = emitScalarExpr(arg);
2616
2617 if (cgm.getCodeGenOpts().StrictVTablePointers &&
2618 argTy.requiresBuiltinLaunder(cgm.getASTContext())) {
2619 mlir::Location loc = getLoc(e->getExprLoc());
2620 ptr = cir::LaunderOp::create(builder, loc, ptr).getResult();
2621 }
2622 return RValue::get(ptr);
2623 }
2624 case Builtin::BI__builtin_clear_padding: {
2626 mlir::Location loc = getLoc(e->getExprLoc());
2627 QualType pointeeTy = e->getArg(0)->getType()->getPointeeType();
2628
2630 cgm.getASTContext().getPaddingIntervals(pointeeTy);
2631
2633 for (const auto &interval : padding)
2634 paddingLocs.push_back(cir::OffsetPairAttr::get(
2635 &getMLIRContext(), interval.First, interval.Last));
2636
2637 cir::ClearPaddingOp::create(
2638 builder, loc, addr.getPointer(),
2639 builder.getI64IntegerAttr(addr.getAlignment().getQuantity()),
2640 mlir::ArrayAttr::get(&getMLIRContext(), paddingLocs));
2641 return RValue::get(nullptr);
2642 }
2643 case Builtin::BI__sync_fetch_and_add:
2644 case Builtin::BI__sync_fetch_and_sub:
2645 case Builtin::BI__sync_fetch_and_or:
2646 case Builtin::BI__sync_fetch_and_and:
2647 case Builtin::BI__sync_fetch_and_xor:
2648 case Builtin::BI__sync_fetch_and_nand:
2649 case Builtin::BI__sync_add_and_fetch:
2650 case Builtin::BI__sync_sub_and_fetch:
2651 case Builtin::BI__sync_and_and_fetch:
2652 case Builtin::BI__sync_or_and_fetch:
2653 case Builtin::BI__sync_xor_and_fetch:
2654 case Builtin::BI__sync_nand_and_fetch:
2655 case Builtin::BI__sync_val_compare_and_swap:
2656 case Builtin::BI__sync_bool_compare_and_swap:
2657 case Builtin::BI__sync_lock_test_and_set:
2658 case Builtin::BI__sync_lock_release:
2659 case Builtin::BI__sync_swap:
2660 llvm_unreachable("Shouldn't make it through sema");
2661 case Builtin::BI__sync_fetch_and_add_1:
2662 case Builtin::BI__sync_fetch_and_add_2:
2663 case Builtin::BI__sync_fetch_and_add_4:
2664 case Builtin::BI__sync_fetch_and_add_8:
2665 case Builtin::BI__sync_fetch_and_add_16:
2666 return emitBinaryAtomic(*this, cir::AtomicFetchKind::Add, e);
2667 case Builtin::BI__sync_fetch_and_sub_1:
2668 case Builtin::BI__sync_fetch_and_sub_2:
2669 case Builtin::BI__sync_fetch_and_sub_4:
2670 case Builtin::BI__sync_fetch_and_sub_8:
2671 case Builtin::BI__sync_fetch_and_sub_16:
2672 return emitBinaryAtomic(*this, cir::AtomicFetchKind::Sub, e);
2673 case Builtin::BI__sync_fetch_and_or_1:
2674 case Builtin::BI__sync_fetch_and_or_2:
2675 case Builtin::BI__sync_fetch_and_or_4:
2676 case Builtin::BI__sync_fetch_and_or_8:
2677 case Builtin::BI__sync_fetch_and_or_16:
2678 return emitBinaryAtomic(*this, cir::AtomicFetchKind::Or, e);
2679 case Builtin::BI__sync_fetch_and_and_1:
2680 case Builtin::BI__sync_fetch_and_and_2:
2681 case Builtin::BI__sync_fetch_and_and_4:
2682 case Builtin::BI__sync_fetch_and_and_8:
2683 case Builtin::BI__sync_fetch_and_and_16:
2684 return emitBinaryAtomic(*this, cir::AtomicFetchKind::And, e);
2685 case Builtin::BI__sync_fetch_and_xor_1:
2686 case Builtin::BI__sync_fetch_and_xor_2:
2687 case Builtin::BI__sync_fetch_and_xor_4:
2688 case Builtin::BI__sync_fetch_and_xor_8:
2689 case Builtin::BI__sync_fetch_and_xor_16:
2690 return emitBinaryAtomic(*this, cir::AtomicFetchKind::Xor, e);
2691 case Builtin::BI__sync_fetch_and_nand_1:
2692 case Builtin::BI__sync_fetch_and_nand_2:
2693 case Builtin::BI__sync_fetch_and_nand_4:
2694 case Builtin::BI__sync_fetch_and_nand_8:
2695 case Builtin::BI__sync_fetch_and_nand_16:
2696 return emitBinaryAtomic(*this, cir::AtomicFetchKind::Nand, e);
2697 case Builtin::BI__sync_fetch_and_min:
2698 case Builtin::BI__sync_fetch_and_max:
2699 case Builtin::BI__sync_fetch_and_umin:
2700 case Builtin::BI__sync_fetch_and_umax:
2701 return errorBuiltinNYI(*this, e, builtinID);
2702 return getUndefRValue(e->getType());
2703 case Builtin::BI__sync_add_and_fetch_1:
2704 case Builtin::BI__sync_add_and_fetch_2:
2705 case Builtin::BI__sync_add_and_fetch_4:
2706 case Builtin::BI__sync_add_and_fetch_8:
2707 case Builtin::BI__sync_add_and_fetch_16:
2708 return emitBinaryAtomicPost<cir::AddOp>(*this, cir::AtomicFetchKind::Add,
2709 e);
2710 case Builtin::BI__sync_sub_and_fetch_1:
2711 case Builtin::BI__sync_sub_and_fetch_2:
2712 case Builtin::BI__sync_sub_and_fetch_4:
2713 case Builtin::BI__sync_sub_and_fetch_8:
2714 case Builtin::BI__sync_sub_and_fetch_16:
2715 return emitBinaryAtomicPost<cir::SubOp>(*this, cir::AtomicFetchKind::Sub,
2716 e);
2717 case Builtin::BI__sync_and_and_fetch_1:
2718 case Builtin::BI__sync_and_and_fetch_2:
2719 case Builtin::BI__sync_and_and_fetch_4:
2720 case Builtin::BI__sync_and_and_fetch_8:
2721 case Builtin::BI__sync_and_and_fetch_16:
2722 return emitBinaryAtomicPost<cir::AndOp>(*this, cir::AtomicFetchKind::And,
2723 e);
2724 case Builtin::BI__sync_or_and_fetch_1:
2725 case Builtin::BI__sync_or_and_fetch_2:
2726 case Builtin::BI__sync_or_and_fetch_4:
2727 case Builtin::BI__sync_or_and_fetch_8:
2728 case Builtin::BI__sync_or_and_fetch_16:
2729 return emitBinaryAtomicPost<cir::OrOp>(*this, cir::AtomicFetchKind::Or, e);
2730 case Builtin::BI__sync_xor_and_fetch_1:
2731 case Builtin::BI__sync_xor_and_fetch_2:
2732 case Builtin::BI__sync_xor_and_fetch_4:
2733 case Builtin::BI__sync_xor_and_fetch_8:
2734 case Builtin::BI__sync_xor_and_fetch_16:
2735 return emitBinaryAtomicPost<cir::XorOp>(*this, cir::AtomicFetchKind::Xor,
2736 e);
2737 case Builtin::BI__sync_nand_and_fetch_1:
2738 case Builtin::BI__sync_nand_and_fetch_2:
2739 case Builtin::BI__sync_nand_and_fetch_4:
2740 case Builtin::BI__sync_nand_and_fetch_8:
2741 case Builtin::BI__sync_nand_and_fetch_16:
2742 return emitBinaryAtomicPost<cir::AndOp>(*this, cir::AtomicFetchKind::Nand,
2743 e, /*invert=*/true);
2744 case Builtin::BI__sync_val_compare_and_swap_1:
2745 case Builtin::BI__sync_val_compare_and_swap_2:
2746 case Builtin::BI__sync_val_compare_and_swap_4:
2747 case Builtin::BI__sync_val_compare_and_swap_8:
2748 return RValue::get(emitAtomicCmpXchg(e, /*returnBool=*/false));
2749 case Builtin::BI__sync_val_compare_and_swap_16:
2750 return errorBuiltinNYI(*this, e, builtinID);
2751 case Builtin::BI__sync_bool_compare_and_swap_1:
2752 case Builtin::BI__sync_bool_compare_and_swap_2:
2753 case Builtin::BI__sync_bool_compare_and_swap_4:
2754 case Builtin::BI__sync_bool_compare_and_swap_8:
2755 return RValue::get(emitAtomicCmpXchg(e, /*returnBool=*/true));
2756 case Builtin::BI__sync_bool_compare_and_swap_16:
2757 return errorBuiltinNYI(*this, e, builtinID);
2758 case Builtin::BI__sync_swap_1:
2759 case Builtin::BI__sync_swap_2:
2760 case Builtin::BI__sync_swap_4:
2761 case Builtin::BI__sync_swap_8:
2762 return emitAtomicXchg(*this, e, cir::MemOrder::SequentiallyConsistent);
2763 case Builtin::BI__sync_swap_16:
2764 return errorBuiltinNYI(*this, e, builtinID);
2765 case Builtin::BI__sync_lock_test_and_set_1:
2766 case Builtin::BI__sync_lock_test_and_set_2:
2767 case Builtin::BI__sync_lock_test_and_set_4:
2768 case Builtin::BI__sync_lock_test_and_set_8:
2769 return emitAtomicXchg(*this, e, cir::MemOrder::SequentiallyConsistent);
2770 case Builtin::BI__sync_lock_test_and_set_16:
2771 return errorBuiltinNYI(*this, e, builtinID);
2772 case Builtin::BI__sync_lock_release_1:
2773 case Builtin::BI__sync_lock_release_2:
2774 case Builtin::BI__sync_lock_release_4:
2775 case Builtin::BI__sync_lock_release_8:
2776 emitAtomicLockRelease(*this, e);
2777 return RValue::get(nullptr);
2778 case Builtin::BI__sync_lock_release_16:
2779 return errorBuiltinNYI(*this, e, builtinID);
2780 case Builtin::BI__sync_synchronize: {
2781 // We assume this is supposed to correspond to a C++0x-style
2782 // sequentially-consistent fence (i.e. this is only usable for
2783 // synchronization, not device I/O or anything like that). This intrinsic
2784 // is really badly designed in the sense that in theory, there isn't
2785 // any way to safely use it... but in practice, it mostly works
2786 // to use it with non-atomic loads and stores to get acquire/release
2787 // semantics.
2788 cir::AtomicFenceOp::create(
2789 builder, getLoc(e->getSourceRange()),
2790 cir::MemOrder::SequentiallyConsistent,
2791 cir::SyncScopeKindAttr::get(&getMLIRContext(),
2792 cir::SyncScopeKind::System));
2793 return RValue::get(nullptr);
2794 }
2795 case Builtin::BI__builtin_nontemporal_load: {
2797 LValue lv = makeAddrLValue(addr, e->getType(),
2799 lv.setNontemporal(true);
2800 mlir::Value val = emitLoadOfScalar(lv, e->getExprLoc());
2801 return RValue::get(val);
2802 }
2803 case Builtin::BI__builtin_nontemporal_store: {
2804 mlir::Value val = emitScalarExpr(e->getArg(0));
2806 val = emitToMemory(val, e->getArg(0)->getType());
2807 LValue lv = makeAddrLValue(addr, e->getArg(0)->getType(),
2809 lv.setNontemporal(true);
2810 emitStoreOfScalar(val, lv, /*isInit=*/false);
2811 return RValue::get(nullptr);
2812 }
2813 case Builtin::BI__c11_atomic_is_lock_free:
2814 case Builtin::BI__atomic_is_lock_free:
2815 return emitAtomicIsLockFree(*this, e, builtinID);
2816 case Builtin::BI__atomic_test_and_set:
2817 case Builtin::BI__atomic_clear:
2818 return errorBuiltinNYI(*this, e, builtinID);
2819 case Builtin::BI__atomic_thread_fence:
2820 case Builtin::BI__atomic_signal_fence:
2821 case Builtin::BI__c11_atomic_thread_fence:
2822 case Builtin::BI__c11_atomic_signal_fence: {
2823 cir::SyncScopeKind syncScope =
2824 builtinID == Builtin::BI__atomic_signal_fence ||
2825 builtinID == Builtin::BI__c11_atomic_signal_fence
2826 ? cir::SyncScopeKind::SingleThread
2827 : cir::SyncScopeKind::System;
2828 emitAtomicFenceOp(*this, e, syncScope);
2829 return RValue::get(nullptr);
2830 }
2831 case Builtin::BI__scoped_atomic_thread_fence:
2832 return errorBuiltinNYI(*this, e, builtinID);
2833 case Builtin::BI__builtin_signbit:
2834 case Builtin::BI__builtin_signbitf:
2835 case Builtin::BI__builtin_signbitl: {
2836 CIRGenFunction::CIRGenFPOptionsRAII fPOptsRAII(*this, e);
2837 mlir::Location loc = getLoc(e->getBeginLoc());
2838 mlir::Value value = emitScalarExpr(e->getArg(0));
2839 mlir::Operation *signBitOp = cir::SignBitOp::create(builder, loc, value);
2840 mlir::Value result = builder.createBoolToInt(signBitOp->getResult(0),
2841 convertType(e->getType()));
2842 return RValue::get(result);
2843 }
2844 case Builtin::BI__warn_memset_zero_len:
2845 case Builtin::BI__annotation:
2846 return errorBuiltinNYI(*this, e, builtinID);
2847
2848 case Builtin::BI__builtin_addcb:
2849 case Builtin::BI__builtin_addcs:
2850 case Builtin::BI__builtin_addc:
2851 case Builtin::BI__builtin_addcl:
2852 case Builtin::BI__builtin_addcll:
2853 case Builtin::BI__builtin_subcb:
2854 case Builtin::BI__builtin_subcs:
2855 case Builtin::BI__builtin_subc:
2856 case Builtin::BI__builtin_subcl:
2857 case Builtin::BI__builtin_subcll: {
2858 // Multiprecision add/sub-with-carry. Lower as two chained checked
2859 // add/sub overflow ops, matching classic CodeGen:
2860 // sum1, carry1 = x +/- y
2861 // result, carry2 = sum1 +/- carryin
2862 // *carryout = carry1 | carry2
2863 // All operands and the result share the builtin's integer type, so no
2864 // encompassing-type widening is needed.
2865 mlir::Value x = emitScalarExpr(e->getArg(0));
2866 mlir::Value y = emitScalarExpr(e->getArg(1));
2867 mlir::Value carryin = emitScalarExpr(e->getArg(2));
2868 Address carryOutPtr = emitPointerWithAlignment(e->getArg(3));
2869
2870 mlir::Location loc = getLoc(e->getSourceRange());
2871 mlir::Type resultTy = convertType(e->getType());
2872
2873 static constexpr unsigned addcBuiltins[] = {
2874 Builtin::BI__builtin_addcb, Builtin::BI__builtin_addcs,
2875 Builtin::BI__builtin_addc, Builtin::BI__builtin_addcl,
2876 Builtin::BI__builtin_addcll};
2877 bool isAdd = llvm::is_contained(addcBuiltins, builtinID);
2878
2879 mlir::Value sum1, carry1, sum2, carry2;
2880 if (isAdd) {
2881 std::tie(sum1, carry1) =
2882 emitOverflowOp<cir::AddOverflowOp>(builder, loc, resultTy, x, y);
2883 std::tie(sum2, carry2) = emitOverflowOp<cir::AddOverflowOp>(
2884 builder, loc, resultTy, sum1, carryin);
2885 } else {
2886 std::tie(sum1, carry1) =
2887 emitOverflowOp<cir::SubOverflowOp>(builder, loc, resultTy, x, y);
2888 std::tie(sum2, carry2) = emitOverflowOp<cir::SubOverflowOp>(
2889 builder, loc, resultTy, sum1, carryin);
2890 }
2891
2892 // Combine the two carry bits, then widen to the result integer type.
2893 mlir::Value carryOut = builder.createBoolToInt(
2894 builder.createOr(loc, carry1, carry2), resultTy);
2895 builder.createStore(loc, carryOut, carryOutPtr);
2896 return RValue::get(sum2);
2897 }
2898
2899 case Builtin::BI__builtin_add_overflow:
2900 case Builtin::BI__builtin_sub_overflow:
2901 case Builtin::BI__builtin_mul_overflow: {
2902 const clang::Expr *leftArg = e->getArg(0);
2903 const clang::Expr *rightArg = e->getArg(1);
2904 const clang::Expr *resultArg = e->getArg(2);
2905
2906 clang::QualType resultQTy =
2907 resultArg->getType()->castAs<clang::PointerType>()->getPointeeType();
2908
2909 WidthAndSignedness leftInfo =
2910 getIntegerWidthAndSignedness(cgm.getASTContext(), leftArg->getType());
2911 WidthAndSignedness rightInfo =
2912 getIntegerWidthAndSignedness(cgm.getASTContext(), rightArg->getType());
2913 WidthAndSignedness resultInfo =
2914 getIntegerWidthAndSignedness(cgm.getASTContext(), resultQTy);
2915
2916 // Note we compute the encompassing type with the consideration to the
2917 // result type, so later in LLVM lowering we don't get redundant integral
2918 // extension casts.
2919 WidthAndSignedness encompassingInfo =
2920 EncompassingIntegerType({leftInfo, rightInfo, resultInfo});
2921
2922 auto encompassingCIRTy = cir::IntType::get(
2923 &getMLIRContext(), encompassingInfo.width, encompassingInfo.isSigned);
2924 mlir::Type resultCIRTy = cgm.convertType(resultQTy);
2925
2926 mlir::Value x = emitScalarExpr(leftArg);
2927 mlir::Value y = emitScalarExpr(rightArg);
2928 Address resultPtr = emitPointerWithAlignment(resultArg);
2929
2930 // Extend each operand to the encompassing type, if necessary.
2931 if (x.getType() != encompassingCIRTy) {
2932 x = builder.createCast(mlir::isa<cir::BoolType>(x.getType())
2933 ? cir::CastKind::bool_to_int
2934 : cir::CastKind::integral,
2935 x, encompassingCIRTy);
2936 }
2937
2938 if (y.getType() != encompassingCIRTy) {
2939 y = builder.createCast(mlir::isa<cir::BoolType>(y.getType())
2940 ? cir::CastKind::bool_to_int
2941 : cir::CastKind::integral,
2942 y, encompassingCIRTy);
2943 }
2944
2945 // Perform the operation on the extended values.
2946 mlir::Location loc = getLoc(e->getSourceRange());
2947 mlir::Value result, overflow;
2948 switch (builtinID) {
2949 default:
2950 llvm_unreachable("Unknown overflow builtin id.");
2951 case Builtin::BI__builtin_add_overflow:
2952 std::tie(result, overflow) =
2953 emitOverflowOp<cir::AddOverflowOp>(builder, loc, resultCIRTy, x, y);
2954 break;
2955 case Builtin::BI__builtin_sub_overflow:
2956 std::tie(result, overflow) =
2957 emitOverflowOp<cir::SubOverflowOp>(builder, loc, resultCIRTy, x, y);
2958 break;
2959 case Builtin::BI__builtin_mul_overflow:
2960 std::tie(result, overflow) =
2961 emitOverflowOp<cir::MulOverflowOp>(builder, loc, resultCIRTy, x, y);
2962 break;
2963 }
2964
2965 // Here is a slight difference from the original clang CodeGen:
2966 // - In the original clang CodeGen, the checked arithmetic result is
2967 // first computed as a value of the encompassing type, and then it is
2968 // truncated to the actual result type with a second overflow checking.
2969 // - In CIRGen, the checked arithmetic operation directly produce the
2970 // checked arithmetic result in its expected type, which may be a
2971 // `cir.bool`.
2972 //
2973 // So we don't need a truncation and a second overflow checking here.
2974
2975 // Finally, store the result using the pointer.
2976 bool isVolatile =
2977 resultArg->getType()->getPointeeType().isVolatileQualified();
2978 builder.createStore(loc, result, resultPtr, isVolatile);
2979
2980 return RValue::get(overflow);
2981 }
2982
2983 case Builtin::BI__builtin_uadd_overflow:
2984 case Builtin::BI__builtin_uaddl_overflow:
2985 case Builtin::BI__builtin_uaddll_overflow:
2986 case Builtin::BI__builtin_usub_overflow:
2987 case Builtin::BI__builtin_usubl_overflow:
2988 case Builtin::BI__builtin_usubll_overflow:
2989 case Builtin::BI__builtin_umul_overflow:
2990 case Builtin::BI__builtin_umull_overflow:
2991 case Builtin::BI__builtin_umulll_overflow:
2992 case Builtin::BI__builtin_sadd_overflow:
2993 case Builtin::BI__builtin_saddl_overflow:
2994 case Builtin::BI__builtin_saddll_overflow:
2995 case Builtin::BI__builtin_ssub_overflow:
2996 case Builtin::BI__builtin_ssubl_overflow:
2997 case Builtin::BI__builtin_ssubll_overflow:
2998 case Builtin::BI__builtin_smul_overflow:
2999 case Builtin::BI__builtin_smull_overflow:
3000 case Builtin::BI__builtin_smulll_overflow: {
3001 // Scalarize our inputs.
3002 mlir::Value x = emitScalarExpr(e->getArg(0));
3003 mlir::Value y = emitScalarExpr(e->getArg(1));
3004
3005 const clang::Expr *resultArg = e->getArg(2);
3006 Address resultPtr = emitPointerWithAlignment(resultArg);
3007
3008 clang::QualType resultQTy =
3009 resultArg->getType()->castAs<clang::PointerType>()->getPointeeType();
3010 auto resultCIRTy = mlir::cast<cir::IntType>(cgm.convertType(resultQTy));
3011
3012 // Create the appropriate overflow-checked arithmetic operation.
3013 mlir::Location loc = getLoc(e->getSourceRange());
3014 mlir::Value result, overflow;
3015 switch (builtinID) {
3016 default:
3017 llvm_unreachable("Unknown overflow builtin id.");
3018 case Builtin::BI__builtin_uadd_overflow:
3019 case Builtin::BI__builtin_uaddl_overflow:
3020 case Builtin::BI__builtin_uaddll_overflow:
3021 case Builtin::BI__builtin_sadd_overflow:
3022 case Builtin::BI__builtin_saddl_overflow:
3023 case Builtin::BI__builtin_saddll_overflow:
3024 std::tie(result, overflow) =
3025 emitOverflowOp<cir::AddOverflowOp>(builder, loc, resultCIRTy, x, y);
3026 break;
3027 case Builtin::BI__builtin_usub_overflow:
3028 case Builtin::BI__builtin_usubl_overflow:
3029 case Builtin::BI__builtin_usubll_overflow:
3030 case Builtin::BI__builtin_ssub_overflow:
3031 case Builtin::BI__builtin_ssubl_overflow:
3032 case Builtin::BI__builtin_ssubll_overflow:
3033 std::tie(result, overflow) =
3034 emitOverflowOp<cir::SubOverflowOp>(builder, loc, resultCIRTy, x, y);
3035 break;
3036 case Builtin::BI__builtin_umul_overflow:
3037 case Builtin::BI__builtin_umull_overflow:
3038 case Builtin::BI__builtin_umulll_overflow:
3039 case Builtin::BI__builtin_smul_overflow:
3040 case Builtin::BI__builtin_smull_overflow:
3041 case Builtin::BI__builtin_smulll_overflow:
3042 std::tie(result, overflow) =
3043 emitOverflowOp<cir::MulOverflowOp>(builder, loc, resultCIRTy, x, y);
3044 break;
3045 }
3046
3047 bool isVolatile =
3048 resultArg->getType()->getPointeeType().isVolatileQualified();
3049 builder.createStore(loc, emitToMemory(result, resultQTy), resultPtr,
3050 isVolatile);
3051
3052 return RValue::get(overflow);
3053 }
3054
3055 case Builtin::BIaddressof:
3056 case Builtin::BI__addressof:
3057 case Builtin::BI__builtin_addressof:
3058 return RValue::get(emitLValue(e->getArg(0)).getPointer());
3059 case Builtin::BI__builtin_function_start:
3060 return errorBuiltinNYI(*this, e, builtinID);
3061 case Builtin::BI__builtin_operator_new:
3063 e->getCallee()->getType()->castAs<FunctionProtoType>(), e, OO_New);
3064 case Builtin::BI__builtin_operator_delete:
3066 e->getCallee()->getType()->castAs<FunctionProtoType>(), e, OO_Delete);
3067 return RValue::get(nullptr);
3068 case Builtin::BI__builtin_is_aligned:
3069 case Builtin::BI__builtin_align_up:
3070 case Builtin::BI__builtin_align_down:
3071 case Builtin::BI__noop:
3072 case Builtin::BI__builtin_call_with_static_chain:
3073 case Builtin::BI_InterlockedExchange8:
3074 case Builtin::BI_InterlockedExchange16:
3075 case Builtin::BI_InterlockedExchange:
3076 case Builtin::BI_InterlockedExchangePointer:
3077 case Builtin::BI_InterlockedCompareExchangePointer:
3078 case Builtin::BI_InterlockedCompareExchangePointer_nf:
3079 case Builtin::BI_InterlockedCompareExchange8:
3080 case Builtin::BI_InterlockedCompareExchange16:
3081 case Builtin::BI_InterlockedCompareExchange:
3082 case Builtin::BI_InterlockedCompareExchange64:
3083 case Builtin::BI_InterlockedIncrement16:
3084 case Builtin::BI_InterlockedIncrement:
3085 case Builtin::BI_InterlockedDecrement16:
3086 case Builtin::BI_InterlockedDecrement:
3087 case Builtin::BI_InterlockedAnd8:
3088 case Builtin::BI_InterlockedAnd16:
3089 case Builtin::BI_InterlockedAnd:
3090 case Builtin::BI_InterlockedExchangeAdd8:
3091 case Builtin::BI_InterlockedExchangeAdd16:
3092 case Builtin::BI_InterlockedExchangeAdd:
3093 case Builtin::BI_InterlockedExchangeSub8:
3094 case Builtin::BI_InterlockedExchangeSub16:
3095 case Builtin::BI_InterlockedExchangeSub:
3096 case Builtin::BI_InterlockedOr8:
3097 case Builtin::BI_InterlockedOr16:
3098 case Builtin::BI_InterlockedOr:
3099 case Builtin::BI_InterlockedXor8:
3100 case Builtin::BI_InterlockedXor16:
3101 case Builtin::BI_InterlockedXor:
3102 case Builtin::BI_bittest64:
3103 case Builtin::BI_bittest:
3104 case Builtin::BI_bittestandcomplement64:
3105 case Builtin::BI_bittestandcomplement:
3106 case Builtin::BI_bittestandreset64:
3107 case Builtin::BI_bittestandreset:
3108 case Builtin::BI_bittestandset64:
3109 case Builtin::BI_bittestandset:
3110 case Builtin::BI_interlockedbittestandreset:
3111 case Builtin::BI_interlockedbittestandreset64:
3112 case Builtin::BI_interlockedbittestandreset64_acq:
3113 case Builtin::BI_interlockedbittestandreset64_rel:
3114 case Builtin::BI_interlockedbittestandreset64_nf:
3115 case Builtin::BI_interlockedbittestandset64:
3116 case Builtin::BI_interlockedbittestandset64_acq:
3117 case Builtin::BI_interlockedbittestandset64_rel:
3118 case Builtin::BI_interlockedbittestandset64_nf:
3119 case Builtin::BI_interlockedbittestandset:
3120 case Builtin::BI_interlockedbittestandset_acq:
3121 case Builtin::BI_interlockedbittestandset_rel:
3122 case Builtin::BI_interlockedbittestandset_nf:
3123 case Builtin::BI_interlockedbittestandreset_acq:
3124 case Builtin::BI_interlockedbittestandreset_rel:
3125 case Builtin::BI_interlockedbittestandreset_nf:
3126 case Builtin::BI__iso_volatile_load8:
3127 case Builtin::BI__iso_volatile_load16:
3128 case Builtin::BI__iso_volatile_load32:
3129 case Builtin::BI__iso_volatile_load64:
3130 case Builtin::BI__iso_volatile_store8:
3131 case Builtin::BI__iso_volatile_store16:
3132 case Builtin::BI__iso_volatile_store32:
3133 case Builtin::BI__iso_volatile_store64:
3134 case Builtin::BI__builtin_ptrauth_sign_constant:
3135 case Builtin::BI__builtin_ptrauth_auth:
3136 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3137 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3138 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3139 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3140 case Builtin::BI__builtin_ptrauth_strip:
3141 case Builtin::BI__builtin_get_vtable_pointer:
3142 case Builtin::BI__exception_code:
3143 case Builtin::BI_exception_code:
3144 case Builtin::BI__exception_info:
3145 case Builtin::BI_exception_info:
3146 case Builtin::BI__abnormal_termination:
3147 case Builtin::BI_abnormal_termination:
3148 return errorBuiltinNYI(*this, e, builtinID);
3149 case Builtin::BI_setjmpex:
3150 case Builtin::BI_setjmp:
3151 if (getTarget().getTriple().isOSMSVCRT()) {
3152 cgm.errorNYI(e->getSourceRange(), "setjmp/setjmpex on MSVCRT");
3153 return getUndefRValue(e->getType());
3154 }
3155 // Else break and this will be handled as a library call.
3156 break;
3157 case Builtin::BImove:
3158 case Builtin::BImove_if_noexcept:
3159 case Builtin::BIforward:
3160 case Builtin::BIforward_like:
3161 case Builtin::BIas_const:
3162 return RValue::get(emitLValue(e->getArg(0)).getPointer());
3163 case Builtin::BI__GetExceptionInfo:
3164 case Builtin::BI__fastfail:
3165 return errorBuiltinNYI(*this, e, builtinID);
3166 case Builtin::BI__builtin_coro_id:
3167 return RValue::get(emitCoroIDBuiltinCall(e).getResult());
3168 case Builtin::BI__builtin_coro_promise:
3169 return RValue::get(emitCoroPromiseBuiltinCall(e).getResult());
3170 case Builtin::BI__builtin_coro_resume: {
3172 return RValue::get(nullptr);
3173 }
3174 case Builtin::BI__builtin_coro_frame: {
3175 return emitCoroutineFrame();
3176 }
3177 case Builtin::BI__builtin_coro_noop:
3178 return RValue::get(emitCoroNoopBuiltinCall(e).getResult());
3179 case Builtin::BI__builtin_coro_free: {
3180 cir::CoroFreeOp coroFree = emitCoroFreeBuiltin(e);
3181 return coroFree ? RValue::get(coroFree.getResult())
3182 : getUndefRValue(e->getType());
3183 }
3184 case Builtin::BI__builtin_coro_destroy: {
3186 return RValue::get(nullptr);
3187 }
3188 case Builtin::BI__builtin_coro_done:
3189 return RValue::get(emitCoroDoneBuiltinCall(e).getResult());
3190 case Builtin::BI__builtin_coro_alloc: {
3191 cir::CoroAllocOp coroAlloc = emitCoroAllocBuiltinCall(e);
3192 return coroAlloc ? RValue::get(coroAlloc.getResult())
3193 : getUndefRValue(e->getType());
3194 }
3195 case Builtin::BI__builtin_coro_begin: {
3196 cir::CoroBeginOp coroBeg = emitCoroBeginBuiltinCall(e);
3197 return coroBeg ? RValue::get(coroBeg.getResult())
3198 : getUndefRValue(e->getType());
3199 }
3200 case Builtin::BI__builtin_coro_end:
3201 return RValue::get(emitCoroEndBuiltinCall(e).getResult());
3202 case Builtin::BI__builtin_coro_suspend: {
3203 mlir::Value result = emitCoroSuspendBuiltinCall(e).getResult();
3204 return RValue::get(
3205 builder.createIntCast(result, convertType(e->getType())));
3206 }
3207 case Builtin::BI__builtin_coro_size: {
3208 return RValue::get(emitCoroSizeBuiltinCall(e).getResult());
3209 }
3210 case Builtin::BI__builtin_coro_align:
3211 return RValue::get(emitCoroAlignBuiltinCall(e).getResult());
3212 case Builtin::BIread_pipe:
3213 case Builtin::BIwrite_pipe:
3214 case Builtin::BIreserve_read_pipe:
3215 case Builtin::BIreserve_write_pipe:
3216 case Builtin::BIwork_group_reserve_read_pipe:
3217 case Builtin::BIwork_group_reserve_write_pipe:
3218 case Builtin::BIsub_group_reserve_read_pipe:
3219 case Builtin::BIsub_group_reserve_write_pipe:
3220 case Builtin::BIcommit_read_pipe:
3221 case Builtin::BIcommit_write_pipe:
3222 case Builtin::BIwork_group_commit_read_pipe:
3223 case Builtin::BIwork_group_commit_write_pipe:
3224 case Builtin::BIsub_group_commit_read_pipe:
3225 case Builtin::BIsub_group_commit_write_pipe:
3226 case Builtin::BIget_pipe_num_packets:
3227 case Builtin::BIget_pipe_max_packets:
3228 case Builtin::BIto_global:
3229 case Builtin::BIto_local:
3230 case Builtin::BIto_private:
3231 case Builtin::BIenqueue_kernel:
3232 case Builtin::BIget_kernel_work_group_size:
3233 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3234 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3235 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3236 case Builtin::BI__builtin_store_half:
3237 case Builtin::BI__builtin_store_halff:
3238 case Builtin::BI__builtin_load_half:
3239 case Builtin::BI__builtin_load_halff:
3240 return errorBuiltinNYI(*this, e, builtinID);
3241 case Builtin::BI__builtin_printf:
3242 case Builtin::BIprintf:
3243 if (getTarget().getTriple().isNVPTX() ||
3244 getTarget().getTriple().isAMDGCN() ||
3245 (getTarget().getTriple().isSPIRV() &&
3246 getTarget().getTriple().getVendor() == llvm::Triple::AMD))
3248 break;
3249 case Builtin::BI__builtin_canonicalize:
3250 case Builtin::BI__builtin_canonicalizef:
3251 case Builtin::BI__builtin_canonicalizef16:
3252 case Builtin::BI__builtin_canonicalizel:
3253 case Builtin::BI__builtin_thread_pointer:
3254 case Builtin::BI__builtin_os_log_format:
3255 case Builtin::BI__xray_customevent:
3256 case Builtin::BI__xray_typedevent:
3257 case Builtin::BI__builtin_ms_va_start:
3258 case Builtin::BI__builtin_ms_va_end:
3259 case Builtin::BI__builtin_ms_va_copy:
3260 case Builtin::BI__builtin_get_device_side_mangled_name:
3261 return errorBuiltinNYI(*this, e, builtinID);
3262 }
3263
3264 // If this is an alias for a lib function (e.g. __builtin_sin), emit
3265 // the call using the normal call path, but using the unmangled
3266 // version of the function name.
3267 if (!shouldEmitBuiltinAsIR(builtinID, getContext().BuiltinInfo, *this) &&
3268 getContext().BuiltinInfo.isLibFunction(builtinID))
3269 return emitLibraryCall(*this, fd, e,
3270 cgm.getBuiltinLibFunction(fd, builtinID));
3271
3272 // If this is a predefined lib function (e.g. malloc), emit the call
3273 // using exactly the normal call path.
3274 if (getContext().BuiltinInfo.isPredefinedLibFunction(builtinID))
3275 return emitLibraryCall(*this, fd, e,
3276 emitScalarExpr(e->getCallee()).getDefiningOp());
3277
3278 // Check that a call to a target specific builtin has the correct target
3279 // features.
3280 // This is down here to avoid non-target specific builtins, however, if
3281 // generic builtins start to require generic target features then we
3282 // can move this up to the beginning of the function.
3283 checkTargetFeatures(e, fd);
3284
3285 // See if we have a target specific intrinsic.
3286 std::string name = getContext().BuiltinInfo.getName(builtinID);
3287 Intrinsic::ID intrinsicID = Intrinsic::not_intrinsic;
3288 StringRef prefix =
3289 llvm::Triple::getArchTypePrefix(getTarget().getTriple().getArch());
3290 if (!prefix.empty()) {
3291 intrinsicID = Intrinsic::getIntrinsicForClangBuiltin(prefix, name);
3292 if (intrinsicID == Intrinsic::not_intrinsic && prefix == "spv" &&
3293 getTarget().getTriple().getOS() == llvm::Triple::OSType::AMDHSA)
3294 intrinsicID = Intrinsic::getIntrinsicForClangBuiltin("amdgcn", name);
3295 // NOTE we don't need to perform a compatibility flag check here since the
3296 // intrinsics are declared in Builtins*.def via LANGBUILTIN which filter the
3297 // MS builtins via ALL_MS_LANGUAGES and are filtered earlier.
3298 if (intrinsicID == Intrinsic::not_intrinsic)
3299 intrinsicID = Intrinsic::getIntrinsicForMSBuiltin(prefix, name);
3300 }
3301
3302 if (intrinsicID != Intrinsic::not_intrinsic) {
3303 unsigned iceArguments = 0;
3305 getContext().GetBuiltinType(builtinID, error, &iceArguments);
3306 assert(error == ASTContext::GE_None && "Should not codegen an error");
3307
3308 StringRef name = Intrinsic::getName(intrinsicID);
3309 // cir::LLVMIntrinsicCallOp expects intrinsic name to not have prefix
3310 // "llvm." For example, `llvm.nvvm.barrier0` should be passed as
3311 // `nvvm.barrier0`.
3312 assert(name.starts_with("llvm.") && "expected llvm. prefix");
3313 name = name.drop_front(/*strlen("llvm.")=*/5);
3314
3315 cir::FuncType intrinsicType = getIntrinsicType(intrinsicID);
3316
3318 const FunctionDecl *fd = e->getDirectCallee();
3319 for (unsigned i = 0; i < e->getNumArgs(); i++) {
3320 mlir::Value argValue =
3321 emitScalarOrConstFoldImmArg(iceArguments, i, e->getArg(i));
3322 // If the intrinsic arg type is different from the builtin arg type
3323 // we need to do a bit cast.
3324 mlir::Type argType = argValue.getType();
3325 mlir::Type expectedTy = intrinsicType.getInput(i);
3326
3327 // Correct integer signedness based on AST parameter type
3328 mlir::Type correctedExpectedTy = expectedTy;
3329 if (fd && i < fd->getNumParams()) {
3330 correctedExpectedTy = correctIntegerSignedness(
3331 expectedTy, fd->getParamDecl(i)->getType(), &getMLIRContext());
3332 }
3333
3334 if (mlir::isa<cir::PointerType>(expectedTy)) {
3335 bool argIsPointer = mlir::isa<cir::PointerType>(argType);
3336 bool argIsVectorOfPointer = false;
3337 if (auto vecTy = dyn_cast<mlir::VectorType>(argType))
3338 argIsVectorOfPointer =
3339 mlir::isa<cir::PointerType>(vecTy.getElementType());
3340
3341 if (!argIsPointer && !argIsVectorOfPointer) {
3342 cgm.errorNYI(
3343 e->getSourceRange(),
3344 "intrinsic expects a pointer type (NYI for non-pointer)");
3345 return getUndefRValue(e->getType());
3346 }
3347
3348 // Pointer handling (address-space cast / bitcast fallback).
3349 if (argType != expectedTy)
3350 argValue = getCorrectedPtr(argValue, expectedTy, builder);
3351 } else {
3352 // Non-pointer expected type: if needed, bitcast to the corrected
3353 // expected type to match signedness/representation.
3354 if (argType != correctedExpectedTy)
3355 argValue = builder.createBitcast(argValue, correctedExpectedTy);
3356 }
3357
3358 args.push_back(argValue);
3359 }
3360
3361 // Correct the builtin type based on the AST function declaration's return
3362 // type, if available.
3363 mlir::Type correctedReturnType =
3364 correctReturnType(intrinsicType.getReturnType(), fd, &getMLIRContext());
3365
3366 cir::LLVMIntrinsicCallOp intrinsicCall = cir::LLVMIntrinsicCallOp::create(
3367 builder, getLoc(e->getExprLoc()), builder.getStringAttr(name),
3368 correctedReturnType, args);
3369
3370 mlir::Value intrinsicRes = intrinsicCall.getResult();
3371
3372 if (isa<cir::VoidType>(correctedReturnType))
3373 return RValue::get(nullptr);
3374
3375 return RValue::get(intrinsicRes);
3376 }
3377
3378 // Some target-specific builtins can have aggregate return values, e.g.
3379 // __builtin_arm_mve_vld2q_u32. So if the result is an aggregate, force
3380 // returnValue to be non-null, so that the target-specific emission code can
3381 // always just emit into it.
3383 if (evalKind == cir::TEK_Aggregate && returnValue.isNull()) {
3384 cgm.errorNYI(e->getSourceRange(), "aggregate return value from builtin");
3385 return getUndefRValue(e->getType());
3386 }
3387
3388 // Now see if we can emit a target-specific builtin.
3389 // FIXME: This is a temporary mechanism (double-optional semantics) that will
3390 // go away once everything is implemented:
3391 // 1. return `mlir::Value{}` for cases where we have issued the diagnostic.
3392 // 2. return `std::nullopt` in cases where we didn't issue a diagnostic
3393 // but also didn't handle the builtin.
3394 if (std::optional<mlir::Value> rst =
3395 emitTargetBuiltinExpr(builtinID, e, returnValue)) {
3396 mlir::Value v = rst.value();
3397 // A null value means either a void builtin or an already diagnosed NYI.
3398 // In the case of a void builtin, getUndefRValue returns
3399 // `RValue::get(nullptr)`.
3400 if (!v)
3401 return getUndefRValue(e->getType());
3402
3403 switch (evalKind) {
3404 case cir::TEK_Scalar:
3405 if (mlir::isa<cir::VoidType>(v.getType()))
3406 return RValue::get(nullptr);
3407 return RValue::get(v);
3408 case cir::TEK_Aggregate:
3409 cgm.errorNYI(e->getSourceRange(), "aggregate return value from builtin");
3410 return getUndefRValue(e->getType());
3411 case cir::TEK_Complex:
3412 llvm_unreachable("No current target builtin returns complex");
3413 }
3414 llvm_unreachable("Bad evaluation kind in EmitBuiltinExpr");
3415 }
3416
3417 cgm.errorNYI(e->getSourceRange(),
3418 std::string("unimplemented builtin call: ") +
3419 getContext().BuiltinInfo.getName(builtinID));
3420 return getUndefRValue(e->getType());
3421}
3422
3423static std::optional<mlir::Value>
3425 const CallExpr *e, ReturnValueSlot &returnValue,
3426 llvm::Triple::ArchType arch) {
3427 // When compiling in HipStdPar mode we have to be conservative in rejecting
3428 // target specific features in the FE, and defer the possible error to the
3429 // AcceleratorCodeSelection pass, wherein iff an unsupported target builtin is
3430 // referenced by an accelerator executable function, we emit an error.
3431 // Returning nullptr here leads to the builtin being handled in
3432 // EmitStdParUnsupportedBuiltin.
3433 if (cgf->getLangOpts().HIPStdPar && cgf->getLangOpts().CUDAIsDevice &&
3434 arch != cgf->getTarget().getTriple().getArch())
3435 return std::nullopt;
3436
3437 switch (arch) {
3438 case llvm::Triple::arm:
3439 case llvm::Triple::armeb:
3440 case llvm::Triple::thumb:
3441 case llvm::Triple::thumbeb:
3442 // These are actually NYI, but that will be reported by emitBuiltinExpr.
3443 // At this point, we don't even know that the builtin is target-specific.
3444 return std::nullopt;
3445 case llvm::Triple::aarch64:
3446 case llvm::Triple::aarch64_32:
3447 case llvm::Triple::aarch64_be:
3448 return cgf->emitAArch64BuiltinExpr(builtinID, e, returnValue, arch);
3449 case llvm::Triple::bpfeb:
3450 case llvm::Triple::bpfel:
3451 // These are actually NYI, but that will be reported by emitBuiltinExpr.
3452 // At this point, we don't even know that the builtin is target-specific.
3453 return std::nullopt;
3454
3455 case llvm::Triple::x86:
3456 case llvm::Triple::x86_64:
3457 return cgf->emitX86BuiltinExpr(builtinID, e);
3458
3459 case llvm::Triple::ppc:
3460 case llvm::Triple::ppcle:
3461 case llvm::Triple::ppc64:
3462 case llvm::Triple::ppc64le:
3463 case llvm::Triple::r600:
3464 // These are actually NYI, but that will be reported by emitBuiltinExpr.
3465 // At this point, we don't even know that the builtin is target-specific.
3466 return std::nullopt;
3467 case llvm::Triple::amdgpu:
3468 return cgf->emitAMDGPUBuiltinExpr(builtinID, e);
3469 case llvm::Triple::systemz:
3470 return std::nullopt;
3471 case llvm::Triple::nvptx:
3472 case llvm::Triple::nvptx64:
3473 return cgf->emitNVPTXBuiltinExpr(builtinID, e);
3474 case llvm::Triple::wasm32:
3475 case llvm::Triple::wasm64:
3476 case llvm::Triple::hexagon:
3477 // These are actually NYI, but that will be reported by emitBuiltinExpr.
3478 // At this point, we don't even know that the builtin is target-specific.
3479 return std::nullopt;
3480 case llvm::Triple::riscv32:
3481 case llvm::Triple::riscv64:
3482 return cgf->emitRISCVBuiltinExpr(builtinID, e);
3483 case llvm::Triple::spirv32:
3484 case llvm::Triple::spirv64:
3485 if (cgf->getTarget().getTriple().getOS() == llvm::Triple::OSType::AMDHSA)
3486 return cgf->emitAMDGPUBuiltinExpr(builtinID, e);
3487 [[fallthrough]];
3488 case llvm::Triple::spirv:
3489 return cgf->emitSPIRVBuiltinExpr(builtinID, e);
3490 default:
3491 return std::nullopt;
3492 }
3493}
3494
3495std::optional<mlir::Value>
3498 if (getContext().BuiltinInfo.isAuxBuiltinID(builtinID)) {
3499 assert(getContext().getAuxTargetInfo() && "Missing aux target info");
3501 this, getContext().BuiltinInfo.getAuxBuiltinID(builtinID), e,
3502 returnValue, getContext().getAuxTargetInfo()->getTriple().getArch());
3503 }
3504
3505 return emitTargetArchBuiltinExpr(this, builtinID, e, returnValue,
3506 getTarget().getTriple().getArch());
3507}
3508
3510 const unsigned iceArguments, const unsigned idx, const Expr *argExpr) {
3511 mlir::Value arg = {};
3512 if ((iceArguments & (1 << idx)) == 0) {
3513 arg = emitScalarExpr(argExpr);
3514 } else {
3515 // If this is required to be a constant, constant fold it so that we
3516 // know that the generated intrinsic gets a ConstantInt.
3517 const std::optional<llvm::APSInt> result =
3519 assert(result && "Expected argument to be a constant");
3520 arg = builder.getConstInt(getLoc(argExpr->getSourceRange()), *result);
3521 }
3522 return arg;
3523}
3524
3525/// Given a builtin id for a function like "__builtin_fabsf", return a Function*
3526/// for "fabsf".
3528 unsigned builtinID) {
3529 assert(astContext.BuiltinInfo.isLibFunction(builtinID));
3530
3531 // Get the name, skip over the __builtin_ prefix (if necessary). We may have
3532 // to build this up so provide a small stack buffer to handle the vast
3533 // majority of names.
3535 GlobalDecl d(fd);
3536
3537 // If the builtin has been declared explicitly with an assembler label,
3538 // use the mangled name. This differs from the plain label on platforms
3539 // that prefix labels.
3540 if (fd->hasAttr<AsmLabelAttr>())
3541 name = getMangledName(d);
3542 else if (llvm::StringRef targetName =
3544 getTarget());
3545 !targetName.empty())
3546 name = targetName;
3547 else
3548 name = astContext.BuiltinInfo.getName(builtinID).substr(10);
3549
3550 mlir::Type type = convertType(fd->getType());
3551 return getOrCreateCIRFunction(name, type, d, /*forVTable=*/false);
3552}
3553
3555 mlir::Value argValue = evaluateExprAsBool(e);
3556 if (!sanOpts.has(SanitizerKind::Builtin))
3557 return argValue;
3558
3560 cgm.errorNYI(e->getSourceRange(),
3561 "emitCheckedArgForAssume: sanitizers are NYI");
3562 return {};
3563}
3564
3565void CIRGenFunction::emitVAStart(mlir::Value vaList) {
3566 // LLVM codegen casts to *i8, no real gain on doing this for CIRGen this
3567 // early, defer to LLVM lowering.
3568 cir::VAStartOp::create(builder, vaList.getLoc(), vaList);
3569}
3570
3571void CIRGenFunction::emitVAEnd(mlir::Value vaList) {
3572 cir::VAEndOp::create(builder, vaList.getLoc(), vaList);
3573}
3574
3575// FIXME(cir): This completely abstracts away the ABI with a generic CIR Op. By
3576// default this lowers to llvm.va_arg which is incomplete and not ABI-compliant
3577// on most targets so cir.va_arg will need some ABI handling in LoweringPrepare
3579 assert(!cir::MissingFeatures::msabi());
3580 assert(!cir::MissingFeatures::vlas());
3581 mlir::Location loc = cgm.getLoc(ve->getExprLoc());
3582 mlir::Type type = convertType(ve->getType());
3583 mlir::Value vaList = emitVAListRef(ve->getSubExpr()).getPointer();
3584 return cir::VAArgOp::create(builder, loc, type, vaList);
3585}
3586
3587mlir::Value CIRGenFunction::emitBuiltinObjectSize(const Expr *e, unsigned type,
3588 cir::IntType resType,
3589 mlir::Value emittedE,
3590 bool isDynamic) {
3591 // If this is a pass_object_size parameter, load the implicit size arg.
3592 //
3593 // BOS type compatibility: a pass_object_size annotation with one type can
3594 // satisfy a __builtin_object_size query with a different type when the
3595 // annotated type is a safe approximation. Type 0 (max, whole object) is
3596 // an overestimate for type 1 (max, closest surrounding subobject), and
3597 // type 3 (min, closest surrounding subobject) is an underestimate for
3598 // type 2 (min, whole object).
3599 enum BOSType {
3600 MaxWholeObject = 0,
3601 MaxSubobject = 1,
3602 MinWholeObject = 2,
3603 MinSubobject = 3,
3604 };
3605 if (auto *dre = dyn_cast<DeclRefExpr>(e->IgnoreParenImpCasts())) {
3606 auto *param = dyn_cast<ParmVarDecl>(dre->getDecl());
3607 auto *objSizeAttr = dre->getDecl()->getAttr<PassObjectSizeAttr>();
3608 if (param && objSizeAttr) {
3609 auto from = objSizeAttr->getType();
3610 bool compatible = from == static_cast<int>(type) ||
3611 (from == MaxWholeObject && type == MaxSubobject) ||
3612 (from == MinSubobject && type == MinWholeObject);
3613 if (compatible) {
3614 const ImplicitParamDecl *sizeDecl = sizeArguments.lookup(param);
3615 assert(sizeDecl && "expected pass_object_size implicit param");
3616
3617 DeclMapTy::iterator declIter = localDeclMap.find(sizeDecl);
3618 assert(declIter != localDeclMap.end());
3619 Address addr = declIter->second;
3620
3621 return emitLoadOfScalar(addr, /*volatile=*/false,
3622 getContext().getSizeType(), e->getBeginLoc(),
3624 }
3625 }
3626 }
3627
3628 // LLVM can't handle type=3 appropriately, and __builtin_object_size shouldn't
3629 // evaluate e for side-effects. In either case, just like original LLVM
3630 // lowering, we shouldn't lower to `cir.objsize` but to a constant instead.
3631 if (type == 3 || (!emittedE && e->HasSideEffects(getContext())))
3632 return builder.getConstInt(getLoc(e->getSourceRange()), resType,
3633 (type & 2) ? 0 : -1);
3634
3635 mlir::Value ptr = emittedE ? emittedE : emitScalarExpr(e);
3636 assert(mlir::isa<cir::PointerType>(ptr.getType()) &&
3637 "Non-pointer passed to __builtin_object_size?");
3638
3640
3641 // Extract the min/max mode from type. CIR only supports type 0
3642 // (max, whole object) and type 2 (min, whole object), not type 1 or 3
3643 // (closest subobject variants).
3644 const bool min = ((type & 2) != 0);
3645 // For GCC compatibility, __builtin_object_size treats NULL as unknown size.
3646 auto op =
3647 cir::ObjSizeOp::create(builder, getLoc(e->getSourceRange()), resType, ptr,
3648 min, /*nullUnknown=*/true, isDynamic);
3649 return op.getResult();
3650}
3651
3653 const Expr *e, unsigned type, cir::IntType resType, mlir::Value emittedE,
3654 bool isDynamic) {
3655 if (std::optional<uint64_t> objectSize =
3657 return builder.getConstInt(getLoc(e->getSourceRange()), resType,
3658 *objectSize);
3659 return emitBuiltinObjectSize(e, type, resType, emittedE, isDynamic);
3660}
3661
3662// Emit a device printf as a cir.offload.printf. Unlike classic codegen, which
3663// emits each target's printf runtime interface here, CIR leaves that to the
3664// target-specific lowering of the op.
3666 assert(cgm.getTriple().isNVPTX() || cgm.getTriple().isAMDGCN() ||
3667 (cgm.getTriple().isSPIRV() &&
3668 cgm.getTriple().getVendor() == llvm::Triple::AMD));
3669 assert(expr->getBuiltinCallee() == Builtin::BIprintf ||
3670 expr->getBuiltinCallee() == Builtin::BI__builtin_printf);
3671 assert(expr->getNumArgs() >= 1); // printf always has at least one arg.
3672 CallArgList args;
3673 emitCallArgs(args,
3674 expr->getDirectCallee()->getType()->getAs<FunctionProtoType>(),
3675 expr->arguments(), expr->getDirectCallee());
3676
3677 mlir::Location loc = getLoc(expr->getBeginLoc());
3678
3679 // We don't know how to emit non-scalar varargs, nor scalars that
3680 // cir.offload.printf does not accept.
3681 bool hasNonScalar =
3682 llvm::any_of(llvm::drop_begin(args), [&](const CallArg &a) {
3683 if (a.hasLValue() || !a.getKnownRValue().isScalar())
3684 return true;
3685 mlir::Type ty = a.getKnownRValue().getValue().getType();
3686 return !mlir::isa<cir::IntType, cir::PointerType, cir::DataMemberType,
3687 cir::VectorType>(ty) &&
3688 !cir::isAnyFloatingPointType(ty);
3689 });
3690 if (hasNonScalar) {
3691 cgm.errorUnsupported(expr, "non-scalar args to printf");
3692 return builder.getConstInt(loc, builder.getSInt32Ty(), 0);
3693 }
3694
3696 for (const CallArg &a : args)
3697 callArgs.push_back(a.getKnownRValue().getValue());
3698
3699 return cir::OffloadPrintfOp::create(builder, loc, builder.getSInt32Ty(),
3700 callArgs.front(),
3701 llvm::drop_begin(callArgs));
3702}
static StringRef bytes(const std::vector< T, Allocator > &v)
Defines enum values for all the target-independent builtin functions.
static RValue emitStdcCountOp(CIRGenFunction &cgf, const CallExpr *e, bool invertArg, Args... args)
static bool isStdcBitOpWidthSupported(cir::IntType intTy)
static RValue emitStdcHasSingleBit(CIRGenFunction &cgf, const CallExpr *e)
static mlir::Value emitSignBit(mlir::Location loc, CIRGenFunction &cgf, mlir::Value val)
static RValue emitTernarySameTypeBuiltin(CIRGenFunction &cgf, const CallExpr &e)
static mlir::Value emitBinaryMaybeConstrainedFPBuiltin(CIRGenFunction &cgf, const CallExpr &e)
static mlir::Value createBuiltinBitOp(CIRGenFunction &cgf, const CallExpr *e, mlir::Value arg, Args... args)
static RValue emitUnaryMaybeConstrainedFPBuiltin(CIRGenFunction &cgf, const CallExpr &e)
static void emitAtomicLockRelease(CIRGenFunction &cgf, const CallExpr *e)
Emit a release store of 0 for __sync_lock_release_N.
static RValue emitBinaryFPBuiltin(CIRGenFunction &cgf, const CallExpr &e)
static RValue emitStdcBitWidthMinus(CIRGenFunction &cgf, const CallExpr *e, Args... args)
static mlir::Type decodeFixedType(CIRGenFunction &cgf, ArrayRef< llvm::Intrinsic::IITDescriptor > &infos, ArrayRef< mlir::Type > overloadTys, mlir::MLIRContext *context)
static RValue emitBinaryAtomicPost(CIRGenFunction &cgf, cir::AtomicFetchKind atomicOpkind, const CallExpr *e, bool invert=false)
static std::optional< mlir::Value > emitTargetArchBuiltinExpr(CIRGenFunction *cgf, unsigned builtinID, const CallExpr *e, ReturnValueSlot &returnValue, llvm::Triple::ArchType arch)
static RValue emitUnaryFPBuiltin(CIRGenFunction &cgf, const CallExpr &e)
static RValue emitBinaryAtomic(CIRGenFunction &cgf, cir::AtomicFetchKind atomicOpkind, const CallExpr *e)
static mlir::Value emitToInt(CIRGenFunction &cgf, mlir::Value v, QualType t, cir::IntType intType)
Emit the conversions required to turn the given value into an integer of the given size.
static RValue emitStdcBitFloor(CIRGenFunction &cgf, const CallExpr *e)
static mlir::Value getCorrectedPtr(mlir::Value argValue, mlir::Type expectedTy, CIRGenBuilderTy &builder)
static std::pair< mlir::Value, mlir::Value > emitOverflowOp(CIRGenBuilderTy &builder, mlir::Location loc, mlir::Type resultTy, mlir::Value lhs, mlir::Value rhs)
Create a checked overflow arithmetic op and return its result and overflow flag.
static bool shouldEmitBuiltinAsIR(unsigned builtinID, const Builtin::Context &bi, const CIRGenFunction &cgf)
static RValue emitTernaryMaybeConstrainedFPBuiltin(CIRGenFunction &cgf, const CallExpr &e)
static RValue emitLibraryCall(CIRGenFunction &cgf, const FunctionDecl *fd, const CallExpr *e, mlir::Operation *calleeValue)
static RValue emitAtomicXchg(CIRGenFunction &cgf, const CallExpr *e, cir::MemOrder ordering)
Emit a cir.atomic.xchg for __sync_swap_N and __sync_lock_test_and_set_N.
static WidthAndSignedness getIntegerWidthAndSignedness(const clang::ASTContext &astContext, const clang::QualType type)
static void emitAtomicFenceOp(CIRGenFunction &cgf, const CallExpr *expr, cir::SyncScopeKind syncScope)
static RValue emitBuiltinBitOp(CIRGenFunction &cgf, const CallExpr *e, Args... args)
static Address checkAtomicAlignment(CIRGenFunction &cgf, const CallExpr *e)
static RValue emitAtomicIsLockFree(CIRGenFunction &cgf, const CallExpr *e, unsigned builtinID)
static bool shouldCIREmitFPMathIntrinsic(CIRGenFunction &cgf, const CallExpr *e, unsigned builtinID)
static RValue tryEmitFPMathIntrinsic(CIRGenFunction &cgf, const CallExpr *e, unsigned builtinID)
static RValue emitBuiltinBitOpWithFallback(CIRGenFunction &cgf, const CallExpr *e)
Emit a clz/ctz bit op with optional fallback for __builtin_c[lt]zg.
static RValue errorStdcBitOpWidthNYI(CIRGenFunction &cgf, const CallExpr *e)
static RValue emitStdcFirstBit(CIRGenFunction &cgf, const CallExpr *e, bool invertArg, Args... args)
static struct WidthAndSignedness EncompassingIntegerType(ArrayRef< struct WidthAndSignedness > types)
static RValue emitBuiltinAlloca(CIRGenFunction &cgf, const CallExpr *e, unsigned builtinID)
static mlir::Type correctIntegerSignedness(mlir::Type iitType, QualType astType, mlir::MLIRContext *context)
Helper function to correct integer signedness for intrinsic arguments and return type.
static RValue emitUnaryMaybeConstrainedFPToIntBuiltin(CIRGenFunction &cgf, const CallExpr &e)
static RValue emitBuiltinVectorReduction(CIRGenFunction &cgf, const CallExpr *e)
static RValue errorBuiltinNYI(CIRGenFunction &cgf, const CallExpr *e, unsigned builtinID)
static RValue emitStdcBitCeil(CIRGenFunction &cgf, const CallExpr *e)
static mlir::Type correctReturnType(mlir::Type iitType, const FunctionDecl *funcDecl, mlir::MLIRContext *context)
Helper function to correct the return type for intrinsic calls.
static mlir::Value emitFromInt(CIRGenFunction &cgf, mlir::Value v, QualType t, mlir::Type resultType)
static StringRef getTriple(const Command &Job)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
Defines an enumeration for C++ overloaded operators.
static QualType getPointeeType(const MemRegion *R)
__DEVICE__ int min(int __a, int __b)
mlir::Value createAdd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs, OverflowFlags flags=OverflowFlags::None)
cir::FenvAttr getConstrainedFPAttr()
Build the #cir.fenv attribute describing the constrained floating-point environment currently in effe...
mlir::Value createSub(mlir::Location loc, mlir::Value lhs, mlir::Value rhs, OverflowFlags flags=OverflowFlags::None)
cir::ConstantOp getNullValue(mlir::Type ty, mlir::Location loc)
cir::ConstantOp getConstant(mlir::Location loc, mlir::TypedAttr attr)
cir::SignBitOp createSignBit(mlir::Location loc, mlir::Value val)
mlir::Value createIntToPtr(mlir::Value src, mlir::Type newTy)
mlir::Value createPtrToInt(mlir::Value src, mlir::Type newTy)
cir::CallOp createCallOp(mlir::Location loc, mlir::SymbolRefAttr callee, mlir::Type returnType, mlir::ValueRange operands, llvm::ArrayRef< mlir::NamedAttribute > attrs={}, llvm::ArrayRef< mlir::NamedAttrList > argAttrs={}, llvm::ArrayRef< mlir::NamedAttribute > resAttrs={}, cir::CallingConv callingConv=cir::CallingConv::C)
cir::ConstantOp getNullPtr(mlir::Type ty, mlir::Location loc)
mlir::Value createShiftLeft(mlir::Location loc, mlir::Value lhs, unsigned bits)
mlir::Value createAlloca(mlir::Location loc, cir::PointerType addrType, llvm::StringRef name, mlir::IntegerAttr alignment, mlir::Value dynAllocSize)
mlir::Value createIntCast(mlir::Value src, mlir::Type newTy)
cir::FastMathFlagsAttr getFastMathFlagsAttr()
Returns a null attribute when no fast-math flags are set.
mlir::Value createBitcast(mlir::Value src, mlir::Type newTy)
cir::CmpOp createCompare(mlir::Location loc, cir::CmpOpKind kind, 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)
mlir::TypedAttr getZeroInitAttr(mlir::Type ty)
cir::PointerType getVoidPtrTy(clang::LangAS langAS=clang::LangAS::Default)
mlir::Value createAddrSpaceCast(mlir::Location loc, mlir::Value src, mlir::Type newTy)
cir::BoolType getBoolTy()
llvm::TypeSize getTypeSizeInBits(mlir::Type ty) const
static llvm::SmallVector< RecordMemberKind > getAllDataKinds(llvm::ArrayRef< mlir::Type > members)
One Data kind per member.
Definition CIRTypes.cpp:151
APSInt & getInt()
Definition APValue.h:577
bool isFloat() const
Definition APValue.h:550
bool isInt() const
Definition APValue.h:549
APFloat & getFloat()
Definition APValue.h:591
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
unsigned getIntWidth(QualType T) const
CanQualType VoidPtrTy
Builtin::Context & BuiltinInfo
Definition ASTContext.h:857
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
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.
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:974
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
@ GE_None
No error.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:238
bool shouldGenerateFPMathIntrinsic(unsigned BuiltinID, llvm::Triple Trip, std::optional< bool > ErrnoOverwritten, bool MathErrnoEnabled, bool HasOptNoneAttr, bool IsOptimizationEnabled) const
Determine whether we can generate LLVM intrinsics for the given builtin ID, based on whether it has s...
Definition Builtins.cpp:247
bool isLibFunction(unsigned ID) const
Return true if this is a builtin for a libc/libm function, with a "__builtin_" prefix (e....
Definition Builtins.h:312
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:94
mlir::Value getPointer() const
Definition Address.h:98
mlir::Type getElementType() const
Definition Address.h:125
Address withElementType(CIRGenBuilderTy &builder, mlir::Type ElemTy) const
Return address with different element type, a bitcast pointer, and the same alignment.
clang::CharUnits getAlignment() const
Definition Address.h:138
Address withAlignment(clang::CharUnits newAlignment) const
Return address with different alignment, but same pointer and element type.
Definition Address.h:89
mlir::Value emitRawPointer() const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:112
cir::PointerType getUInt8PtrTy()
cir::StoreOp createStore(mlir::Location loc, mlir::Value val, Address dst, bool isVolatile=false, bool isNontemporal=false, mlir::IntegerAttr align={}, cir::SyncScopeKindAttr scope={}, cir::MemOrderAttr order={})
cir::StructType getAnonRecordTy(llvm::ArrayRef< mlir::Type > members, bool packed, llvm::ArrayRef< cir::RecordMemberKind > memberKinds)
Get a CIR anonymous struct type.
cir::ConstantOp getConstInt(mlir::Location loc, llvm::APSInt intVal)
static CIRGenCallee forDirect(mlir::Operation *funcPtr, const CIRGenCalleeInfo &abstractInfo=CIRGenCalleeInfo())
Definition CIRGenCall.h:92
mlir::Type convertType(clang::QualType t)
mlir::Value emitCheckedArgForAssume(const Expr *e)
Emits an argument for a call to a __builtin_assume.
static cir::TypeEvaluationKind getEvaluationKind(clang::QualType type)
Return the cir::TypeEvaluationKind of QualType type.
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...
const clang::LangOptions & getLangOpts() const
void emitTrap(mlir::Location loc, bool createNewBlock)
Emit a trap instruction, which is used to abort the program in an abnormal way, usually for debugging...
cir::CoroAllocOp emitCoroAllocBuiltinCall(const CallExpr *e)
mlir::Value emitComplexExpr(const Expr *e)
Emit the computation of the specified expression of complex type, returning the result.
const TargetInfo & getTarget() const
LValue emitLValue(const clang::Expr *e)
Emit code to compute a designator that specifies the location of the expression.
const clang::Decl * curFuncDecl
cir::CoroNoopOp emitCoroNoopBuiltinCall(const CallExpr *e)
mlir::Value evaluateExprAsBool(const clang::Expr *e)
Perform the usual unary conversions on the specified expression and compare the result against zero,...
cir::CoroSuspendOp emitCoroSuspendBuiltinCall(const CallExpr *e)
LValue makeNaturalAlignAddrLValue(mlir::Value val, QualType ty)
mlir::Location getLoc(clang::SourceLocation srcLoc)
Helpers to convert Clang's SourceLocation to a MLIR Location.
void emitCallArgs(CallArgList &args, PrototypeWrapper prototype, llvm::iterator_range< clang::CallExpr::const_arg_iterator > argRange, AbstractCallee callee=AbstractCallee(), unsigned paramsToSkip=0, EvaluationOrder order=EvaluationOrder::Default)
cir::CoroBeginOp emitCoroBeginBuiltinCall(const CallExpr *e)
mlir::Value performAddrSpaceCast(mlir::Value v, mlir::Type destTy) const
cir::CoroFreeOp emitCoroFreeBuiltin(const CallExpr *e)
mlir::Value evaluateOrEmitBuiltinObjectSize(const clang::Expr *e, unsigned type, cir::IntType resType, mlir::Value emittedE, bool isDynamic)
std::optional< mlir::Value > emitRISCVBuiltinExpr(unsigned builtinID, const CallExpr *expr)
void checkTargetFeatures(const clang::CallExpr *e, const clang::FunctionDecl *targetDecl)
Emit a diagnostic if the target features required by targetDecl are not available in the calling func...
mlir::Value emitBuiltinObjectSize(const clang::Expr *e, unsigned type, cir::IntType resType, mlir::Value emittedE, bool isDynamic)
Returns a Value corresponding to the size of the given expression by emitting a cir....
mlir::Value makeBinaryAtomicValue(cir::AtomicFetchKind kind, const clang::CallExpr *expr, mlir::Type *originalArgType=nullptr, mlir::Value *emittedArgValue=nullptr, cir::MemOrder ordering=cir::MemOrder::SequentiallyConsistent)
Utility to insert an atomic instruction based on Intrinsic::ID and the expression node.
std::optional< mlir::Value > emitTargetBuiltinExpr(unsigned builtinID, const clang::CallExpr *e, ReturnValueSlot &returnValue)
mlir::Value emitDevicePrintfCallExpr(const CallExpr *expr)
Emit a device-side printf call for GPU targets.
clang::SanitizerSet sanOpts
Sanitizers enabled for this function.
cir::FastMathFlagsAttr getFastMathFlagsAttr(cir::FastMathFlags fastMathFlags)
Create a CIR fast-math attribute from the specified flags.
void emitUnreachable(clang::SourceLocation loc, bool createNewBlock)
Emit a reached-unreachable diagnostic if loc is valid and runtime checking is enabled.
cir::FastMathFlags getCurrentFastMathFlags() const
Convert the active Clang floating-point options to CIR fast-math flags.
cir::CoroPromiseOp emitCoroPromiseBuiltinCall(const CallExpr *e)
void emitStoreOfScalar(mlir::Value value, Address addr, bool isVolatile, clang::QualType ty, LValueBaseInfo baseInfo, bool isInit=false, bool isNontemporal=false)
RValue getUndefRValue(clang::QualType ty)
Get an appropriate 'undef' rvalue for the given type.
Address returnValue
The temporary alloca to hold the return value.
std::optional< mlir::Value > emitX86BuiltinExpr(unsigned builtinID, const CallExpr *expr)
cir::CoroDestroyOp emitCoroDestroyBuiltinCall(const CallExpr *e)
cir::CoroEndOp emitCoroEndBuiltinCall(const CallExpr *e)
const clang::Decl * curCodeDecl
This is the inner-most code context, which includes blocks.
std::optional< mlir::Value > emitAMDGPUBuiltinExpr(unsigned builtinID, const CallExpr *expr)
Emit a call to an AMDGPU builtin function.
std::optional< mlir::Value > emitAArch64BuiltinExpr(unsigned builtinID, const CallExpr *expr, ReturnValueSlot returnValue, llvm::Triple::ArchType arch)
llvm::SmallDenseMap< const ParmVarDecl *, const ImplicitParamDecl * > sizeArguments
If a ParmVarDecl had the pass_object_size attribute, this will contain a mapping from said ParmVarDec...
void emitVAEnd(mlir::Value vaList)
Emits the end of a CIR variable-argument operation (cir.va_start)
mlir::Value emitToMemory(mlir::Value value, clang::QualType ty)
Given a value and its clang type, returns the value casted to its memory representation.
mlir::Value emitScalarExpr(const clang::Expr *e, bool ignoreResultAssign=false)
Emit the computation of the specified expression of scalar type.
void emitAtomicExprWithMemOrder(const EmittedOrderOrScope &order, bool isStore, bool isLoad, bool isFence, llvm::function_ref< void(cir::MemOrder)> emitAtomicOp)
mlir::Value emitAtomicCmpXchg(const clang::CallExpr *expr, bool returnBool, cir::MemOrder successOrder=cir::MemOrder::SequentiallyConsistent, cir::MemOrder failureOrder=cir::MemOrder::SequentiallyConsistent, cir::SyncScopeKind scope=cir::SyncScopeKind::System)
Emit cir.atomic.cmpxchg.
CIRGenBuilderTy & getBuilder()
void emitVAStart(mlir::Value vaList)
Emits the start of a CIR variable-argument operation (cir.va_start)
cir::FuncType getIntrinsicType(llvm::Intrinsic::ID id, llvm::ArrayRef< mlir::Type > overloadTys={})
Return the CIR signature of the LLVM intrinsic id, resolving its overloaded types to overloadTys.
void emitNonNullArgCheck(RValue rv, QualType argType, SourceLocation argLoc, AbstractCallee ac, unsigned paramNum)
Create a check for a function parameter that may potentially be declared as non-null.
mlir::MLIRContext & getMLIRContext()
mlir::Value emitLoadOfScalar(LValue lvalue, SourceLocation loc)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
DeclMapTy localDeclMap
This keeps track of the CIR allocas or globals for local C declarations.
std::optional< mlir::Value > emitNVPTXBuiltinExpr(unsigned builtinID, const CallExpr *expr)
Emit a call to an NVPTX builtin function.
RValue emitCall(const CIRGenFunctionInfo &funcInfo, const CIRGenCallee &callee, ReturnValueSlot returnValue, const CallArgList &args, cir::CIRCallOpInterface *callOp, bool isMustTail, SourceRange clangLoc)
mlir::Value emitAlignmentAssumption(mlir::Value ptrValue, QualType ty, SourceLocation loc, SourceLocation assumptionLoc, int64_t alignment, mlir::Value offsetValue=nullptr)
std::optional< mlir::Value > emitSPIRVBuiltinExpr(unsigned builtinID, const CallExpr *expr)
Emit a call to a SPIR-V builtin function.
LValue makeAddrLValue(Address addr, QualType ty, AlignmentSource source=AlignmentSource::Type)
cir::CoroSizeOp emitCoroSizeBuiltinCall(const CallExpr *e)
RValue emitNewOrDeleteBuiltinCall(const FunctionProtoType *type, const CallExpr *callExpr, OverloadedOperatorKind op)
cir::CoroDoneOp emitCoroDoneBuiltinCall(const CallExpr *e)
cir::CoroResumeOp emitCoroResumeBuiltinCall(const CallExpr *e)
cir::CoroAlignOp emitCoroAlignBuiltinCall(const CallExpr *e)
CIRGenFunction(CIRGenModule &cgm, CIRGenBuilderTy &builder, bool suppressNewContext=false)
cir::CoroIdOp emitCoroIDBuiltinCall(const CallExpr *e)
clang::ASTContext & getContext() const
RValue emitBuiltinExpr(const clang::GlobalDecl &gd, unsigned builtinID, const clang::CallExpr *e, ReturnValueSlot returnValue)
mlir::Value emitFromMemory(mlir::Value value, clang::QualType ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
Address emitVAListRef(const Expr *e)
Build a "reference" to a va_list; this is either the address or the value of the expression,...
void emitIgnoredExpr(const clang::Expr *e)
Emit code to compute the specified expression, ignoring the result.
mlir::Value emitScalarOrConstFoldImmArg(unsigned iceArguments, unsigned idx, const Expr *argExpr)
mlir::Value emitVAArg(VAArgExpr *ve)
Generate code to get an argument from the passed in pointer and update it accordingly.
RValue emitRotate(const CallExpr *e, bool isRotateLeft)
llvm::StringRef getMangledName(clang::GlobalDecl gd)
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
clang::ASTContext & getASTContext() const
mlir::Type convertType(clang::QualType type)
clang::DiagnosticsEngine & getDiags() const
const clang::TargetInfo & getTarget() const
cir::FuncOp getBuiltinLibFunction(const FunctionDecl *fd, unsigned builtinID)
Given a builtin id for a function like "__builtin_fabsf", return a Function* for "fabsf".
const llvm::Triple & getTriple() const
const cir::CIRDataLayout & getDataLayout() const
cir::FuncOp createRuntimeFunction(cir::FuncType ty, llvm::StringRef name, mlir::NamedAttrList extraAttrs={}, bool isLocal=false, bool assumeConvergent=false)
const clang::CodeGenOptions & getCodeGenOpts() const
const clang::LangOptions & getLangOpts() const
cir::FuncOp getOrCreateCIRFunction(llvm::StringRef mangledName, mlir::Type funcType, clang::GlobalDecl gd, bool forVTable, bool dontDefer=false, bool isThunk=false, ForDefinition_t isForDefinition=NotForDefinition, mlir::NamedAttrList extraAttrs={})
const TargetCIRGenInfo & getTargetCIRGenInfo()
mlir::Value getPointer() const
void setNontemporal(bool v)
This trivial value class is used to represent the result of an expression that is evaluated.
Definition CIRGenValue.h:33
static RValue get(mlir::Value v)
Definition CIRGenValue.h:83
static RValue getComplex(mlir::Value v)
Definition CIRGenValue.h:91
mlir::Value getValue() const
Return the value of this scalar value.
Definition CIRGenValue.h:57
bool isScalar() const
Definition CIRGenValue.h:49
bool isIgnored() const
Definition CIRGenValue.h:52
static RValue getIgnored()
Definition CIRGenValue.h:78
Contains the address where the return value of a function can be stored, and whether the address is v...
Definition CIRGenCall.h:262
virtual bool supportsLibCall() const
Returns true if the target supports math library calls.
Definition TargetInfo.h:58
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
bool hasStoredFPFeatures() const
Definition Expr.h:3171
SourceLocation getBeginLoc() const
Definition Expr.h:3346
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
Expr * getCallee()
Definition Expr.h:3159
FPOptionsOverride getFPFeatures() const
Definition Expr.h:3311
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3203
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3305
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition CharUnits.h:177
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool hasAttr() const
Definition DeclBase.h:586
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:240
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
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,...
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3134
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
bool isPRValue() const
Definition Expr.h:287
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...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3728
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
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
Represents difference between two FPOptions values.
LangOptions::FPExceptionModeKind getExceptionMode() const
Represents a function declaration or definition.
Definition Decl.h:2082
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2974
QualType getReturnType() const
Definition Decl.h:3022
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
const Decl * getDecl() const
Definition GlobalDecl.h:115
@ FPE_Ignore
Assume that floating-point exceptions are masked.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8662
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
bool requiresBuiltinLaunder(const ASTContext &Context) const
Returns true if this type requires laundering by checking if it is a dynamic class type,...
Definition Type.cpp:5820
Encodes a location in the source.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
Exposes information about the current target.
Definition TargetInfo.h:228
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual bool isCLZForZeroUndef() const
The __builtin_clz* and __builtin_ctz* built-in functions are specified to have undefined results for ...
unsigned getSuitableAlign() const
Return the alignment that is the largest alignment ever used for any scalar/SIMD data type on the tar...
Definition TargetInfo.h:743
bool isBlockPointerType() const
Definition TypeBase.h:8835
bool isBooleanType() const
Definition TypeBase.h:9341
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:857
bool isPointerType() const
Definition TypeBase.h:8815
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9326
bool isExtVectorBoolType() const
Definition TypeBase.h:8962
bool isObjCObjectPointerType() const
Definition TypeBase.h:8994
bool isFloatingType() const
Definition Type.cpp:2519
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:2462
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:5026
const Expr * getSubExpr() const
Definition Expr.h:5046
QualType getType() const
Definition Decl.h:725
Represents a GCC generic vector type.
Definition TypeBase.h:4398
bool isMatchingAddressSpace(mlir::ptr::MemorySpaceAttrInterface cirAS, clang::LangAS as)
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
llvm::StringRef getTargetBuiltinLibFunctionName(unsigned BuiltinID, const TargetInfo &Target)
Returns the library function name that should be called for the library builtin BuiltinID when the ta...
void checkTargetFeatures(ASTContext &Ctx, DiagnosticsEngine &Diags, const LangOptions &LangOpts, const CallExpr *E, const FunctionDecl *Caller, const FunctionDecl *TargetDecl)
Check that a call to a target-specific builtin has the required target features enabled in the caller...
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
U cast(CodeGen::Address addr)
Definition Address.h:327
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
static bool builtinCheckKind()
static bool addressSpace()
static bool builtinCallF128()
static bool isPPC_FP128Ty()
static bool emitCheckedInBoundsGEP()
static bool opFuncCallingConv()
static bool countedBySize()
static bool fastMathFlags()
static bool builtinBitCountExpr()
static bool builtinCall()
static bool generateDebugInfo()
An emitted atomic order or scope value with optional constant evaluation.
cir::PointerType allocaInt8PtrTy
void* in alloca address space
mlir::ptr::MemorySpaceAttrInterface getCIRAllocaAddressSpace() const
cir::PointerType voidPtrTy
void* in address space 0
bool hasLValue() const
Definition CIRGenCall.h:218
RValue getKnownRValue() const
Definition CIRGenCall.h:229
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
bool hasSideEffects() const
Return true if the evaluated expression has side effects.
Definition Expr.h:661
#define conj(__x)
Definition tgmath.h:1299
#define floor(__x)
Definition tgmath.h:722
#define ceil(__x)
Definition tgmath.h:601