// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --version 3
// RUN: %clang_cc1 -triple=x86_64 -emit-llvm -o - -std=c23 %s | FileCheck %s

#include <stdckdint.h>
#include <stdint.h>

// CHECK-LABEL: define dso_local void @test_add_overflow_to64(
// CHECK-SAME: ) #[[ATTR0:[0-9]+]] {
// CHECK-NEXT:  entry:
// CHECK-NEXT:    [[RESULT64:%.*]] = alloca i64, align 8
// CHECK-NEXT:    [[FLAG_ADD:%.*]] = alloca i8, align 1
// CHECK-NEXT:    store i64 0, ptr [[RESULT64]], align 8
// CHECK-NEXT:    [[TMP0:%.*]] = call { i64, i1 } @llvm.sadd.with.overflow.i64(i64 2147483647, i64 1)
// CHECK-NEXT:    [[TMP1:%.*]] = extractvalue { i64, i1 } [[TMP0]], 1
// CHECK-NEXT:    [[TMP2:%.*]] = extractvalue { i64, i1 } [[TMP0]], 0
// CHECK-NEXT:    store i64 [[TMP2]], ptr [[RESULT64]], align 8
// CHECK-NEXT:    [[FROMBOOL:%.*]] = zext i1 [[TMP1]] to i8
// CHECK-NEXT:    store i8 [[FROMBOOL]], ptr [[FLAG_ADD]], align 1
// CHECK-NEXT:    ret void
//
void test_add_overflow_to64() {
  int64_t result64 = 0;
  bool flag_add = ckd_add(&result64, INT32_MAX, 1);
}

// CHECK-LABEL: define dso_local void @test_sub_overflow(
// CHECK-SAME: ) #[[ATTR0]] {
// CHECK-NEXT:  entry:
// CHECK-NEXT:    [[RESULT32:%.*]] = alloca i32, align 4
// CHECK-NEXT:    [[FLAG_SUB:%.*]] = alloca i8, align 1
// CHECK-NEXT:    store i32 0, ptr [[RESULT32]], align 4
// CHECK-NEXT:    [[TMP0:%.*]] = call { i32, i1 } @llvm.ssub.with.overflow.i32(i32 2147483647, i32 -1)
// CHECK-NEXT:    [[TMP1:%.*]] = extractvalue { i32, i1 } [[TMP0]], 1
// CHECK-NEXT:    [[TMP2:%.*]] = extractvalue { i32, i1 } [[TMP0]], 0
// CHECK-NEXT:    store i32 [[TMP2]], ptr [[RESULT32]], align 4
// CHECK-NEXT:    [[FROMBOOL:%.*]] = zext i1 [[TMP1]] to i8
// CHECK-NEXT:    store i8 [[FROMBOOL]], ptr [[FLAG_SUB]], align 1
// CHECK-NEXT:    ret void
//
void test_sub_overflow() {
  int32_t result32 = 0;
  bool flag_sub = ckd_sub(&result32, INT32_MAX, -1);
}

// CHECK-LABEL: define dso_local void @test_mul_normal(
// CHECK-SAME: ) #[[ATTR0]] {
// CHECK-NEXT:  entry:
// CHECK-NEXT:    [[A:%.*]] = alloca i32, align 4
// CHECK-NEXT:    [[RESULT:%.*]] = alloca i32, align 4
// CHECK-NEXT:    [[FLAG_MUL:%.*]] = alloca i8, align 1
// CHECK-NEXT:    store i32 3, ptr [[A]], align 4
// CHECK-NEXT:    store i32 0, ptr [[RESULT]], align 4
// CHECK-NEXT:    [[TMP0:%.*]] = load i32, ptr [[A]], align 4
// CHECK-NEXT:    [[TMP1:%.*]] = call { i32, i1 } @llvm.smul.with.overflow.i32(i32 [[TMP0]], i32 2)
// CHECK-NEXT:    [[TMP2:%.*]] = extractvalue { i32, i1 } [[TMP1]], 1
// CHECK-NEXT:    [[TMP3:%.*]] = extractvalue { i32, i1 } [[TMP1]], 0
// CHECK-NEXT:    store i32 [[TMP3]], ptr [[RESULT]], align 4
// CHECK-NEXT:    [[FROMBOOL:%.*]] = zext i1 [[TMP2]] to i8
// CHECK-NEXT:    store i8 [[FROMBOOL]], ptr [[FLAG_MUL]], align 1
// CHECK-NEXT:    ret void
//
void test_mul_normal() {
  int a = 3;
  int result = 0;
  bool flag_mul = ckd_mul(&result, a, 2);
}
