name: MLIR

on:
  push:
    branches:
    - main
  pull_request:
    branches:
    - main
  merge_group:

jobs:
  build-linux:
    name: MLIR ${{ matrix.build }} ${{ matrix.os }}
    runs-on: ${{ matrix.os }}

    strategy:
      fail-fast: false
      matrix:
        build: ["Release", "Debug"] # "RelWithDebInfo"
        llbuild: ["Release"]
        os: [openstack22]

    timeout-minutes: 500

    steps:
    - name: Install dependencies
      run: |
          sudo apt-get update
          sudo apt-get install -y binutils ninja-build cmake gcc g++ python3 python3-dev

    - uses: actions/checkout@v4
      with:
        path: 'Enzyme'

    - uses: actions/checkout@v4
      with:
        repository: 'llvm/llvm-project'
        ref: 'ff24e9a19e3db330dd6412aac9d1d6c0b416697f'
        path: 'llvm-project'

    - name: Get MLIR commit hash
      id: mlir-commit
      working-directory: 'llvm-project'
      run: echo "sha_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT

    - name: Cache MLIR
      id: cache-mlir
      uses: actions/cache@v4
      with:
        path: llvm-project/mlir-build
        key: ${{ matrix.llbuild }}-${{ matrix.os }}-mlir-${{ steps.mlir-commit.outputs.sha_short }}

    - name: MLIR build
      if: steps.cache-mlir.outputs.cache-hit != 'true'
      working-directory: 'llvm-project'
      run: |
        mkdir mlir-build && cd mlir-build && cmake ../llvm -GNinja -DLLVM_ENABLE_PROJECTS="llvm;clang;mlir;openmp" -DCMAKE_BUILD_TYPE=${{ matrix.llbuild }} \
        -DLLVM_ENABLE_ASSERTIONS=ON -DLLVM_TARGETS_TO_BUILD=X86 \
        -DLLVM_USE_LINKER=gold -DLLVM_PARALLEL_LINK_JOBS=2 \
        -DCLANG_ENABLE_STATIC_ANALYZER=OFF -DCLANG_ENABLE_ARCMT=OFF \
        -DLLVM_OPTIMIZED_TABLEGEN=ON && ninja || echo "already built"

    - name: Enzyme build
      working-directory: 'Enzyme'
      run: |
          mkdir enzyme-build && cd enzyme-build
          cmake ../enzyme -GNinja -DCMAKE_BUILD_TYPE=${{ matrix.build }} -DLLVM_DIR=${{ github.workspace }}/llvm-project/mlir-build -DENZYME_MLIR=ON
          ninja

    - name: Check enzyme-mlir
      working-directory: 'Enzyme/enzyme-build'
      run: ninja check-enzymemlir

