source
stringlengths
3
92
c
stringlengths
26
2.25M
GB_binop__ldexp_fp64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__ldexp_fp64) // A.*B function (eWiseMult): GB (_AemultB_08__ldexp_fp64) // A.*B function (eWiseMult): GB (_AemultB_02__ldexp_fp64) // A.*B function (eWiseMult): GB (_AemultB_04__ldexp_fp64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__ldexp_fp64) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__ldexp_fp64) // C+=b function (dense accum): GB (_Cdense_accumb__ldexp_fp64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__ldexp_fp64) // C=scalar+B GB (_bind1st__ldexp_fp64) // C=scalar+B' GB (_bind1st_tran__ldexp_fp64) // C=A+scalar GB (_bind2nd__ldexp_fp64) // C=A'+scalar GB (_bind2nd_tran__ldexp_fp64) // C type: double // A type: double // B,b type: double // BinaryOp: cij = ldexp (aij, bij) #define GB_ATYPE \ double #define GB_BTYPE \ double #define GB_CTYPE \ double // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ double aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ double bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ double t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = ldexp (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LDEXP || GxB_NO_FP64 || GxB_NO_LDEXP_FP64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__ldexp_fp64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__ldexp_fp64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__ldexp_fp64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type double double bwork = (*((double *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double *restrict Cx = (double *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double *restrict Cx = (double *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__ldexp_fp64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__ldexp_fp64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__ldexp_fp64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__ldexp_fp64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__ldexp_fp64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__ldexp_fp64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double *Cx = (double *) Cx_output ; double x = (*((double *) x_input)) ; double *Bx = (double *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; double bij = GBX (Bx, p, false) ; Cx [p] = ldexp (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__ldexp_fp64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; double *Cx = (double *) Cx_output ; double *Ax = (double *) Ax_input ; double y = (*((double *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; double aij = GBX (Ax, p, false) ; Cx [p] = ldexp (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ double aij = GBX (Ax, pA, false) ; \ Cx [pC] = ldexp (x, aij) ; \ } GrB_Info GB (_bind1st_tran__ldexp_fp64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ double #if GB_DISABLE return (GrB_NO_VALUE) ; #else double x = (*((const double *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ double } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ double aij = GBX (Ax, pA, false) ; \ Cx [pC] = ldexp (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__ldexp_fp64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double y = (*((const double *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
app.c
/** * Christina Giannoula * cgiannoula: christina.giann@gmail.com */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <dpu.h> #include <dpu_log.h> #include <unistd.h> #include <getopt.h> #include <assert.h> #include <math.h> #include <omp.h> #include "../support/common.h" #include "../support/matrix.h" #include "../support/params.h" #include "../support/partition.h" #include "../support/timer.h" #include "../support/utils.h" // Define the DPU Binary path as DPU_BINARY here. #ifndef DPU_BINARY #define DPU_BINARY "./bin/spmv_dpu" #endif #define DPU_CAPACITY (64 << 20) // A DPU's capacity is 64 MB /* * Main Structures: * 1. Matrices * 2. Input vector * 3. Output vector * 4. Help structures for data partitioning */ static struct RBDBCSRMatrix* A; static struct RBDCSRMatrix* B; static struct COOMatrix* C; static val_dt* x; static val_dt* y; static val_dt* z; static struct partition_info_t *part_info; /** * @brief Specific information for each DPU */ struct dpu_info_t { uint32_t block_rows_per_dpu; uint32_t prev_block_rows_dpu; uint32_t cols_per_dpu; uint32_t block_start; uint32_t blocks; uint32_t blocks_pad; uint32_t prev_blocks_dpu; uint32_t ptr_offset; uint32_t merge; }; struct dpu_info_t *dpu_info; /** * @brief find the dpus_per_row_partition * @param factor n to create partitions * @param column_partitions to create vert_partitions * @param horz_partitions to return the 2D partitioning */ void find_partitions(uint32_t n, uint32_t *horz_partitions, uint32_t vert_partitions) { uint32_t dpus_per_vert_partition = n / vert_partitions; *horz_partitions = dpus_per_vert_partition; } /** * @brief initialize input vector * @param pointer to input vector and vector size */ void init_vector(val_dt* vec, uint32_t size) { for(unsigned int i = 0; i < size; ++i) { vec[i] = (val_dt) (i%4+1); } } /** * @brief compute output in the host CPU */ static void spmv_host(val_dt* y, struct RBDBCSRMatrix *A, val_dt* x) { uint64_t total_blocks = 0; for (uint32_t c = 0; c < A->vert_partitions; c++) { uint32_t ptr_offset = c * (A->num_block_rows + 1); uint32_t col_offset = c * A->tile_width; for(uint64_t n=0; n < A->num_block_rows; n++) { for(uint64_t i=A->browptr[ptr_offset + n]; i<A->browptr[ptr_offset + n+1]; i++){ uint64_t j = A->bcolind[total_blocks + i]; for(uint64_t blr=0; blr < A->row_block_size; blr++){ val_dt acc = 0; for(uint64_t blc=0; blc < A->col_block_size; blc++) { acc += A->bval[(total_blocks + i) * A->col_block_size * A->row_block_size + blr * A->col_block_size + blc] * x[col_offset + j * A->col_block_size + blc]; } y[n * A->row_block_size + blr] += acc; } } } total_blocks += A->blocks_per_vert_partition[c]; } } /** * @brief main of the host application */ int main(int argc, char **argv) { struct Params p = input_params(argc, argv); struct dpu_set_t dpu_set, dpu; uint32_t nr_of_dpus; uint32_t nr_of_ranks; // Allocate DPUs and load binary DPU_ASSERT(dpu_alloc(NR_DPUS, NULL, &dpu_set)); DPU_ASSERT(dpu_load(dpu_set, DPU_BINARY, NULL)); DPU_ASSERT(dpu_get_nr_dpus(dpu_set, &nr_of_dpus)); DPU_ASSERT(dpu_get_nr_ranks(dpu_set, &nr_of_ranks)); printf("[INFO] Allocated %d DPU(s)\n", nr_of_dpus); printf("[INFO] Allocated %d Rank(s)\n", nr_of_ranks); printf("[INFO] Allocated %d TASKLET(s) per DPU\n", NR_TASKLETS); unsigned int i; // Initialize input data C = readCOOMatrix(p.fileName); sortCOOMatrix(C); uint32_t horz_partitions = 0; uint32_t vert_partitions = p.vert_partitions; find_partitions(nr_of_dpus, &horz_partitions, p.vert_partitions); printf("[INFO] %dx%d Matrix Partitioning\n\n", horz_partitions, vert_partitions); B = coo2rbdcsr(C, horz_partitions, vert_partitions); freeCOOMatrix(C); A = rbdcsr2rbdbcsr(B, p.row_blsize, p.col_blsize); countNNZperBlockRBDBCSRMatrix(A); freeRBDCSRMatrix(B); // Initialize partition data part_info = partition_init(A, nr_of_dpus, p.max_nranks, NR_TASKLETS); #if FG_TRANS struct dpu_set_t rank; uint32_t each_rank; DPU_RANK_FOREACH(dpu_set, rank, each_rank){ uint32_t nr_dpus_in_rank; DPU_ASSERT(dpu_get_nr_dpus(rank, &nr_dpus_in_rank)); part_info->active_dpus_per_rank[each_rank+1] = nr_dpus_in_rank; } int sum = 0; for(int i=0; i < p.max_nranks+1; i++) { part_info->accum_dpus_ranks[i] = part_info->active_dpus_per_rank[i] + sum; sum += part_info->active_dpus_per_rank[i]; } #endif // Initialize help data - Padding needed uint32_t ncols_pad = A->ncols + A->tile_width + A->col_block_size; uint32_t tile_width_pad = A->num_block_cols * A->col_block_size; uint32_t nrows_pad = A->nrows + A->row_block_size; if (ncols_pad % (8 / byte_dt) != 0) ncols_pad = ncols_pad + ((8 / byte_dt) - (ncols_pad % (8 / byte_dt))); if (tile_width_pad % (8 / byte_dt) != 0) tile_width_pad = tile_width_pad + ((8 / byte_dt) - (tile_width_pad % (8 / byte_dt))); #if INT8 if (tile_width_pad % 2 != 0) tile_width_pad++; #endif if (nrows_pad % (8 / byte_dt) != 0) nrows_pad = nrows_pad + ((8 / byte_dt) - (nrows_pad % (8 / byte_dt))); // Allocate input vector x = (val_dt *) malloc(ncols_pad * sizeof(val_dt)); // Allocate output vector z = (val_dt *) calloc(nrows_pad, sizeof(val_dt)); // Initialize input vector with arbitrary data init_vector(x, ncols_pad); // Load-balance blocks (at block-row granularity) across DPUs of the same vertical partition partition_by_block(A, part_info); // Initialize help data dpu_info = (struct dpu_info_t *) malloc(nr_of_dpus * sizeof(struct dpu_info_t)); dpu_arguments_t *input_args = (dpu_arguments_t *) malloc(nr_of_dpus * sizeof(dpu_arguments_t)); // Max limits for parallel transfers uint64_t max_block_rows_per_dpu = 0; uint64_t max_blocks_per_dpu = 0; // Timer for measurements Timer timer; i = 0; uint32_t acc_blocks = 0; uint32_t total_blocks = 0; DPU_FOREACH(dpu_set, dpu, i) { // Find padding for block rows and non-zero elements needed for CPU-DPU transfers uint32_t tile_horz_indx = i % A->horz_partitions; uint32_t tile_vert_indx = i / A->horz_partitions; uint32_t block_rows_per_dpu = part_info->brow_split[tile_vert_indx * (A->horz_partitions + 1) + tile_horz_indx + 1] - part_info->brow_split[tile_vert_indx * (A->horz_partitions + 1) + tile_horz_indx]; uint32_t block_rows_per_dpu_pad = part_info->brow_split[tile_vert_indx * (A->horz_partitions + 1) + tile_horz_indx + 1] - part_info->brow_split[tile_vert_indx * (A->horz_partitions + 1) + tile_horz_indx] + 1; uint32_t prev_block_rows_dpu = part_info->brow_split[tile_vert_indx * (A->horz_partitions + 1) + tile_horz_indx]; if (block_rows_per_dpu_pad > max_block_rows_per_dpu) max_block_rows_per_dpu = block_rows_per_dpu_pad; unsigned int blocks, blocks_pad; blocks = A->browptr[tile_vert_indx * (A->num_block_rows + 1) + prev_block_rows_dpu + block_rows_per_dpu] - A->browptr[tile_vert_indx * (A->num_block_rows + 1) + prev_block_rows_dpu]; assert(blocks == part_info->blocks_dpu[i]); if (blocks % 2 != 0) // bcolind blocks_pad = blocks + 1; else blocks_pad = blocks; if (blocks_pad > max_blocks_per_dpu) max_blocks_per_dpu = blocks_pad; // Keep information per DPU dpu_info[i].block_rows_per_dpu = block_rows_per_dpu; dpu_info[i].prev_block_rows_dpu = prev_block_rows_dpu; dpu_info[i].cols_per_dpu = A->tile_width; dpu_info[i].blocks = blocks; dpu_info[i].blocks_pad = blocks_pad; dpu_info[i].prev_blocks_dpu = total_blocks; dpu_info[i].ptr_offset = tile_vert_indx * (A->num_block_rows + 1) + prev_block_rows_dpu; // Find input arguments per DPU input_args[i].block_rows = block_rows_per_dpu; input_args[i].tcols = tile_width_pad; input_args[i].row_block_size = A->row_block_size; input_args[i].col_block_size = A->col_block_size; #if BLNC_TSKLT_BLOCK // Load-balance blocks across tasklets partition_tsklt_by_block(A, part_info, i, NR_TASKLETS, nr_of_dpus, acc_blocks, prev_block_rows_dpu, block_rows_per_dpu, tile_vert_indx); #else // Load-balance nnzs across tasklets partition_tsklt_by_nnz(A, part_info, i, NR_TASKLETS, nr_of_dpus, acc_blocks, prev_block_rows_dpu, block_rows_per_dpu, tile_vert_indx); #endif uint32_t t; for (t = 0; t < NR_TASKLETS; t++) { // Find input arguments per tasklet input_args[i].start_block_row[t] = part_info->brow_split_tasklet[i * (NR_TASKLETS+2) + t]; input_args[i].end_block_row[t] = part_info->brow_split_tasklet[i * (NR_TASKLETS+2) + (t+1)]; } if (tile_horz_indx == (A->horz_partitions - 1)) acc_blocks += A->blocks_per_vert_partition[tile_vert_indx]; total_blocks += part_info->blocks_dpu[i]; } #if FG_TRANS // Find max number of block rows (subset of elements of the output vector) among DPUs of each rank DPU_RANK_FOREACH(dpu_set, rank, each_rank){ uint32_t max_block_rows_cur_rank = 0; uint32_t nr_dpus_in_rank; DPU_ASSERT(dpu_get_nr_dpus(rank, &nr_dpus_in_rank)); uint32_t start_dpu = part_info->accum_dpus_ranks[each_rank]; for (uint32_t k = 0; k < nr_dpus_in_rank; k++) { if (start_dpu + k >= nr_of_dpus) break; if (dpu_info[start_dpu + k].block_rows_per_dpu > max_block_rows_cur_rank) max_block_rows_cur_rank = dpu_info[start_dpu + k].block_rows_per_dpu; } if (max_block_rows_cur_rank % 2 != 0) max_block_rows_cur_rank++; part_info->max_block_rows_per_rank[each_rank] = (uint32_t) max_block_rows_cur_rank; } #endif // Initializations for parallel transfers with padding needed if (max_block_rows_per_dpu % 2 != 0) max_block_rows_per_dpu++; if (max_blocks_per_dpu % 2 != 0) max_blocks_per_dpu++; // Re-allocations for padding needed A->browptr = (uint32_t *) realloc(A->browptr, (max_block_rows_per_dpu * nr_of_dpus * sizeof(uint32_t))); A->bcolind = (uint32_t *) realloc(A->bcolind, (max_blocks_per_dpu * nr_of_dpus * sizeof(uint32_t))); A->bval = (val_dt *) realloc(A->bval, (max_blocks_per_dpu * A->row_block_size * A->col_block_size * nr_of_dpus * sizeof(val_dt))); y = (val_dt *) calloc((uint64_t) ((uint64_t) nr_of_dpus * (uint64_t) max_block_rows_per_dpu * A->row_block_size), sizeof(val_dt)); // Count total number of bytes to be transfered in MRAM of DPU unsigned long int total_bytes; total_bytes = ((max_block_rows_per_dpu) * sizeof(uint32_t)) + (max_blocks_per_dpu * sizeof(uint32_t)) + (max_blocks_per_dpu * A->row_block_size * A->col_block_size * sizeof(val_dt)) + (tile_width_pad * sizeof(val_dt)) + (max_block_rows_per_dpu * A->row_block_size * sizeof(val_dt)); assert(total_bytes <= DPU_CAPACITY && "Bytes needed exceeded MRAM size"); // Copy input arguments to DPUs i = 0; DPU_FOREACH(dpu_set, dpu, i) { input_args[i].max_block_rows = max_block_rows_per_dpu; input_args[i].max_blocks = max_blocks_per_dpu; DPU_ASSERT(dpu_prepare_xfer(dpu, input_args + i)); } DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_TO_DPU, "DPU_INPUT_ARGUMENTS", 0, sizeof(dpu_arguments_t), DPU_XFER_DEFAULT)); // Copy input matrix to DPUs startTimer(&timer, 0); // Copy Browptr i = 0; DPU_FOREACH(dpu_set, dpu, i) { DPU_ASSERT(dpu_prepare_xfer(dpu, A->browptr + dpu_info[i].ptr_offset)); } DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_TO_DPU, DPU_MRAM_HEAP_POINTER_NAME, (max_block_rows_per_dpu * A->row_block_size * sizeof(val_dt) + tile_width_pad * sizeof(val_dt)), max_block_rows_per_dpu * sizeof(uint32_t), DPU_XFER_DEFAULT)); // Copy Bcolind i = 0; total_blocks = 0; DPU_FOREACH(dpu_set, dpu, i) { DPU_ASSERT(dpu_prepare_xfer(dpu, A->bcolind + total_blocks)); total_blocks += part_info->blocks_dpu[i]; } DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_TO_DPU, DPU_MRAM_HEAP_POINTER_NAME, max_block_rows_per_dpu * A->row_block_size * sizeof(val_dt) + tile_width_pad * sizeof(val_dt) + max_block_rows_per_dpu * sizeof(uint32_t), max_blocks_per_dpu * sizeof(uint32_t), DPU_XFER_DEFAULT)); // Copy Bvalues i = 0; total_blocks = 0; DPU_FOREACH(dpu_set, dpu, i) { DPU_ASSERT(dpu_prepare_xfer(dpu, A->bval + ((uint64_t) total_blocks * A->row_block_size * A->col_block_size))); total_blocks += part_info->blocks_dpu[i]; } DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_TO_DPU, DPU_MRAM_HEAP_POINTER_NAME, max_block_rows_per_dpu * A->row_block_size * sizeof(val_dt) + tile_width_pad * sizeof(val_dt) + max_block_rows_per_dpu * sizeof(uint32_t) + max_blocks_per_dpu * sizeof(uint32_t), max_blocks_per_dpu * A->row_block_size * A->col_block_size * sizeof(val_dt), DPU_XFER_DEFAULT)); stopTimer(&timer, 0); // Copy input vector to DPUs startTimer(&timer, 1); i = 0; DPU_FOREACH(dpu_set, dpu, i) { uint32_t tile_vert_indx = i / A->horz_partitions; DPU_ASSERT(dpu_prepare_xfer(dpu, x + tile_vert_indx * A->tile_width)); } DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_TO_DPU, DPU_MRAM_HEAP_POINTER_NAME, max_block_rows_per_dpu * A->row_block_size * sizeof(val_dt), tile_width_pad * sizeof(val_dt), DPU_XFER_DEFAULT)); stopTimer(&timer, 1); // Run kernel on DPUs startTimer(&timer, 2); DPU_ASSERT(dpu_launch(dpu_set, DPU_SYNCHRONOUS)); stopTimer(&timer, 2); #if LOG // Display DPU Log (default: disabled) DPU_FOREACH(dpu_set, dpu) { DPU_ASSERT(dpulog_read_for_dpu(dpu.dpu, stdout)); } #endif // Retrieve results for output vector from DPUs startTimer(&timer, 3); #if CG_TRANS // Coarse-grained data transfers in the output vector i = 0; uint32_t block_rows_footprint = 0; DPU_FOREACH(dpu_set, dpu, i) { DPU_ASSERT(dpu_prepare_xfer(dpu, y + (i * max_block_rows_per_dpu * A->row_block_size))); } DPU_ASSERT(dpu_push_xfer(dpu_set, DPU_XFER_FROM_DPU, DPU_MRAM_HEAP_POINTER_NAME, 0, max_block_rows_per_dpu * A->row_block_size * sizeof(val_dt), DPU_XFER_DEFAULT)); #endif #if FG_TRANS // Fine-grained data transfers in the output vector at rank granularity i = 0; DPU_FOREACH(dpu_set, dpu, i) { DPU_ASSERT(dpu_prepare_xfer(dpu, y + (i * max_block_rows_per_dpu * A->row_block_size))); } i = 0; //struct dpu_set_t rank; DPU_RANK_FOREACH(dpu_set, rank) { DPU_ASSERT(dpu_push_xfer(rank, DPU_XFER_FROM_DPU, DPU_MRAM_HEAP_POINTER_NAME, 0, part_info->max_block_rows_per_rank[i] * A->row_block_size * sizeof(val_dt), DPU_XFER_ASYNC)); i++; } DPU_ASSERT(dpu_sync(dpu_set)); #endif stopTimer(&timer, 3); // Merge partial results to the host CPU startTimer(&timer, 4); uint32_t r, c, t, b; for (c = 0; c < A->vert_partitions; c++) { for (r = 0; r < A->horz_partitions; r++) { #pragma omp parallel for num_threads(p.nthreads) shared(A, z, y, max_block_rows_per_dpu, r, c) private(t, b) for (t = 0; t < part_info->brow_split[c * (A->horz_partitions + 1) + r+1] - part_info->brow_split[c * (A->horz_partitions + 1) + r]; t++) { for (b = 0; b < A->row_block_size; b++) { z[(part_info->brow_split[c * (A->horz_partitions + 1) + r] + t) * A->row_block_size + b] += y[(c * A->horz_partitions + r) * max_block_rows_per_dpu * A->row_block_size + t * A->row_block_size + b]; } } } } stopTimer(&timer, 4); // Print timing results printf("\n"); printf("Load Matrix "); printTimer(&timer, 0); printf("Load Input Vector "); printTimer(&timer, 1); printf("Kernel "); printTimer(&timer, 2); printf("Retrieve Output Vector "); printTimer(&timer, 3); printf("Merge Partial Results "); printTimer(&timer, 4); printf("\n\n"); #if CHECK_CORR // Check output startTimer(&timer, 4); val_dt *y_host = (val_dt *) calloc(nrows_pad, sizeof(val_dt)); spmv_host(y_host, A, x); bool status = true; i = 0; for (i = 0; i < A->nrows; i++) { if(y_host[i] != z[i]) { status = false; } } if (status) { printf("[" ANSI_COLOR_GREEN "OK" ANSI_COLOR_RESET "] Outputs are equal\n"); } else { printf("[" ANSI_COLOR_RED "ERROR" ANSI_COLOR_RESET "] Outputs differ!\n"); } free(y_host); #endif // Deallocation freeRBDBCSRMatrix(A); free(x); free(y); free(z); partition_free(part_info); DPU_ASSERT(dpu_free(dpu_set)); return 0; }
7709.c
/* POLYBENCH/GPU-OPENMP * * This file is a part of the Polybench/GPU-OpenMP suite * * Contact: * William Killian <killian@udel.edu> * * Copyright 2013, The University of Delaware */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4000. */ #include "covariance.h" /* Array initialization. */ static void init_array (int m, int n, DATA_TYPE *float_n, DATA_TYPE POLYBENCH_2D(data,M,N,m,n)) { int i, j; *float_n = 1.2; for (i = 0; i < M; i++) for (j = 0; j < N; j++) data[i][j] = ((DATA_TYPE) i*j) / M; } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int m, DATA_TYPE POLYBENCH_2D(symmat,M,M,m,m)) { int i, j; for (i = 0; i < m; i++) for (j = 0; j < m; j++) { fprintf (stderr, DATA_PRINTF_MODIFIER, symmat[i][j]); if ((i * m + j) % 20 == 0) fprintf (stderr, "\n"); } fprintf (stderr, "\n"); } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_covariance(int m, int n, DATA_TYPE float_n, DATA_TYPE POLYBENCH_2D(data,M,N,m,n), DATA_TYPE POLYBENCH_2D(symmat,M,M,m,m), DATA_TYPE POLYBENCH_1D(mean,M,m)) { int i, j, j1, j2; #pragma scop /* Determine mean of column vectors of input data matrix */ { #pragma omp parallel for schedule(static, 28) simd for (j = 0; j < _PB_M; j++) { mean[j] = 0.0; for (i = 0; i < _PB_N; i++) mean[j] += data[i][j]; mean[j] /= float_n; } /* Center the column vectors. */ #pragma omp parallel for schedule(static, 28) simd for (i = 0; i < _PB_N; i++) { for (j = 0; j < _PB_M; j++) { data[i][j] -= mean[j]; } } /* Calculate the m * m covariance matrix. */ #pragma omp parallel for schedule(static, 28) simd for (j1 = 0; j1 < _PB_M; j1++) { for (j2 = j1; j2 < _PB_M; j2++) { symmat[j1][j2] = 0.0; for (i = 0; i < _PB_N; i++) symmat[j1][j2] += data[i][j1] * data[i][j2]; symmat[j2][j1] = symmat[j1][j2]; } } } #pragma endscop } int main(int argc, char** argv) { /* Retrieve problem size. */ int n = N; int m = M; /* Variable declaration/allocation. */ DATA_TYPE float_n; POLYBENCH_2D_ARRAY_DECL(data,DATA_TYPE,M,N,m,n); POLYBENCH_2D_ARRAY_DECL(symmat,DATA_TYPE,M,M,m,m); POLYBENCH_1D_ARRAY_DECL(mean,DATA_TYPE,M,m); /* Initialize array(s). */ init_array (m, n, &float_n, POLYBENCH_ARRAY(data)); /* Start timer. */ polybench_start_instruments; /* Run kernel. */ kernel_covariance (m, n, float_n, POLYBENCH_ARRAY(data), POLYBENCH_ARRAY(symmat), POLYBENCH_ARRAY(mean)); /* Stop and print timer. */ polybench_stop_instruments; polybench_print_instruments; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ polybench_prevent_dce(print_array(m, POLYBENCH_ARRAY(symmat))); /* Be clean. */ POLYBENCH_FREE_ARRAY(data); POLYBENCH_FREE_ARRAY(symmat); POLYBENCH_FREE_ARRAY(mean); return 0; }
ckdeg.c
/* Maximilien Danisch and Qinna Wang January 2015 http://bit.ly/maxdan94 maximilien.danisch@telecom-paristech.fr Info: Feel free to use these lines as you wish. This program computes the k-clique degrees of each node in the graph (that is the number of k-cliques the node belongs to). To compile: "gcc ckdeg.c -O9 -o ckdeg -fopenmp". To execute: "./ckdeg p k edgelist.txt kdeg.txt". p is the number of processors to use. k of k-clique to enumerate. "edgelist.txt" should contain the graph: one edge on each line separated by a space. Will print the total number of k-cliques. "kdeg.txt" will contain the k-clique degrees (node ID followed and its k-clique degree separated by a space on each line). Note: parallelisation over edges and increasing core ordering */ #include <stdlib.h> #include <stdio.h> #include <omp.h> #include <time.h> #define NLINKS 100000000 //maximum number of edges for memory allocation, will increase if needed // heap data structure : typedef struct { unsigned key; unsigned value; } keyvalue; typedef struct { unsigned n_max; // max number of nodes. unsigned n; // number of nodes. unsigned *pt; // pointers to nodes. keyvalue *kv; // nodes. } bheap; bheap *construct(unsigned n_max){ unsigned i; bheap *heap=malloc(sizeof(bheap)); heap->n_max=n_max; heap->n=0; heap->pt=malloc(n_max*sizeof(unsigned)); for (i=0;i<n_max;i++) heap->pt[i]=-1; heap->kv=malloc(n_max*sizeof(keyvalue)); return heap; } inline void swap(bheap *heap,unsigned i, unsigned j) { keyvalue kv_tmp=heap->kv[i]; unsigned pt_tmp=heap->pt[kv_tmp.key]; heap->pt[heap->kv[i].key]=heap->pt[heap->kv[j].key]; heap->kv[i]=heap->kv[j]; heap->pt[heap->kv[j].key]=pt_tmp; heap->kv[j]=kv_tmp; } inline void bubble_up(bheap *heap,unsigned i) { unsigned j=(i-1)/2; while (i>0) { if (heap->kv[j].value>heap->kv[i].value) { swap(heap,i,j); i=j; j=(i-1)/2; } else break; } } inline void bubble_down(bheap *heap) { unsigned i=0,j1=1,j2=2,j; while (j1<heap->n) { j=( (j2<heap->n) && (heap->kv[j2].value<heap->kv[j1].value) ) ? j2 : j1 ; if (heap->kv[j].value < heap->kv[i].value) { swap(heap,i,j); i=j; j1=2*i+1; j2=j1+1; continue; } break; } } inline void insert(bheap *heap,keyvalue kv){ heap->pt[kv.key]=(heap->n)++; heap->kv[heap->n-1]=kv; bubble_up(heap,heap->n-1); } inline void update(bheap *heap,unsigned key){ unsigned i=heap->pt[key]; if (i!=-1){ ((heap->kv[i]).value)--; bubble_up(heap,i); } } inline keyvalue popmin(bheap *heap){ keyvalue min=heap->kv[0]; heap->pt[min.key]=-1; heap->kv[0]=heap->kv[--(heap->n)]; heap->pt[heap->kv[0].key]=0; bubble_down(heap); return min; } // graph datastructure: typedef struct { unsigned s; unsigned t; } edge; typedef struct { //edge list structure: unsigned n; //number of nodes unsigned e; //number of edges unsigned n2; //number of nodes with core value larger than one unsigned e2; //number of edges between nodes with core value larger than one edge *edges;//list of edges //to compute a degeneracy ordering: unsigned *d0; //degrees unsigned *cd0; //cumulative degree: (start with 0) length=dim+1 unsigned *adj0; //list of neighbors unsigned *rank; //degeneracy rankings of nodes unsigned *map;//map[newlabel]=oldlabel unsigned core; //core number of the graph //truncated neighborhoods: unsigned *d; //truncated degrees unsigned *cd; //cumulative degree: (start with 0) length=dim+1 unsigned *adj; //list of neighbors with higher rank } sparse; //compute the maximum of three unsigned inline unsigned max3(unsigned a,unsigned b,unsigned c){ a=(a>b) ? a : b; return (a>c) ? a : c; } //reading the edgelist from file sparse* readedgelist(char* edgelist){ unsigned e1=NLINKS; sparse *g=malloc(sizeof(sparse)); FILE *file; g->n=0; g->e=0; file=fopen(edgelist,"r"); g->edges=malloc(e1*sizeof(edge)); while (fscanf(file,"%u %u", &(g->edges[g->e].s), &(g->edges[g->e].t))==2) { g->n=max3(g->n,g->edges[g->e].s,g->edges[g->e].t); if (g->e++==e1) { e1+=NLINKS; g->edges=realloc(g->edges,e1*sizeof(edge)); } } fclose(file); g->n++; g->edges=realloc(g->edges,g->e*sizeof(edge)); return g; } //Building the graph structure void mkgraph(sparse *g){ unsigned i; g->d0=calloc(g->n,sizeof(unsigned)); for (i=0;i<g->e;i++) { g->d0[g->edges[i].s]++; g->d0[g->edges[i].t]++; } g->cd0=malloc((g->n+1)*sizeof(unsigned)); g->cd0[0]=0; for (i=1;i<g->n+1;i++) { g->cd0[i]=g->cd0[i-1]+g->d0[i-1]; g->d0[i-1]=0; } g->adj0=malloc(2*g->e*sizeof(unsigned)); for (i=0;i<g->e;i++) { g->adj0[ g->cd0[g->edges[i].s] + g->d0[ g->edges[i].s ]++ ]=g->edges[i].t; g->adj0[ g->cd0[g->edges[i].t] + g->d0[ g->edges[i].t ]++ ]=g->edges[i].s; } } //Building the heap structure with (key,value)=(node,degree) for each node bheap* mkheap(sparse *g){ unsigned i; keyvalue kv; bheap* heap=construct(g->n); for (i=0;i<g->n;i++){ kv.key=i; kv.value=g->d0[i]; insert(heap,kv); } return heap; } void freeheap(bheap *heap){ free(heap->pt); free(heap->kv); free(heap); } //computing degeneracy ordering and core value void kcore(sparse* g,unsigned kmax){ unsigned i,j,r=0,n=g->n,k=kmax-1; keyvalue kv; unsigned c=0;//the core number bheap *heap=mkheap(g); g->rank=malloc(g->n*sizeof(unsigned)); g->map=malloc(g->n*sizeof(unsigned)); for (i=0;i<g->n;i++){ kv=popmin(heap); if (kv.value>c){ c=kv.value; } if (c<k){//remove node with core value less than kmax-1 g->rank[kv.key]=-1; n--; } else{ g->map[n-(++r)]=kv.key; g->rank[kv.key]=n-r; } for (j=g->cd0[kv.key];j<g->cd0[kv.key+1];j++){ update(heap,g->adj0[j]); } } freeheap(heap); free(g->d0); free(g->cd0); free(g->adj0); g->core=c; g->n2=n; } void relabelnodes(sparse *g) { unsigned i,j,source,target; j=0; for (i=0;i<g->e;i++) { source=g->rank[g->edges[i].s]; target=g->rank[g->edges[i].t]; if (source==-1 || target==-1){ continue; } if (source<target) { g->edges[j].s=target; g->edges[j++].t=source; } else { g->edges[j].s=source; g->edges[j++].t=target; } } g->e2=j; g->edges=realloc(g->edges,g->e2*sizeof(edge)); } //for future use in qsort int cmpfunc (const void * a, const void * b){ if (*(unsigned*)a>*(unsigned*)b){ return 1; } return -1; } //Building the special graph structure void mkspecial(sparse *g){ unsigned i; g->d=calloc(g->n2,sizeof(unsigned)); for (i=0;i<g->e2;i++) { g->d[g->edges[i].s]++; } g->cd=malloc((g->n2+1)*sizeof(unsigned)); g->cd[0]=0; for (i=1;i<g->n2+1;i++) { g->cd[i]=g->cd[i-1]+g->d[i-1]; g->d[i-1]=0; } g->adj=malloc((g->e2)*sizeof(unsigned)); for (i=0;i<g->e2;i++) { g->adj[g->cd[g->edges[i].s] + g->d[ g->edges[i].s ]++ ]=g->edges[i].t; } #pragma omp parallel for private(i) for (i=0;i<g->n2;i++) { qsort(&g->adj[g->cd[i]],g->d[i],sizeof(unsigned),cmpfunc); } //free(g->edges); Can be freed if node parallelisation is used instead of edge } void freesparse(sparse *g){ free(g->edges); free(g->rank); free(g->map); free(g->d); free(g->cd); free(g->adj); free(g); } //store the intersection of list1 and list2 in list3 and return the size of list3 (the 3 lists are sorted) inline unsigned merging(unsigned *list1, unsigned s1, unsigned *list2, unsigned s2,unsigned *list3){ unsigned i=0,j=0,s3=0; unsigned x=list1[0],y=list2[0]; while (i<s1 && j<s2){ if(x<y){ x=list1[++i]; continue; } if(y<x){ y=list2[++j]; continue; } list3[s3++]=x; x=list1[++i]; y=list2[++j]; } return s3; } //the recursion to compute all possible intersections void recursion(unsigned kmax, unsigned k, sparse* g, unsigned* ck, unsigned* merge, unsigned* size, unsigned long long* ckdeg){ unsigned t=(k-3)*g->core,t2=t+g->core; unsigned i, j, u; if (size[k-3]<kmax-k){//stop if we already know k-cliques cannot be formed return; } if (k==kmax){//increasing the k-clique degrees for (i=0;i<kmax-1;i++){ ckdeg[ck[i]]+=size[k-3]; } for (i=0;i<size[k-3];i++){ ckdeg[merge[t+i]]++; } return; } for(i=0; i<size[k-3]; i++){ ck[k-1]=merge[t+i]; size[k-2]=merging(&g->adj[g->cd[ck[k-1]]],g->d[ck[k-1]],&merge[t],size[k-3],&merge[t2]); recursion(kmax, k+1, g, ck, merge, size, ckdeg); } } //one pass over all k-cliques unsigned long long *onepass(sparse *g,unsigned kmax){ unsigned e,i,u,v,k; unsigned *merge,*size,*ck; unsigned long long *ckdeg_p,*ckdeg; if (kmax>2){ ckdeg=calloc(g->n2,sizeof(unsigned long long)); #pragma omp parallel private(merge,size,ck,ckdeg_p,e,u,v,k) shared(ckdeg) { merge=malloc((kmax-2)*g->core*sizeof(unsigned)); size=malloc((kmax-2)*sizeof(unsigned)); ck=malloc(kmax*sizeof(unsigned)); ckdeg_p=calloc(g->n2,sizeof(unsigned long long)); #pragma omp for schedule(dynamic, 1) nowait for(e=0; e<g->e2; e++){ ck[0]=g->edges[e].s; ck[1]=g->edges[e].t; size[0]=merging(&(g->adj[g->cd[ck[0]]]),g->d[ck[0]],&(g->adj[g->cd[ck[1]]]),g->d[ck[1]],merge); recursion(kmax,3,g,ck,merge,size,ckdeg_p); } #pragma omp critical { for (i=0;i<g->n2;i++){ ckdeg[i]+=ckdeg_p[i]; } } free(ckdeg_p); free(merge); free(size); } } return ckdeg; } unsigned long long printckdeg(unsigned long long *ckdeg,sparse *g, char* output){ unsigned i; unsigned long long sum=0; FILE* file=fopen(output,"w"); for (i=0;i<g->n2;i++){ fprintf(file,"%u %llu\n",g->map[i],ckdeg[i]); sum+=ckdeg[i]; } fclose(file); return sum; } int main(int argc,char** argv){ sparse* g; unsigned i, kmax=atoi(argv[2]); unsigned long long *ckdeg,nck; omp_set_num_threads(atoi(argv[1])); time_t t0,t1,t2; t1=time(NULL); t0=t1; printf("Reading edgelist from file %s\n",argv[3]); g=readedgelist(argv[3]); t2=time(NULL); printf("- Time = %ldh%ldm%lds\n",(t2-t1)/3600,((t2-t1)%3600)/60,((t2-t1)%60)); t1=t2; printf("Number of nodes: %u\n",g->n); printf("Number of edges: %u\n",g->e); printf("Building the graph structure\n"); mkgraph(g); printf("Computing degeneracy ordering\n"); kcore(g,kmax); relabelnodes(g); printf("Number of nodes (with core value > %u): %u\n",kmax-2,g->n2); printf("Number of edges (between nodes with core value > %u): %u\n",kmax-2,g->e2); printf("Core number = %u\n",g->core); mkspecial(g); t2=time(NULL); printf("- Time = %ldh%ldm%lds\n",(t2-t1)/3600,((t2-t1)%3600)/60,((t2-t1)%60)); t1=t2; printf("computing %u-clique degrees\n",kmax); ckdeg=onepass(g,kmax); nck=printckdeg(ckdeg,g,argv[4]); nck/=kmax; printf("Number of %u-cliques: %llu\n",kmax,nck); free(ckdeg); freesparse(g); t2=time(NULL); printf("- Time = %ldh%ldm%lds\n",(t2-t1)/3600,((t2-t1)%3600)/60,((t2-t1)%60)); t1=t2; printf("- Overall time = %ldh%ldm%lds\n",(t2-t0)/3600,((t2-t0)%3600)/60,((t2-t0)%60)); return 0; }
merge_openmp.h
// merge sequences [xs,xe) and [ys,ye) to output [zs,zs+(xe-xs)+(ye-ys)) void parallel_merge( T* xs, T* xe, T* ys, T* ye, T* zs ) { const size_t MERGE_CUT_OFF = 2000; if( xe-xs + ye-ys <= MERGE_CUT_OFF ) { serial_merge(xs,xe,ys,ye,zs); } else { T *xm, *ym; if( xe-xs < ye-ys ) { ym = ys+(ye-ys)/2; xm = std::upper_bound(xs,xe,*ym); } else { xm = xs+(xe-xs)/2; ym = std::lower_bound(ys,ye,*xm); } T* zm = zs + (xm-xs) + (ym-ys); #pragma omp task parallel_merge( xs, xm, ys, ym, zs ); parallel_merge( xm, xe, ym, ye, zm ); #pragma omp taskwait } }
c-omp.c
/* This file contains routines to construct OpenACC and OpenMP constructs, called from parsing in the C and C++ front ends. Copyright (C) 2005-2015 Free Software Foundation, Inc. Contributed by Richard Henderson <rth@redhat.com>, Diego Novillo <dnovillo@redhat.com>. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "hash-set.h" #include "machmode.h" #include "vec.h" #include "double-int.h" #include "input.h" #include "alias.h" #include "symtab.h" #include "wide-int.h" #include "inchash.h" #include "tree.h" #include "c-common.h" #include "c-pragma.h" #include "gimple-expr.h" #include "langhooks.h" #include "omp-low.h" #include "gomp-constants.h" /* Complete a #pragma oacc wait construct. LOC is the location of the #pragma. */ tree c_finish_oacc_wait (location_t loc, tree parms, tree clauses) { const int nparms = list_length (parms); tree stmt, t; vec<tree, va_gc> *args; vec_alloc (args, nparms + 2); stmt = builtin_decl_explicit (BUILT_IN_GOACC_WAIT); if (find_omp_clause (clauses, OMP_CLAUSE_ASYNC)) t = OMP_CLAUSE_ASYNC_EXPR (clauses); else t = build_int_cst (integer_type_node, GOMP_ASYNC_SYNC); args->quick_push (t); args->quick_push (build_int_cst (integer_type_node, nparms)); for (t = parms; t; t = TREE_CHAIN (t)) { if (TREE_CODE (OMP_CLAUSE_WAIT_EXPR (t)) == INTEGER_CST) args->quick_push (build_int_cst (integer_type_node, TREE_INT_CST_LOW (OMP_CLAUSE_WAIT_EXPR (t)))); else args->quick_push (OMP_CLAUSE_WAIT_EXPR (t)); } stmt = build_call_expr_loc_vec (loc, stmt, args); add_stmt (stmt); vec_free (args); return stmt; } /* Complete a #pragma omp master construct. STMT is the structured-block that follows the pragma. LOC is the l*/ tree c_finish_omp_master (location_t loc, tree stmt) { tree t = add_stmt (build1 (OMP_MASTER, void_type_node, stmt)); SET_EXPR_LOCATION (t, loc); return t; } /* Complete a #pragma omp taskgroup construct. STMT is the structured-block that follows the pragma. LOC is the l*/ tree c_finish_omp_taskgroup (location_t loc, tree stmt) { tree t = add_stmt (build1 (OMP_TASKGROUP, void_type_node, stmt)); SET_EXPR_LOCATION (t, loc); return t; } /* Complete a #pragma omp critical construct. STMT is the structured-block that follows the pragma, NAME is the identifier in the pragma, or null if it was omitted. LOC is the location of the #pragma. */ tree c_finish_omp_critical (location_t loc, tree body, tree name) { tree stmt = make_node (OMP_CRITICAL); TREE_TYPE (stmt) = void_type_node; OMP_CRITICAL_BODY (stmt) = body; OMP_CRITICAL_NAME (stmt) = name; SET_EXPR_LOCATION (stmt, loc); return add_stmt (stmt); } /* Complete a #pragma omp ordered construct. STMT is the structured-block that follows the pragma. LOC is the location of the #pragma. */ tree c_finish_omp_ordered (location_t loc, tree stmt) { tree t = build1 (OMP_ORDERED, void_type_node, stmt); SET_EXPR_LOCATION (t, loc); return add_stmt (t); } /* Complete a #pragma omp barrier construct. LOC is the location of the #pragma. */ void c_finish_omp_barrier (location_t loc) { tree x; x = builtin_decl_explicit (BUILT_IN_GOMP_BARRIER); x = build_call_expr_loc (loc, x, 0); add_stmt (x); } /* Complete a #pragma omp taskwait construct. LOC is the location of the pragma. */ void c_finish_omp_taskwait (location_t loc) { tree x; x = builtin_decl_explicit (BUILT_IN_GOMP_TASKWAIT); x = build_call_expr_loc (loc, x, 0); add_stmt (x); } /* Complete a #pragma omp taskyield construct. LOC is the location of the pragma. */ void c_finish_omp_taskyield (location_t loc) { tree x; x = builtin_decl_explicit (BUILT_IN_GOMP_TASKYIELD); x = build_call_expr_loc (loc, x, 0); add_stmt (x); } /* Complete a #pragma omp atomic construct. For CODE OMP_ATOMIC the expression to be implemented atomically is LHS opcode= RHS. For OMP_ATOMIC_READ V = LHS, for OMP_ATOMIC_CAPTURE_{NEW,OLD} LHS opcode= RHS with the new or old content of LHS returned. LOC is the location of the atomic statement. The value returned is either error_mark_node (if the construct was erroneous) or an OMP_ATOMIC* node which should be added to the current statement tree with add_stmt. */ tree c_finish_omp_atomic (location_t loc, enum tree_code code, enum tree_code opcode, tree lhs, tree rhs, tree v, tree lhs1, tree rhs1, bool swapped, bool seq_cst) { tree x, type, addr, pre = NULL_TREE; if (lhs == error_mark_node || rhs == error_mark_node || v == error_mark_node || lhs1 == error_mark_node || rhs1 == error_mark_node) return error_mark_node; /* ??? According to one reading of the OpenMP spec, complex type are supported, but there are no atomic stores for any architecture. But at least icc 9.0 doesn't support complex types here either. And lets not even talk about vector types... */ type = TREE_TYPE (lhs); if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type) && !SCALAR_FLOAT_TYPE_P (type)) { error_at (loc, "invalid expression type for %<#pragma omp atomic%>"); return error_mark_node; } if (opcode == RDIV_EXPR) opcode = TRUNC_DIV_EXPR; /* ??? Validate that rhs does not overlap lhs. */ /* Take and save the address of the lhs. From then on we'll reference it via indirection. */ addr = build_unary_op (loc, ADDR_EXPR, lhs, 0); if (addr == error_mark_node) return error_mark_node; addr = save_expr (addr); if (TREE_CODE (addr) != SAVE_EXPR && (TREE_CODE (addr) != ADDR_EXPR || TREE_CODE (TREE_OPERAND (addr, 0)) != VAR_DECL)) { /* Make sure LHS is simple enough so that goa_lhs_expr_p can recognize it even after unsharing function body. */ tree var = create_tmp_var_raw (TREE_TYPE (addr)); DECL_CONTEXT (var) = current_function_decl; addr = build4 (TARGET_EXPR, TREE_TYPE (addr), var, addr, NULL, NULL); } lhs = build_indirect_ref (loc, addr, RO_NULL); if (code == OMP_ATOMIC_READ) { x = build1 (OMP_ATOMIC_READ, type, addr); SET_EXPR_LOCATION (x, loc); OMP_ATOMIC_SEQ_CST (x) = seq_cst; return build_modify_expr (loc, v, NULL_TREE, NOP_EXPR, loc, x, NULL_TREE); } /* There are lots of warnings, errors, and conversions that need to happen in the course of interpreting a statement. Use the normal mechanisms to do this, and then take it apart again. */ if (swapped) { rhs = build_binary_op (loc, opcode, rhs, lhs, 1); opcode = NOP_EXPR; } bool save = in_late_binary_op; in_late_binary_op = true; x = build_modify_expr (loc, lhs, NULL_TREE, opcode, loc, rhs, NULL_TREE); in_late_binary_op = save; if (x == error_mark_node) return error_mark_node; if (TREE_CODE (x) == COMPOUND_EXPR) { pre = TREE_OPERAND (x, 0); gcc_assert (TREE_CODE (pre) == SAVE_EXPR); x = TREE_OPERAND (x, 1); } gcc_assert (TREE_CODE (x) == MODIFY_EXPR); rhs = TREE_OPERAND (x, 1); /* Punt the actual generation of atomic operations to common code. */ if (code == OMP_ATOMIC) type = void_type_node; x = build2 (code, type, addr, rhs); SET_EXPR_LOCATION (x, loc); OMP_ATOMIC_SEQ_CST (x) = seq_cst; /* Generally it is hard to prove lhs1 and lhs are the same memory location, just diagnose different variables. */ if (rhs1 && TREE_CODE (rhs1) == VAR_DECL && TREE_CODE (lhs) == VAR_DECL && rhs1 != lhs) { if (code == OMP_ATOMIC) error_at (loc, "%<#pragma omp atomic update%> uses two different variables for memory"); else error_at (loc, "%<#pragma omp atomic capture%> uses two different variables for memory"); return error_mark_node; } if (code != OMP_ATOMIC) { /* Generally it is hard to prove lhs1 and lhs are the same memory location, just diagnose different variables. */ if (lhs1 && TREE_CODE (lhs1) == VAR_DECL && TREE_CODE (lhs) == VAR_DECL) { if (lhs1 != lhs) { error_at (loc, "%<#pragma omp atomic capture%> uses two different variables for memory"); return error_mark_node; } } x = build_modify_expr (loc, v, NULL_TREE, NOP_EXPR, loc, x, NULL_TREE); if (rhs1 && rhs1 != lhs) { tree rhs1addr = build_unary_op (loc, ADDR_EXPR, rhs1, 0); if (rhs1addr == error_mark_node) return error_mark_node; x = omit_one_operand_loc (loc, type, x, rhs1addr); } if (lhs1 && lhs1 != lhs) { tree lhs1addr = build_unary_op (loc, ADDR_EXPR, lhs1, 0); if (lhs1addr == error_mark_node) return error_mark_node; if (code == OMP_ATOMIC_CAPTURE_OLD) x = omit_one_operand_loc (loc, type, x, lhs1addr); else { x = save_expr (x); x = omit_two_operands_loc (loc, type, x, x, lhs1addr); } } } else if (rhs1 && rhs1 != lhs) { tree rhs1addr = build_unary_op (loc, ADDR_EXPR, rhs1, 0); if (rhs1addr == error_mark_node) return error_mark_node; x = omit_one_operand_loc (loc, type, x, rhs1addr); } if (pre) x = omit_one_operand_loc (loc, type, x, pre); return x; } /* Complete a #pragma omp flush construct. We don't do anything with the variable list that the syntax allows. LOC is the location of the #pragma. */ void c_finish_omp_flush (location_t loc) { tree x; x = builtin_decl_explicit (BUILT_IN_SYNC_SYNCHRONIZE); x = build_call_expr_loc (loc, x, 0); add_stmt (x); } /* Check and canonicalize OMP_FOR increment expression. Helper function for c_finish_omp_for. */ static tree check_omp_for_incr_expr (location_t loc, tree exp, tree decl) { tree t; if (!INTEGRAL_TYPE_P (TREE_TYPE (exp)) || TYPE_PRECISION (TREE_TYPE (exp)) < TYPE_PRECISION (TREE_TYPE (decl))) return error_mark_node; if (exp == decl) return build_int_cst (TREE_TYPE (exp), 0); switch (TREE_CODE (exp)) { CASE_CONVERT: t = check_omp_for_incr_expr (loc, TREE_OPERAND (exp, 0), decl); if (t != error_mark_node) return fold_convert_loc (loc, TREE_TYPE (exp), t); break; case MINUS_EXPR: t = check_omp_for_incr_expr (loc, TREE_OPERAND (exp, 0), decl); if (t != error_mark_node) return fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (exp), t, TREE_OPERAND (exp, 1)); break; case PLUS_EXPR: t = check_omp_for_incr_expr (loc, TREE_OPERAND (exp, 0), decl); if (t != error_mark_node) return fold_build2_loc (loc, PLUS_EXPR, TREE_TYPE (exp), t, TREE_OPERAND (exp, 1)); t = check_omp_for_incr_expr (loc, TREE_OPERAND (exp, 1), decl); if (t != error_mark_node) return fold_build2_loc (loc, PLUS_EXPR, TREE_TYPE (exp), TREE_OPERAND (exp, 0), t); break; case COMPOUND_EXPR: { /* cp_build_modify_expr forces preevaluation of the RHS to make sure that it is evaluated before the lvalue-rvalue conversion is applied to the LHS. Reconstruct the original expression. */ tree op0 = TREE_OPERAND (exp, 0); if (TREE_CODE (op0) == TARGET_EXPR && !VOID_TYPE_P (TREE_TYPE (op0))) { tree op1 = TREE_OPERAND (exp, 1); tree temp = TARGET_EXPR_SLOT (op0); if (TREE_CODE_CLASS (TREE_CODE (op1)) == tcc_binary && TREE_OPERAND (op1, 1) == temp) { op1 = copy_node (op1); TREE_OPERAND (op1, 1) = TARGET_EXPR_INITIAL (op0); return check_omp_for_incr_expr (loc, op1, decl); } } break; } default: break; } return error_mark_node; } /* If the OMP_FOR increment expression in INCR is of pointer type, canonicalize it into an expression handled by gimplify_omp_for() and return it. DECL is the iteration variable. */ static tree c_omp_for_incr_canonicalize_ptr (location_t loc, tree decl, tree incr) { if (POINTER_TYPE_P (TREE_TYPE (decl)) && TREE_OPERAND (incr, 1)) { tree t = fold_convert_loc (loc, sizetype, TREE_OPERAND (incr, 1)); if (TREE_CODE (incr) == POSTDECREMENT_EXPR || TREE_CODE (incr) == PREDECREMENT_EXPR) t = fold_build1_loc (loc, NEGATE_EXPR, sizetype, t); t = fold_build_pointer_plus (decl, t); incr = build2 (MODIFY_EXPR, void_type_node, decl, t); } return incr; } /* Validate and generate OMP_FOR. DECLV is a vector of iteration variables, for each collapsed loop. INITV, CONDV and INCRV are vectors containing initialization expressions, controlling predicates and increment expressions. BODY is the body of the loop and PRE_BODY statements that go before the loop. */ tree c_finish_omp_for (location_t locus, enum tree_code code, tree declv, tree initv, tree condv, tree incrv, tree body, tree pre_body) { location_t elocus; bool fail = false; int i; if ((code == CILK_SIMD || code == CILK_FOR) && !c_check_cilk_loop (locus, TREE_VEC_ELT (declv, 0))) fail = true; gcc_assert (TREE_VEC_LENGTH (declv) == TREE_VEC_LENGTH (initv)); gcc_assert (TREE_VEC_LENGTH (declv) == TREE_VEC_LENGTH (condv)); gcc_assert (TREE_VEC_LENGTH (declv) == TREE_VEC_LENGTH (incrv)); for (i = 0; i < TREE_VEC_LENGTH (declv); i++) { tree decl = TREE_VEC_ELT (declv, i); tree init = TREE_VEC_ELT (initv, i); tree cond = TREE_VEC_ELT (condv, i); tree incr = TREE_VEC_ELT (incrv, i); elocus = locus; if (EXPR_HAS_LOCATION (init)) elocus = EXPR_LOCATION (init); /* Validate the iteration variable. */ if (!INTEGRAL_TYPE_P (TREE_TYPE (decl)) && TREE_CODE (TREE_TYPE (decl)) != POINTER_TYPE) { error_at (elocus, "invalid type for iteration variable %qE", decl); fail = true; } /* In the case of "for (int i = 0...)", init will be a decl. It should have a DECL_INITIAL that we can turn into an assignment. */ if (init == decl) { elocus = DECL_SOURCE_LOCATION (decl); init = DECL_INITIAL (decl); if (init == NULL) { error_at (elocus, "%qE is not initialized", decl); init = integer_zero_node; fail = true; } init = build_modify_expr (elocus, decl, NULL_TREE, NOP_EXPR, /* FIXME diagnostics: This should be the location of the INIT. */ elocus, init, NULL_TREE); } if (init != error_mark_node) { gcc_assert (TREE_CODE (init) == MODIFY_EXPR); gcc_assert (TREE_OPERAND (init, 0) == decl); } if (cond == NULL_TREE) { error_at (elocus, "missing controlling predicate"); fail = true; } else { bool cond_ok = false; if (EXPR_HAS_LOCATION (cond)) elocus = EXPR_LOCATION (cond); if (TREE_CODE (cond) == LT_EXPR || TREE_CODE (cond) == LE_EXPR || TREE_CODE (cond) == GT_EXPR || TREE_CODE (cond) == GE_EXPR || TREE_CODE (cond) == NE_EXPR || TREE_CODE (cond) == EQ_EXPR) { tree op0 = TREE_OPERAND (cond, 0); tree op1 = TREE_OPERAND (cond, 1); /* 2.5.1. The comparison in the condition is computed in the type of DECL, otherwise the behavior is undefined. For example: long n; int i; i < n; according to ISO will be evaluated as: (long)i < n; We want to force: i < (int)n; */ if (TREE_CODE (op0) == NOP_EXPR && decl == TREE_OPERAND (op0, 0)) { TREE_OPERAND (cond, 0) = TREE_OPERAND (op0, 0); TREE_OPERAND (cond, 1) = fold_build1_loc (elocus, NOP_EXPR, TREE_TYPE (decl), TREE_OPERAND (cond, 1)); } else if (TREE_CODE (op1) == NOP_EXPR && decl == TREE_OPERAND (op1, 0)) { TREE_OPERAND (cond, 1) = TREE_OPERAND (op1, 0); TREE_OPERAND (cond, 0) = fold_build1_loc (elocus, NOP_EXPR, TREE_TYPE (decl), TREE_OPERAND (cond, 0)); } if (decl == TREE_OPERAND (cond, 0)) cond_ok = true; else if (decl == TREE_OPERAND (cond, 1)) { TREE_SET_CODE (cond, swap_tree_comparison (TREE_CODE (cond))); TREE_OPERAND (cond, 1) = TREE_OPERAND (cond, 0); TREE_OPERAND (cond, 0) = decl; cond_ok = true; } if (TREE_CODE (cond) == NE_EXPR || TREE_CODE (cond) == EQ_EXPR) { if (!INTEGRAL_TYPE_P (TREE_TYPE (decl))) { if (code != CILK_SIMD && code != CILK_FOR) cond_ok = false; } else if (operand_equal_p (TREE_OPERAND (cond, 1), TYPE_MIN_VALUE (TREE_TYPE (decl)), 0)) TREE_SET_CODE (cond, TREE_CODE (cond) == NE_EXPR ? GT_EXPR : LE_EXPR); else if (operand_equal_p (TREE_OPERAND (cond, 1), TYPE_MAX_VALUE (TREE_TYPE (decl)), 0)) TREE_SET_CODE (cond, TREE_CODE (cond) == NE_EXPR ? LT_EXPR : GE_EXPR); else if (code != CILK_SIMD && code != CILK_FOR) cond_ok = false; } } if (!cond_ok) { error_at (elocus, "invalid controlling predicate"); fail = true; } } if (incr == NULL_TREE) { error_at (elocus, "missing increment expression"); fail = true; } else { bool incr_ok = false; if (EXPR_HAS_LOCATION (incr)) elocus = EXPR_LOCATION (incr); /* Check all the valid increment expressions: v++, v--, ++v, --v, v = v + incr, v = incr + v and v = v - incr. */ switch (TREE_CODE (incr)) { case POSTINCREMENT_EXPR: case PREINCREMENT_EXPR: case POSTDECREMENT_EXPR: case PREDECREMENT_EXPR: if (TREE_OPERAND (incr, 0) != decl) break; incr_ok = true; incr = c_omp_for_incr_canonicalize_ptr (elocus, decl, incr); break; case COMPOUND_EXPR: if (TREE_CODE (TREE_OPERAND (incr, 0)) != SAVE_EXPR || TREE_CODE (TREE_OPERAND (incr, 1)) != MODIFY_EXPR) break; incr = TREE_OPERAND (incr, 1); /* FALLTHRU */ case MODIFY_EXPR: if (TREE_OPERAND (incr, 0) != decl) break; if (TREE_OPERAND (incr, 1) == decl) break; if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR && (TREE_OPERAND (TREE_OPERAND (incr, 1), 0) == decl || TREE_OPERAND (TREE_OPERAND (incr, 1), 1) == decl)) incr_ok = true; else if ((TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR || (TREE_CODE (TREE_OPERAND (incr, 1)) == POINTER_PLUS_EXPR)) && TREE_OPERAND (TREE_OPERAND (incr, 1), 0) == decl) incr_ok = true; else { tree t = check_omp_for_incr_expr (elocus, TREE_OPERAND (incr, 1), decl); if (t != error_mark_node) { incr_ok = true; t = build2 (PLUS_EXPR, TREE_TYPE (decl), decl, t); incr = build2 (MODIFY_EXPR, void_type_node, decl, t); } } break; default: break; } if (!incr_ok) { error_at (elocus, "invalid increment expression"); fail = true; } } TREE_VEC_ELT (initv, i) = init; TREE_VEC_ELT (incrv, i) = incr; } if (fail) return NULL; else { tree t = make_node (code); TREE_TYPE (t) = void_type_node; OMP_FOR_INIT (t) = initv; OMP_FOR_COND (t) = condv; OMP_FOR_INCR (t) = incrv; OMP_FOR_BODY (t) = body; OMP_FOR_PRE_BODY (t) = pre_body; SET_EXPR_LOCATION (t, locus); return add_stmt (t); } } /* Right now we have 14 different combined constructs, this function attempts to split or duplicate clauses for combined constructs. CODE is the innermost construct in the combined construct, and MASK allows to determine which constructs are combined together, as every construct has at least one clause that no other construct has (except for OMP_SECTIONS, but that can be only combined with parallel). Combined constructs are: #pragma omp parallel for #pragma omp parallel sections #pragma omp parallel for simd #pragma omp for simd #pragma omp distribute simd #pragma omp distribute parallel for #pragma omp distribute parallel for simd #pragma omp teams distribute #pragma omp teams distribute parallel for #pragma omp teams distribute parallel for simd #pragma omp target teams #pragma omp target teams distribute #pragma omp target teams distribute parallel for #pragma omp target teams distribute parallel for simd */ void c_omp_split_clauses (location_t loc, enum tree_code code, omp_clause_mask mask, tree clauses, tree *cclauses) { tree next, c; enum c_omp_clause_split s; int i; for (i = 0; i < C_OMP_CLAUSE_SPLIT_COUNT; i++) cclauses[i] = NULL; /* Add implicit nowait clause on #pragma omp parallel {for,for simd,sections}. */ if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NUM_THREADS)) != 0) switch (code) { case OMP_FOR: case OMP_SIMD: cclauses[C_OMP_CLAUSE_SPLIT_FOR] = build_omp_clause (loc, OMP_CLAUSE_NOWAIT); break; case OMP_SECTIONS: cclauses[C_OMP_CLAUSE_SPLIT_SECTIONS] = build_omp_clause (loc, OMP_CLAUSE_NOWAIT); break; default: break; } for (; clauses ; clauses = next) { next = OMP_CLAUSE_CHAIN (clauses); switch (OMP_CLAUSE_CODE (clauses)) { /* First the clauses that are unique to some constructs. */ case OMP_CLAUSE_DEVICE: case OMP_CLAUSE_MAP: s = C_OMP_CLAUSE_SPLIT_TARGET; break; case OMP_CLAUSE_NUM_TEAMS: case OMP_CLAUSE_THREAD_LIMIT: s = C_OMP_CLAUSE_SPLIT_TEAMS; break; case OMP_CLAUSE_DIST_SCHEDULE: s = C_OMP_CLAUSE_SPLIT_DISTRIBUTE; break; case OMP_CLAUSE_COPYIN: case OMP_CLAUSE_NUM_THREADS: case OMP_CLAUSE_PROC_BIND: s = C_OMP_CLAUSE_SPLIT_PARALLEL; break; case OMP_CLAUSE_ORDERED: case OMP_CLAUSE_SCHEDULE: case OMP_CLAUSE_NOWAIT: s = C_OMP_CLAUSE_SPLIT_FOR; break; case OMP_CLAUSE_SAFELEN: case OMP_CLAUSE_LINEAR: case OMP_CLAUSE_ALIGNED: s = C_OMP_CLAUSE_SPLIT_SIMD; break; /* Duplicate this to all of distribute, for and simd. */ case OMP_CLAUSE_COLLAPSE: if (code == OMP_SIMD) { c = build_omp_clause (OMP_CLAUSE_LOCATION (clauses), OMP_CLAUSE_COLLAPSE); OMP_CLAUSE_COLLAPSE_EXPR (c) = OMP_CLAUSE_COLLAPSE_EXPR (clauses); OMP_CLAUSE_CHAIN (c) = cclauses[C_OMP_CLAUSE_SPLIT_SIMD]; cclauses[C_OMP_CLAUSE_SPLIT_SIMD] = c; } if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_SCHEDULE)) != 0) { if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DIST_SCHEDULE)) != 0) { c = build_omp_clause (OMP_CLAUSE_LOCATION (clauses), OMP_CLAUSE_COLLAPSE); OMP_CLAUSE_COLLAPSE_EXPR (c) = OMP_CLAUSE_COLLAPSE_EXPR (clauses); OMP_CLAUSE_CHAIN (c) = cclauses[C_OMP_CLAUSE_SPLIT_FOR]; cclauses[C_OMP_CLAUSE_SPLIT_FOR] = c; s = C_OMP_CLAUSE_SPLIT_DISTRIBUTE; } else s = C_OMP_CLAUSE_SPLIT_FOR; } else s = C_OMP_CLAUSE_SPLIT_DISTRIBUTE; break; /* Private clause is supported on all constructs but target, it is enough to put it on the innermost one. For #pragma omp {for,sections} put it on parallel though, as that's what we did for OpenMP 3.1. */ case OMP_CLAUSE_PRIVATE: switch (code) { case OMP_SIMD: s = C_OMP_CLAUSE_SPLIT_SIMD; break; case OMP_FOR: case OMP_SECTIONS: case OMP_PARALLEL: s = C_OMP_CLAUSE_SPLIT_PARALLEL; break; case OMP_DISTRIBUTE: s = C_OMP_CLAUSE_SPLIT_DISTRIBUTE; break; case OMP_TEAMS: s = C_OMP_CLAUSE_SPLIT_TEAMS; break; default: gcc_unreachable (); } break; /* Firstprivate clause is supported on all constructs but target and simd. Put it on the outermost of those and duplicate on parallel. */ case OMP_CLAUSE_FIRSTPRIVATE: if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NUM_THREADS)) != 0) { if ((mask & ((OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NUM_TEAMS) | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DIST_SCHEDULE))) != 0) { c = build_omp_clause (OMP_CLAUSE_LOCATION (clauses), OMP_CLAUSE_FIRSTPRIVATE); OMP_CLAUSE_DECL (c) = OMP_CLAUSE_DECL (clauses); OMP_CLAUSE_CHAIN (c) = cclauses[C_OMP_CLAUSE_SPLIT_PARALLEL]; cclauses[C_OMP_CLAUSE_SPLIT_PARALLEL] = c; if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NUM_TEAMS)) != 0) s = C_OMP_CLAUSE_SPLIT_TEAMS; else s = C_OMP_CLAUSE_SPLIT_DISTRIBUTE; } else /* This must be #pragma omp parallel{, for{, simd}, sections}. */ s = C_OMP_CLAUSE_SPLIT_PARALLEL; } else if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NUM_TEAMS)) != 0) { /* This must be one of #pragma omp {,target }teams distribute #pragma omp target teams #pragma omp {,target }teams distribute simd. */ gcc_assert (code == OMP_DISTRIBUTE || code == OMP_TEAMS || code == OMP_SIMD); s = C_OMP_CLAUSE_SPLIT_TEAMS; } else if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DIST_SCHEDULE)) != 0) { /* This must be #pragma omp distribute simd. */ gcc_assert (code == OMP_SIMD); s = C_OMP_CLAUSE_SPLIT_TEAMS; } else { /* This must be #pragma omp for simd. */ gcc_assert (code == OMP_SIMD); s = C_OMP_CLAUSE_SPLIT_FOR; } break; /* Lastprivate is allowed on for, sections and simd. In parallel {for{, simd},sections} we actually want to put it on parallel rather than for or sections. */ case OMP_CLAUSE_LASTPRIVATE: if (code == OMP_FOR || code == OMP_SECTIONS) { if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NUM_THREADS)) != 0) s = C_OMP_CLAUSE_SPLIT_PARALLEL; else s = C_OMP_CLAUSE_SPLIT_FOR; break; } gcc_assert (code == OMP_SIMD); if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_SCHEDULE)) != 0) { c = build_omp_clause (OMP_CLAUSE_LOCATION (clauses), OMP_CLAUSE_LASTPRIVATE); OMP_CLAUSE_DECL (c) = OMP_CLAUSE_DECL (clauses); if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NUM_THREADS)) != 0) s = C_OMP_CLAUSE_SPLIT_PARALLEL; else s = C_OMP_CLAUSE_SPLIT_FOR; OMP_CLAUSE_CHAIN (c) = cclauses[s]; cclauses[s] = c; } s = C_OMP_CLAUSE_SPLIT_SIMD; break; /* Shared and default clauses are allowed on private and teams. */ case OMP_CLAUSE_SHARED: case OMP_CLAUSE_DEFAULT: if (code == OMP_TEAMS) { s = C_OMP_CLAUSE_SPLIT_TEAMS; break; } if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NUM_TEAMS)) != 0) { c = build_omp_clause (OMP_CLAUSE_LOCATION (clauses), OMP_CLAUSE_CODE (clauses)); if (OMP_CLAUSE_CODE (clauses) == OMP_CLAUSE_SHARED) OMP_CLAUSE_DECL (c) = OMP_CLAUSE_DECL (clauses); else OMP_CLAUSE_DEFAULT_KIND (c) = OMP_CLAUSE_DEFAULT_KIND (clauses); OMP_CLAUSE_CHAIN (c) = cclauses[C_OMP_CLAUSE_SPLIT_TEAMS]; cclauses[C_OMP_CLAUSE_SPLIT_TEAMS] = c; } s = C_OMP_CLAUSE_SPLIT_PARALLEL; break; /* Reduction is allowed on simd, for, parallel, sections and teams. Duplicate it on all of them, but omit on for or sections if parallel is present. */ case OMP_CLAUSE_REDUCTION: if (code == OMP_SIMD) { c = build_omp_clause (OMP_CLAUSE_LOCATION (clauses), OMP_CLAUSE_REDUCTION); OMP_CLAUSE_DECL (c) = OMP_CLAUSE_DECL (clauses); OMP_CLAUSE_REDUCTION_CODE (c) = OMP_CLAUSE_REDUCTION_CODE (clauses); OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) = OMP_CLAUSE_REDUCTION_PLACEHOLDER (clauses); OMP_CLAUSE_CHAIN (c) = cclauses[C_OMP_CLAUSE_SPLIT_SIMD]; cclauses[C_OMP_CLAUSE_SPLIT_SIMD] = c; } if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_SCHEDULE)) != 0) { if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NUM_TEAMS)) != 0) { c = build_omp_clause (OMP_CLAUSE_LOCATION (clauses), OMP_CLAUSE_REDUCTION); OMP_CLAUSE_DECL (c) = OMP_CLAUSE_DECL (clauses); OMP_CLAUSE_REDUCTION_CODE (c) = OMP_CLAUSE_REDUCTION_CODE (clauses); OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) = OMP_CLAUSE_REDUCTION_PLACEHOLDER (clauses); OMP_CLAUSE_CHAIN (c) = cclauses[C_OMP_CLAUSE_SPLIT_PARALLEL]; cclauses[C_OMP_CLAUSE_SPLIT_PARALLEL] = c; s = C_OMP_CLAUSE_SPLIT_TEAMS; } else if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NUM_THREADS)) != 0) s = C_OMP_CLAUSE_SPLIT_PARALLEL; else s = C_OMP_CLAUSE_SPLIT_FOR; } else if (code == OMP_SECTIONS) s = C_OMP_CLAUSE_SPLIT_PARALLEL; else s = C_OMP_CLAUSE_SPLIT_TEAMS; break; case OMP_CLAUSE_IF: /* FIXME: This is currently being discussed. */ if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NUM_THREADS)) != 0) s = C_OMP_CLAUSE_SPLIT_PARALLEL; else s = C_OMP_CLAUSE_SPLIT_TARGET; break; default: gcc_unreachable (); } OMP_CLAUSE_CHAIN (clauses) = cclauses[s]; cclauses[s] = clauses; } } /* qsort callback to compare #pragma omp declare simd clauses. */ static int c_omp_declare_simd_clause_cmp (const void *p, const void *q) { tree a = *(const tree *) p; tree b = *(const tree *) q; if (OMP_CLAUSE_CODE (a) != OMP_CLAUSE_CODE (b)) { if (OMP_CLAUSE_CODE (a) > OMP_CLAUSE_CODE (b)) return -1; return 1; } if (OMP_CLAUSE_CODE (a) != OMP_CLAUSE_SIMDLEN && OMP_CLAUSE_CODE (a) != OMP_CLAUSE_INBRANCH && OMP_CLAUSE_CODE (a) != OMP_CLAUSE_NOTINBRANCH) { int c = tree_to_shwi (OMP_CLAUSE_DECL (a)); int d = tree_to_shwi (OMP_CLAUSE_DECL (b)); if (c < d) return 1; if (c > d) return -1; } return 0; } /* Change PARM_DECLs in OMP_CLAUSE_DECL of #pragma omp declare simd CLAUSES on FNDECL into argument indexes and sort them. */ tree c_omp_declare_simd_clauses_to_numbers (tree parms, tree clauses) { tree c; vec<tree> clvec = vNULL; for (c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) { if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_SIMDLEN && OMP_CLAUSE_CODE (c) != OMP_CLAUSE_INBRANCH && OMP_CLAUSE_CODE (c) != OMP_CLAUSE_NOTINBRANCH) { tree decl = OMP_CLAUSE_DECL (c); tree arg; int idx; for (arg = parms, idx = 0; arg; arg = TREE_CHAIN (arg), idx++) if (arg == decl) break; if (arg == NULL_TREE) { error_at (OMP_CLAUSE_LOCATION (c), "%qD is not an function argument", decl); continue; } OMP_CLAUSE_DECL (c) = build_int_cst (integer_type_node, idx); } clvec.safe_push (c); } if (!clvec.is_empty ()) { unsigned int len = clvec.length (), i; clvec.qsort (c_omp_declare_simd_clause_cmp); clauses = clvec[0]; for (i = 0; i < len; i++) OMP_CLAUSE_CHAIN (clvec[i]) = (i < len - 1) ? clvec[i + 1] : NULL_TREE; } else clauses = NULL_TREE; clvec.release (); return clauses; } /* Change argument indexes in CLAUSES of FNDECL back to PARM_DECLs. */ void c_omp_declare_simd_clauses_to_decls (tree fndecl, tree clauses) { tree c; for (c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_SIMDLEN && OMP_CLAUSE_CODE (c) != OMP_CLAUSE_INBRANCH && OMP_CLAUSE_CODE (c) != OMP_CLAUSE_NOTINBRANCH) { int idx = tree_to_shwi (OMP_CLAUSE_DECL (c)), i; tree arg; for (arg = DECL_ARGUMENTS (fndecl), i = 0; arg; arg = TREE_CHAIN (arg), i++) if (i == idx) break; gcc_assert (arg); OMP_CLAUSE_DECL (c) = arg; } } /* True if OpenMP sharing attribute of DECL is predetermined. */ enum omp_clause_default_kind c_omp_predetermined_sharing (tree decl) { /* Variables with const-qualified type having no mutable member are predetermined shared. */ if (TREE_READONLY (decl)) return OMP_CLAUSE_DEFAULT_SHARED; return OMP_CLAUSE_DEFAULT_UNSPECIFIED; }
GB_unop__identity_uint32_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_uint32_fc64) // op(A') function: GB (_unop_tran__identity_uint32_fc64) // C type: uint32_t // A type: GxB_FC64_t // cast: uint32_t cij = GB_cast_to_uint32_t (creal (aij)) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint32_t z = GB_cast_to_uint32_t (creal (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint32_t z = GB_cast_to_uint32_t (creal (aij)) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT32 || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_uint32_fc64) ( uint32_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; uint32_t z = GB_cast_to_uint32_t (creal (aij)) ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; uint32_t z = GB_cast_to_uint32_t (creal (aij)) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_uint32_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unaryop__abs_int64_fp64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__abs_int64_fp64 // op(A') function: GB_tran__abs_int64_fp64 // C type: int64_t // A type: double // cast: int64_t cij ; GB_CAST_SIGNED(cij,aij,64) // unaryop: cij = GB_IABS (aij) #define GB_ATYPE \ double #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IABS (x) ; // casting #define GB_CASTING(z, x) \ int64_t z ; GB_CAST_SIGNED(z,x,64) ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_INT64 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_int64_fp64 ( int64_t *restrict Cx, const double *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__abs_int64_fp64 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
test_arrow_utf8.c
// Amazon FPGA Hardware Development Kit // // Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (the "License"). You may not use // this file except in compliance with the License. A copy of the License is // located at // // http://aws.amazon.com/asl/ // // or in the "license" file accompanying this file. This file is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or // implied. See the License for the specific language governing permissions and // limitations under the License. #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <poll.h> #include <fpga_pci.h> #include <fpga_mgmt.h> #include <utils/lcd.h> #include <byteswap.h> #include <regex.h> #include <omp.h> #define DEBUG #define INFO #define PRINT_STRINGS //#define USE_OMP #ifdef DEBUG #define DBG(...) do{ fprintf( stderr, __VA_ARGS__ ); } while( false ) #else #define DBG(...) #endif #ifdef INFO #define INF(...) do{ fprintf( stderr, __VA_ARGS__ ); } while( false ) #else #define INF(...) #endif #ifndef DEBUG #define TIME_PRINT(...) do{ fprintf( stderr, "%16.12f, ", __VA_ARGS__ ); } while( false ) #else #define TIME_PRINT(...) #endif static uint16_t pci_vendor_id = 0x1D0F; /* Amazon PCI Vendor ID */ static uint16_t pci_device_id = 0xF001; #define DEFAULT_SLOT_ID 0 /* Hardware settings */ #define ACTIVE_UNITS 16 #define TOTAL_UNITS 16 /* Registers */ #define STATUS_REG_HI 0 #define STATUS_REG_LO 4 #define STATUS_BUSY 0x0000FFFF #define STATUS_DONE 0xFFFF0000 #define CONTROL_REG_HI 8 #define CONTROL_REG_LO 12 #define CONTROL_START 0x0000FFFF #define CONTROL_RESET 0xFFFF0000 #define RETURN_HI 16 #define RETURN_LO 20 #define CFG_OFF_HI 24 #define CFG_OFF_LO 28 #define CFG_DATA_HI 32 #define CFG_DATA_LO 36 #define FIRST_IDX_OFF 40 #define LAST_IDX_OFF FIRST_IDX_OFF + 4*TOTAL_UNITS #define RESULT_OFF LAST_IDX_OFF + 4*TOTAL_UNITS /* Data sizes */ #define MIN_STR_LEN 6 // Must be at least len("kitten") #define MAX_STR_LEN 32 // Must be larger than len("kitten") #define DEFAULT_ROWS 8*1024*1024 // About 1 gigabyte of characters #define BURST_LENGTH 4096 /* Structure to easily convert from 64-bit addresses to 2x32-bit registers */ typedef struct _lohi { uint32_t lo; uint32_t hi; } lohi; typedef union _addr_lohi { uint64_t full; lohi half; } addr_lohi; /* use the stdout logger */ const struct logger *logger = &logger_stdout; void usage(const char *program_name) { INF("usage: %s [<num_rows>] [<slot>]\n", program_name); } static int check_slot_config(int slot_id) { int rc; struct fpga_mgmt_image_info info = {0}; /* get local image description, contains status, vendor id, and device id */ rc = fpga_mgmt_describe_local_image(slot_id, &info, 0); fail_on(rc, out, "Unable to get local image information. Are you running as root?"); /* check to see if the slot is ready */ if (info.status != FPGA_STATUS_LOADED) { rc = 1; fail_on(rc, out, "Slot %d is not ready", slot_id); } /* confirm that the AFI that we expect is in fact loaded */ if (info.spec.map[FPGA_APP_PF].vendor_id != pci_vendor_id || info.spec.map[FPGA_APP_PF].device_id != pci_device_id) { rc = 1; INF( "The slot appears loaded, but the pci vendor or device ID doesn't match the expected values. You may need to rescan the fpga with\n" "fpga-describe-local-image -S %i -R\n" "Note that rescanning can change which device file in /dev/ a FPGA will map to. To remove and re-add your edma driver and reset the device file mappings, run\n" "`sudo rmmod edma-drv && sudo insmod <aws-fpga>/sdk/linux_kernel_drivers/edma/edma-drv.ko`\n", slot_id); fail_on(rc, out, "The PCI vendor id and device of the loaded image are not the expected values."); } out: return rc; } /** * Read and print the strings from the offset and data buffer */ void print_strings(uint32_t *offsets, char *data, int num_rows, int hex) { int offsets_size = num_rows + 1; for (int i = 0; i < offsets_size; i++) { if (i < num_rows) { INF("%6d, %5d, %5d, ", i, offsets[i], offsets[i + 1] - offsets[i]); for (int j = offsets[i]; (j < offsets[i + 1]) && (i < num_rows); j++) { if (hex) { INF("%2X ", data[j]); } else { printf("%c", data[j]); } } } else { INF("%6d, %5d, ", i, offsets[i]); } INF("\n"); } fflush(stdout); } /** * Generate random strings randomly containing some string. */ int gen_rand_strings_with(const char *with, const char *alphabet, uint32_t **idx_buf, char **data_buf, size_t *data_size, uint32_t num_rows) { int strings = 0; size_t length = strlen(with); // Determine offsets buffer size size_t idx_buf_size = sizeof(uint32_t) * (num_rows + 1); uint32_t *offsets_buffer = (uint32_t *) malloc(idx_buf_size); // Set random seed, we always want the same seed for debugging srand(0); // Generate indices // First offset offsets_buffer[0] = 0; // Iterate over rows, inclusive range because of last offset for (uint32_t i = 1; i <= num_rows; i++) { // Generate a string length between min and max offsets_buffer[i] = offsets_buffer[i - 1] + length + ((uint32_t) rand() % (MAX_STR_LEN - MIN_STR_LEN)); } // The last offset is the size of the data buffer *data_size = (size_t) offsets_buffer[num_rows]; // Allocate the data buffer now that we know the total length char *data_buffer = (char *) malloc(sizeof(char) * (*data_size)); // Generate data: for (uint32_t i = 0; i < num_rows; i++) { int has_str = 0; // Generate random characters for (uint32_t j = offsets_buffer[i]; j < offsets_buffer[i + 1];) { // Randomly insert a string and check if it still fits in the current string if ((rand() % MAX_STR_LEN == 0) && (j + length < offsets_buffer[i + 1])) { memcpy(&data_buffer[j], with, length); j += strlen(with); has_str = 1; } else { char chr = alphabet[rand() % strlen(alphabet)]; data_buffer[j] = chr; j += 1; } } strings += has_str; } // Set buffer addresses *idx_buf = offsets_buffer; *data_buf = data_buffer; return strings; } /** * Count the number of strings matching to a regular expression given an offsets and data buffer */ uint32_t count_matches_cpu(const uint32_t *offsets_buffer, const char *data_buffer, const char *regexp_str, uint32_t num_rows) { regex_t regexp; int regexp_ret; char str_buf[MAX_STR_LEN + 1]; regexp_ret = regcomp(&regexp, regexp_str, REG_NOSUB); if (regexp_ret) { fprintf(stderr, "Could not compile regex\n"); exit(1); } uint32_t total_matches = 0; for (int i = 0; i < num_rows; i++) { // Get a pointer to the string const char *str = &data_buffer[offsets_buffer[i]]; // Clear the string buffer memset(str_buf, 0, MAX_STR_LEN + 1); // Calculate the string length int len = offsets_buffer[i + 1] - offsets_buffer[i]; // Copy the string memcpy(str_buf, str, len); // Terminate the string str_buf[len] = '\0'; // Perform the regular expression matching regexp_ret = regexec(&regexp, str_buf, 0, NULL, 0); if (regexp_ret == 0) { total_matches++; } #ifdef DEBUG #ifdef PRINT_STRINGS printf("%6d, %5d, %5d, %s\n", i, !regexp_ret, len, str_buf); #endif #endif } return total_matches; } /** * Count the number of strings matching to a regular expression given an offsets and data buffer in parallel using OpenMP */ uint32_t count_matches_omp(const uint32_t *offsets_buffer, const char *data_buffer, const char *regexp_str, uint32_t num_rows, int threads) { uint32_t total_matches = 0; if (threads == 0) { threads = omp_get_max_threads(); } uint32_t *thread_matches = (uint32_t *) calloc(threads, sizeof(uint32_t)); omp_set_num_threads(threads); #pragma omp parallel { int thread = omp_get_thread_num(); uint32_t matches = 0; regex_t regexp; int regexp_ret; char str_buf[MAX_STR_LEN + 1]; regexp_ret = regcomp(&regexp, regexp_str, REG_NOSUB); if (regexp_ret) { fprintf(stderr, "Could not compile regex\n"); exit(1); } #pragma omp for for (int i = 0; i < num_rows; i++) { // Get a pointer to the string const char *str = &data_buffer[offsets_buffer[i]]; // Clear the string buffer memset(str_buf, 0, MAX_STR_LEN + 1); // Calculate the string length int len = offsets_buffer[i + 1] - offsets_buffer[i]; // Copy the string memcpy(str_buf, str, len); // Terminate the string str_buf[len] = '\0'; // Perform the regular expression matching regexp_ret = regexec(&regexp, str_buf, 0, NULL, 0); if (regexp_ret == 0) { matches++; } } thread_matches[thread] = matches; } for (int i = 0; i < threads; i++) { total_matches += thread_matches[i]; } return total_matches; } /** * Copy the example data */ int copy_buffers(int slot_id, const uint32_t *offsets_buffer, const char *data_buffer, size_t data_size, uint64_t offsets_offset, uint64_t data_offset, uint32_t rows) { int fd, rc; char device_file_name[256]; double start, end; fd = -1; rc = sprintf(device_file_name, "/dev/edma%i_queue_0", slot_id); fail_on((rc = (rc < 0) ? 1 : 0), out, "Unable to format device file name."); INF("device_file_name=%s\n", device_file_name); /* make sure the AFI is loaded and ready */ rc = check_slot_config(slot_id); fail_on(rc, out, "slot config is not correct"); fd = open(device_file_name, O_RDWR); if (fd < 0) { INF( "Cannot open device file %s.\nMaybe the EDMA " "driver isn't installed, isn't modified to attach to the PCI ID of " "your CL, or you're using a device file that doesn't exist?\n" "See the edma_install manual at <aws-fpga>/sdk/linux_kernel_drivers/edma/edma_install.md\n" "Remember that rescanning your FPGA can change the device file.\n" "To remove and re-add your edma driver and reset the device file mappings, run\n" "`sudo rmmod edma-drv && sudo insmod <aws-fpga>/sdk/linux_kernel_drivers/edma/edma-drv.ko`\n", device_file_name); fail_on((rc = (fd < 0) ? 1 : 0), out, "unable to open DMA queue. "); } INF("Device file opened. Writing strings to buffer.\n"); uint32_t offsets_size = rows + 1; double t_copy = 0; INF("Copying offsets buffer: t="); start = omp_get_wtime(); rc = pwrite(fd, offsets_buffer, offsets_size * sizeof(uint32_t), offsets_offset); end = omp_get_wtime(); t_copy += end - start; TIME_PRINT(end - start); INF("\nCopied %d bytes for offsets buffer. \n", rc); INF("Copying data buffer: t="); start = omp_get_wtime(); rc = pwrite(fd, data_buffer, data_size, data_offset); end = omp_get_wtime(); t_copy += end - start; TIME_PRINT(end - start); INF("\nCopied %d bytes for data buffer. \n", rc); INF("Total copy time: %.16g\n", t_copy); fsync(fd); #ifdef DEBUG uint32_t *check_offsets_buffer = (uint32_t *) malloc(offsets_size * sizeof(uint32_t)); char *check_data_buffer = (char *) malloc(data_size * sizeof(char)); INF("Reading back data from FPGA on-board DDR:\n"); rc = pread(fd, check_offsets_buffer, offsets_size * sizeof(uint32_t), offsets_offset); rc = pread(fd, check_data_buffer, data_size * sizeof(char), data_offset); #ifdef PRINT_STRINGS print_strings(check_offsets_buffer, check_data_buffer, rows, 1); #endif INF("Memory compare offsets buffer: %d\n", memcmp(offsets_buffer, check_offsets_buffer, offsets_size * sizeof(uint32_t))); INF("Memory compare data buffer: %d\n", memcmp(data_buffer, check_data_buffer, data_size)); free(check_offsets_buffer); free(check_data_buffer); #endif rc = 0; out: if (fd >= 0) { close(fd); } /* if there is an error code, exit with status 1 */ return (rc != 0 ? 1 : 0); } /** * Configure and run the FPGA regular expression matcher */ int count_matches_fpga(uint64_t offsets_address, uint64_t data_address, int32_t firstIdx, int32_t lastIdx, uint32_t *matches, uint32_t rows) { int rc; int slot_id; addr_lohi conv; uint32_t result = 0xFFFFFFFF; uint32_t status = 0; rc = fpga_pci_init(); fail_on(rc, out, "Unable to initialize the fpga_pci library"); slot_id = 0; int rc_bar1; int pf_id = FPGA_APP_PF; int bar_id = APP_PF_BAR1; pci_bar_handle_t pci_bar_handle = PCI_BAR_HANDLE_INIT; rc_bar1 = fpga_pci_attach(slot_id, pf_id, bar_id, 0, &pci_bar_handle); fail_on(rc_bar1, out, "Unable to attach to the AFI on slot id %d", slot_id); INF("[count_matches_fpga] Initializing registers.\n"); DBG("Offsets buffer address: %016lX\n", offsets_address); DBG("Data buffer address: %016lX\n", data_address); // Reset rc_bar1 = fpga_pci_poke(pci_bar_handle, CONTROL_REG_LO, CONTROL_RESET); // Initialize offsets address conv.full = offsets_address; rc_bar1 = fpga_pci_poke(pci_bar_handle, CFG_OFF_LO, conv.half.lo); rc_bar1 = fpga_pci_poke(pci_bar_handle, CFG_OFF_HI, conv.half.hi); // Initialize data address conv.full = data_address; rc_bar1 = fpga_pci_poke(pci_bar_handle, CFG_DATA_LO, conv.half.lo); rc_bar1 = fpga_pci_poke(pci_bar_handle, CFG_DATA_HI, conv.half.hi); uint32_t match_rows = lastIdx - firstIdx; // Set first and last offset for each unit for (int i = 0; i < ACTIVE_UNITS; i++) { uint32_t first = firstIdx + i * match_rows / ACTIVE_UNITS; uint32_t last = first + match_rows / ACTIVE_UNITS; // 4 * for the proper byte address: rc_bar1 = fpga_pci_poke(pci_bar_handle, FIRST_IDX_OFF + 4 * i, first); rc_bar1 = fpga_pci_poke(pci_bar_handle, LAST_IDX_OFF + 4 * i, last); } #ifdef DEBUG // Check settings: DBG("Reading back settings:\n"); rc_bar1 = fpga_pci_peek(pci_bar_handle, CFG_OFF_HI, &result); rc_bar1 = fpga_pci_peek(pci_bar_handle, CFG_OFF_LO, &result); rc_bar1 = fpga_pci_peek(pci_bar_handle, CFG_DATA_HI, &result); rc_bar1 = fpga_pci_peek(pci_bar_handle, CFG_DATA_LO, &result); for (int i = 0; i < ACTIVE_UNITS; i++) { uint32_t fi, li; rc_bar1 = fpga_pci_peek(pci_bar_handle, FIRST_IDX_OFF + 4 * i, &fi); rc_bar1 = fpga_pci_peek(pci_bar_handle, LAST_IDX_OFF + 4 * i, &li); DBG("Unit %4d firstIdx - lastIdx : %16d .. %16d\n", i, fi, li); } #endif INF("[count_matches_fpga] Starting RegExp matchers and polling until done: "); fflush(stdout); #ifndef DEBUG double start = omp_get_wtime(); #endif rc_bar1 = fpga_pci_poke(pci_bar_handle, CONTROL_REG_LO, CONTROL_START); // Wait until completed - poll status do { #ifdef DEBUG // Poll slowly in debug sleep(1); INF("------------------------------\n"); rc_bar1 = fpga_pci_peek(pci_bar_handle, STATUS_REG_LO, &status); INF("Status : %08X\n", status); #else // Poll fast usleep(10); rc_bar1 = fpga_pci_peek(pci_bar_handle, STATUS_REG_LO, &status); #endif } while (status != STATUS_DONE); #ifndef DEBUG double end = omp_get_wtime(); INF("FPGA t="); TIME_PRINT(end-start); INF("\n"); #endif // Read the return registers (not necessary) //rc_bar1 = fpga_pci_peek(pci_bar_handle, 4*RETURN_HI, &result); //rc_bar1 = fpga_pci_peek(pci_bar_handle, 4*RETURN_LO, &result); uint32_t fpga_matches = 0; /* Calculate total matches */ for (int i = 0; i < ACTIVE_UNITS; i++) { rc_bar1 = fpga_pci_peek(pci_bar_handle, (RESULT_OFF + 4 * i), &result); INF("Unit %4d result: %d\n", i, result); fpga_matches += result; } // Just get unit 9 matches for comparison (kitten matcher) rc_bar1 = fpga_pci_peek(pci_bar_handle, (RESULT_OFF + 4 * 9), &result); *matches = result; out: /* Clean up */ if (pci_bar_handle >= 0) { rc = fpga_pci_detach(pci_bar_handle); if (rc) { INF("Failure while detaching from the fpga.\n"); } } /* if there is an error code, exit with status 1 */ return (rc != 0 ? 1 : 0); } /** * Main */ int main(int argc, char **argv) { const char insstring[] = "kitten"; const char insstring_regexp[] = ".*[Kk][Ii][Tt][Tt][Ee][Nn].*"; const char alphabet[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; int rc; int slot_id = DEFAULT_SLOT_ID; int rows = DEFAULT_ROWS; switch (argc) { case 1:break; case 2:sscanf(argv[1], "%u", &rows); if (rows < 0) { usage(argv[0]); return 1; } break; case 3:sscanf(argv[1], "%d", &rows); sscanf(argv[2], "%x", &slot_id); break; default:usage(argv[0]); return 1; } /* Setup logging to print to stdout */ rc = log_init("test_arrow_utf8"); fail_on(rc, out, "Unable to initialize the log."); rc = log_attach(logger, NULL, 0); fail_on(rc, out, "%s", "Unable to attach to the log."); /* Initialize the fpga_plat library */ INF("Initializing FPGA management library\n"); rc = fpga_mgmt_init(); fail_on(rc, out, "Unable to initialize the fpga_mgmt library"); double start, end; /* Generate the offsets and data buffer */ uint32_t *offsets_buffer; char *data_buffer; size_t data_size; INF("Generating random strings containing %s\n", insstring); start = omp_get_wtime(); int insertions = gen_rand_strings_with(insstring, alphabet, &offsets_buffer, &data_buffer, &data_size, rows); end = omp_get_wtime(); TIME_PRINT(end - start); #ifdef DEBUG #ifdef PRINT_STRINGS print_strings(offsets_buffer, data_buffer, rows, 1); #endif #endif INF(" Generated %d strings of which %d contain at least one deliberately inserted \"%s\".\n", rows, insertions, insstring); INF(" It could be that more generated strings randomly contain it, especially in a large number of strings.\n"); /* Match the strings on CPU */ start = omp_get_wtime(); #ifdef USE_OMP INF("RegExping on CPU in parallel: t="); uint32_t cpu_matches = count_matches_omp(offsets_buffer, data_buffer, insstring_regexp, rows, 0); #else INF("RegExping on CPU on single core: t="); uint32_t cpu_matches = count_matches_cpu(offsets_buffer, data_buffer, insstring_regexp, rows); #endif end = omp_get_wtime(); TIME_PRINT(end - start); INF("\nCPU RegExp matches %s %d times.\n", insstring_regexp, cpu_matches); /* Calculate the location of the buffers in the on-board memory */ // Buffers must be aligned to burst boundaries (Currently a Fletcher spec, this will be changed to Arrow alignment spec) uint64_t offsets_addr = (uint64_t)(0); uint64_t data_addr = (uint64_t)(offsets_addr + ((rows * sizeof(uint32_t)) / BURST_LENGTH + 1) * BURST_LENGTH); /* Copy the buffers to FPGA on-board memory */ INF("Copy data to FPGA on-board memory.\n"); rc = copy_buffers(slot_id, offsets_buffer, data_buffer, data_size, offsets_addr, data_addr, rows); fail_on(rc, out, "Data copy failed"); sleep(1); /* Perform regular expression matching on FPGA */ INF("RegExping on FPGA\n"); uint32_t fpga_matches = 0xFFFFFFFF; rc = count_matches_fpga(offsets_addr, data_addr, 0, rows, &fpga_matches, rows); INF("FPGA RegExp matches %s %d times.\n", insstring_regexp, fpga_matches); printf("%16lu, %16d, %16d, %16d, %16d\n", sizeof(uint32_t) * (rows + 1), (uint32_t) data_size, cpu_matches, fpga_matches, insertions); if (fpga_matches == cpu_matches) { INF("TEST PASSED\n"); } else { INF("TEST FAILED\n"); } fail_on(rc, out, "Data copy failed"); out: if (offsets_buffer != NULL) { free(offsets_buffer); } if (data_buffer != NULL) { free(data_buffer); } printf("%f", end - start); return rc; }
exponentialRashba.h
/*************************************************************************** * Copyright (C) 2014 by Florian Goth * * fgoth@wthp095 * * * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ***************************************************************************/ #ifndef EXPONENTIAL_RASHBA_CHAIN_H #define EXPONENTIAL_RASHBA_CHAIN_H #include <complex> #include <limits> #include "ddqmc.h" #include "Vertex.h" #include "Greensfunction.h" /** An implementation of a 1D chain with an added Rashba-type interaction. the transition rates decay exponentially I assume that the lattice constant is a = 1 */ template<typename FPType = float> class ExponentialRashbaChain { public: enum {timeevolution = 0, has_Spin_symmetry = true,//helical base has_Giomega = false, Is_Impurity_model = false, has_TRS = true, }; typedef Hubbard_Vertex<FPType> Vertex; typedef std::complex<FPType> FreeGreensFunctionReturnValueType;///< a typedef of the data type of the free greensfunction /** This evaluates the value of the free particle Green-function for the two given vertices @param v1 the first vertex @param v2 the second vertex @return the value of the free greensfunction evaluated with the given vertices */ static inline FreeGreensFunctionReturnValueType eval(const Vertex& v1, const Vertex& v2) throw(); /** A function for initializing the tables that make up the Greensfunction. Beta and the nr of sites are read from config files @param CFG a class that contains the necessary information to extract the parameters. */ template <class CFG> static inline void init(CFG&); /** This function frees the memory used by the tables for the Greensfunction */ static inline void tidyup(); /** To access the nr of atoms of the chain @return the nr of atoms in the chain */ static unsigned int getLen() throw() { return N; } /** Get the length of the interactioninterval. @return the inverse temperature beta */ static FPType getContourLen() throw() { return beta; } private: static std::complex<FPType>* g;///< the free particle greensfunction. We store the up and down part next to each other in a complex number. If we use the symmetry some time in the future this might be helpful. Note that we switch to a flat array. static unsigned int slices;///< the number of timeslices. This means the resolution of the free greensfunction in tau space static FPType betaslice;///< The length of one timeslice on the tau axis static FPType beta;///< The inverse temperature beta static unsigned int N;///< The length of the chain /** the Dispersionrelation -2t cos(k) -my . Note that the chemical potential is included here. @param k the momentum @param t the kinetic energy @param my the chemical potential @param lambda the spin-orbit strength @return the energy */ static inline FPType disp(FPType k, FPType t, FPType my, FPType lambda, FPType alpha) throw(); // /** // * The free particle Greens function in k-space for the up - up part and for the down-down part // @param k the momentum // @param tau the imaginary time // @param t the kinetic energy // @param my the chemical potential // @param lambda the spin-orbit strength // */ // static inline FPType GreenNullKSpacediag(FPType k, FPType tau, FPType t, FPType my, FPType lambda) throw(); // /** // * The free particle Greens function in k-space for the up - down part as well as the down-up part // * since they are symmetric. // @param k the momentum // @param tau the imaginary time // @param t the kinetic energy // @param my the chemical potential // @param lambda the spin-orbit strength // */ // static inline FPType GreenNullKSpaceoffdiag(FPType k, FPType tau, FPType t, FPType my, FPType lambda) throw(); /** * This Green's function should suffice to specify the necessary Green's function. * After the Fourier-transform the spin-diagonal G can be recovered from the real part and the * off-diagonal from the imaginary part. @param k the momentum @param tau the imaginary time @param t the kinetic energy @param my the chemical potential @param lambda the spin-orbit strength */ static inline FPType GreenNullKSpace(FPType k, FPType tau, FPType t, FPType my, FPType lambda, FPType alpha) throw(); }; template <typename FPType> FPType ExponentialRashbaChain<FPType>::disp(FPType k, FPType t, FPType my, FPType lambda, FPType alpha) throw()//some system function seems to be also called epsilon { FPType p = std::atan(lambda); return std::sqrt(t*t + lambda * lambda)* std::cos(k + p)/(2*std::cosh(alpha) - 2.0*std::cos(k)); } // template <typename FPType> // FPType PowerLawRashbaChain<FPType>::GreenNullKSpacediag(FPType k, FPType tau, FPType t, FPType my, FPType lambda) throw() // { // FPType ep = disp(k, t, my, lambda); // FPType em = disp(k, t, my, -lambda); // return 0.5*(std::exp( ep * tau) * fermi(beta * ep) + std::exp(em * tau) * fermi(beta * em)); // } // // template <typename FPType> // FPType PowerLawRashbaChain<FPType>::GreenNullKSpaceoffdiag(FPType k, FPType tau, FPType t, FPType my, FPType lambda) throw() // {//remember to add the correct i or -i // FPType ep = disp(k, t, my, lambda); // FPType em = disp(k, t, my, -lambda); // return 0.5*(std::exp( ep * tau) * fermi(beta * ep) - std::exp(em * tau) * fermi(beta * em)); // } template <typename FPType> FPType ExponentialRashbaChain<FPType>::GreenNullKSpace(FPType k, FPType tau, FPType t, FPType my, FPType lambda, FPType alpha) throw() { FPType ep = disp(k, t, my, lambda, alpha); FPType retval; // std::cout<<ep*tau <<"> "<<std::log(0.01*std::numeric_limits<FPType>::max())<<std::endl; if(ep*tau > std::log(0.01*std::numeric_limits<FPType>::max())) retval = 0.5*std::exp(ep*(tau - beta/2))/std::cosh(ep*beta/2); else retval = std::exp( ep * tau) * fermi(beta * ep); return retval; } template<typename FPType> std::complex<FPType>* ExponentialRashbaChain<FPType>::g = NULL; template<typename FPType> FPType ExponentialRashbaChain<FPType>::betaslice; template<typename FPType> FPType ExponentialRashbaChain<FPType>::beta; template<typename FPType> unsigned int ExponentialRashbaChain<FPType>::N; template<typename FPType> unsigned int ExponentialRashbaChain<FPType>::slices; template <typename FPType> void ExponentialRashbaChain<FPType>::tidyup() { delete [] g; } template <typename FPType> template <class CFG> void ExponentialRashbaChain<FPType>::init(CFG& curparams) { //lattice sites N = curparams.N; beta = curparams.beta; slices = 100000;//Number of TimeSlices const unsigned int slicesp = slices + 1; betaslice = beta / static_cast<FPType>(slices); g = new std::complex<FPType>[slicesp * N]; // if (N == 1)//take special care of the 1 site hubbard model // { // for (unsigned int j = 0; j < slicesp; ++j) // { // g[j] = std::complex<FPType>(GreenNullKSpacediag(0, j * betaslice, curparams.t, curparams.mu, curparams.lambda), // GreenNullKSpaceoffdiag(0, j * betaslice, curparams.t, curparams.mu, curparams.lambda)); // // std::cout<<j * betaslice<<" "<<g[j][0]<<std::endl; // } // return; // } #pragma omp parallel for for (int j = 0; j < static_cast<int>(N); ++j)//for every realspacepoint { for (int i = 0; i < static_cast<int>(slicesp); ++i)//for every timeslice { std::complex<FPType> tempsum = 0; for (uint k = 0; k < N; ++k)//sum over all k-space values { const std::complex<FPType> expkj = exp(std::complex<FPType>(0.0, 2.0 * M_PI/N * static_cast<FPType>(k * j)) ); FPType temp = GreenNullKSpace(2*k*M_PI/N, i * betaslice, curparams.t, curparams.mu, curparams.lambda, curparams.alpha); // std::cout<<k<<" "<<temp<<std::endl; // if ( std::isnan(temp) ) exit(-1); tempsum += expkj * temp;//R_j = j, because the lattice constant is assumed to be equal to one. } g[j*slicesp + i] = tempsum/static_cast<FPType>(N); } } //Debugging Output /*std::ofstream dbg("dbg.txt"); for(uint n = 0; n < N; ++n) { for(unsigned int i = 0; i < slicesp; ++i) { dbg<<(i * betaslice)<<" "<<-imag(g[n*slicesp + i]); dbg<<std::endl; } dbg<<"&"<<std::endl; } exit(-1);*/ return; } template<typename FPType> typename ExponentialRashbaChain<FPType>::FreeGreensFunctionReturnValueType ExponentialRashbaChain<FPType>::eval(const Vertex& v1, const Vertex& v2) throw() { //determine the differences between the two FPType delta_tau = v1.tau - v2.tau; int delta = v1.site - v2.site; //Take care of negative values if (delta < 0) delta = N + delta;//because delta is in this case already a negative number const std::complex<FPType> *const addr = g + delta*(slices + 1);//addr points to the memory area where the GF of the particular site resides. //Take care of negative values uint signchanges = 0; while (delta_tau < 0) { delta_tau += beta; ++signchanges; } while (delta_tau > beta) { delta_tau -= beta; ++signchanges; } FPType sign = (signchanges & 1? -1.0 : 1.0); if (fpequal(v1.tau, v2.tau)) { //return only the particle number return sign * addr[0]; } if (fpequal(delta_tau, beta)) return sign * addr[slices]; FPType fptau_idx0; FPType rem = std::modf(delta_tau/betaslice, &fptau_idx0);//round to the smaller index and determine how far we're of long int tau_idx0 = lround(fptau_idx0); return lerp(rem, addr[tau_idx0], addr[tau_idx0 + 1]) * sign;//return the value of the greensfunction } #endif
GB_binop__band_uint8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__band_uint8) // A.*B function (eWiseMult): GB (_AemultB_08__band_uint8) // A.*B function (eWiseMult): GB (_AemultB_02__band_uint8) // A.*B function (eWiseMult): GB (_AemultB_04__band_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__band_uint8) // A*D function (colscale): GB (_AxD__band_uint8) // D*A function (rowscale): GB (_DxB__band_uint8) // C+=B function (dense accum): GB (_Cdense_accumB__band_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__band_uint8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__band_uint8) // C=scalar+B GB (_bind1st__band_uint8) // C=scalar+B' GB (_bind1st_tran__band_uint8) // C=A+scalar GB (_bind2nd__band_uint8) // C=A'+scalar GB (_bind2nd_tran__band_uint8) // C type: uint8_t // A type: uint8_t // A pattern? 0 // B type: uint8_t // B pattern? 0 // BinaryOp: cij = (aij) & (bij) #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_t #define GB_CTYPE \ uint8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint8_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint8_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x) & (y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BAND || GxB_NO_UINT8 || GxB_NO_BAND_UINT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__band_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__band_uint8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__band_uint8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint8_t uint8_t bwork = (*((uint8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__band_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__band_uint8) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__band_uint8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint8_t alpha_scalar ; uint8_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint8_t *) alpha_scalar_in)) ; beta_scalar = (*((uint8_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__band_uint8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__band_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__band_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__band_uint8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__band_uint8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t x = (*((uint8_t *) x_input)) ; uint8_t *Bx = (uint8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint8_t bij = GBX (Bx, p, false) ; Cx [p] = (x) & (bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__band_uint8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t *Ax = (uint8_t *) Ax_input ; uint8_t y = (*((uint8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint8_t aij = GBX (Ax, p, false) ; Cx [p] = (aij) & (y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x) & (aij) ; \ } GrB_Info GB (_bind1st_tran__band_uint8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij) & (y) ; \ } GrB_Info GB (_bind2nd_tran__band_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t y = (*((const uint8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
JointWMF.h
/***************************************************************/ /* * Distribution code Version 1.1 -- 09/21/2014 by Qi Zhang Copyright 2014, The Chinese University of Hong Kong. * * The Code is created based on the method described in the following paper * [1] "100+ Times Faster Weighted Median Filter", Qi Zhang, Li Xu, Jiaya Jia, IEEE Conference on * Computer Vision and Pattern Recognition (CVPR), 2014 * * Due to the adaption for supporting mask and different types of input, this code is * slightly slower than the one claimed in the original paper. Please use * our executable on our website for performance comparison. * * The code and the algorithm are for non-comercial use only. * /***************************************************************/ #ifndef JOINT_WMF_H #define JOINT_WMF_H /***************************************************************/ /* * Standard IO library is required. * STL String library is required. * /***************************************************************/ #include <cstdio> #include <string> /***************************************************************/ /* * OpenCV 2.4 is required. * The following code is already built on OpenCV 2.4.2. * /***************************************************************/ #include "opencv2/core/core.hpp" #include <time.h> #include <omp.h> //Use the namespace of CV and STD using namespace std; using namespace cv; class JointWMF{ public: /***************************************************************/ /* Function: filter * * Description: filter implementation of joint-histogram weighted median framework * including clustering of feature image, adaptive quantization of input image. * * Input arguments: * I: input image (any # of channels). Accept only CV_32F and CV_8U type. * feature: the feature image ("F" in the paper). Accept only CV_8UC1 and CV_8UC3 type (the # of channels should be 1 or 3). * r: radius of filtering kernel, should be a positive integer. * sigma: filter range standard deviation for the feature image. * nI: # of quantization level of input image. (only when the input image is CV_32F type) * nF: # of clusters of feature value. (only when the feature image is 3-channel) * iter: # of filtering times/iterations. (without changing the feature map) * weightType: the type of weight definition, including: * exp: exp(-|I1-I2|^2/(2*sigma^2)) * iv1: (|I1-I2|+sigma)^-1 * iv2: (|I1-I2|^2+sigma^2)^-1 * cos: dot(I1,I2)/(|I1|*|I2|) * jac: (min(r1,r2)+min(g1,g2)+min(b1,b2))/(max(r1,r2)+max(g1,g2)+max(b1,b2)) * off: unweighted * mask: a 0-1 mask that has the same size with I. This mask is used to ignore the effect of some pixels. If the pixel value on mask is 0, * the pixel will be ignored when maintaining the joint-histogram. This is useful for applications like optical flow occlusion handling. * * Note: * 1. When feature image clustering (when F is 3-channel) OR adaptive quantization (when I is floating point image) is * performed, the result is an approximation. To increase the accuracy, using a larger "nI" or "nF" will help. * */ /***************************************************************/ static Mat filter(Mat &I, Mat &feature, int r, float sigma=25.5, int nI=256, int nF=256, int iter=1, string weightType="exp", Mat mask=Mat()){ Mat F = feature.clone(); //check validation assert(I.depth() == CV_32F || I.depth() == CV_8U); assert(F.depth() == CV_8U && (F.channels()==1 || F.channels()==3)); //declaration Mat result; //Preprocess I //OUTPUT OF THIS STEP: Is, iMap //If I is floating point image, "adaptive quantization" is done in from32FTo32S. //The mapping of floating value to integer value is stored in iMap (for each channel). //"Is" stores each channel of "I". The channels are converted to CV_32S type after this step. vector<float *> iMap(I.channels()); vector<Mat> Is; { split(I,Is); for(int i=0;i<(int)Is.size();i++){ if(I.depth()==CV_32F){ iMap[i] = new float[nI]; from32FTo32S(Is[i],Is[i],nI,iMap[i]); } else if(I.depth()==CV_8U){ Is[i].convertTo(Is[i],CV_32S); } } } //Preprocess F //OUTPUT OF THIS STEP: F(new), wMap //If "F" is 3-channel image, "clustering feature image" is done in featureIndexing. //If "F" is 1-channel image, featureIndexing only does a type-casting on "F". //The output "F" is CV_32S type, containing indexes of feature values. //"wMap" is a 2D array that defines the distance between each pair of feature indexes. // wMap[i][j] is the weight between feature index "i" and "j". float **wMap; { featureIndexing(F, wMap, nF, sigma, weightType); } //Filtering - Joint-Histogram Framework { for(int i=0;i<(int)Is.size();i++){ for(int k=0;k<iter;k++){ {//Do filtering Is[i] = filterCore(Is[i], F, wMap, r, nF,nI,mask); } } } } float2D_release(wMap); //Postprocess F //Convert input image back to the original type. { for(int i=0;i<(int)Is.size();i++){ if(I.depth()==CV_32F){ from32STo32F(Is[i],Is[i],iMap[i]); delete []iMap[i]; } else if(I.depth()==CV_8U){ Is[i].convertTo(Is[i],CV_8U); } } } //merge the channels merge(Is,result); //end of the function return result; } /***************************************************************/ /* Function: filterCore * * Description: filter core implementation only containing joint-histogram weighted median framework * * input arguments: * I: input image. Only accept CV_32S type. * F: feature image. Only accept CV_32S type. * wMap: a 2D array that defines the distance between each pair of feature values. wMap[i][j] is the weight between feature value "i" and "j". * r: radius of filtering kernel, should be a positive integer. * nI: # of possible values in I, i.e., all values of I should in range [0, nI) * nF: # of possible values in F, i.e., all values of F should in range [0, nF) * mask: a 0-1 mask that has the same size with I, for ignoring the effect of some pixels, as introduced in function "filter" */ /***************************************************************/ static Mat filterCore(Mat &I, Mat &F, float **wMap, int r=20, int nF=256, int nI=256, Mat mask=Mat()){ // Check validation assert(I.depth() == CV_32S && I.channels()==1);//input image: 32SC1 assert(F.depth() == CV_32S && F.channels()==1);//feature image: 32SC1 // Configuration and declaration int rows = I.rows, cols = I.cols; int alls = rows * cols; int winSize = (2*r+1)*(2*r+1); Mat outImg = I.clone(); // Handle Mask if(mask.empty()){ mask = Mat(I.size(),CV_8U); mask = Scalar(1); } // Allocate memory for joint-histogram and BCB int **H = int2D(nI,nF); int *BCB = new int[nF]; // Allocate links for necklace table int **Hf = int2D(nI,nF);//forward link int **Hb = int2D(nI,nF);//backward link int *BCBf = new int[nF];//forward link int *BCBb = new int[nF];//backward link // Column Scanning for(int x=0;x<cols;x++){ // Reset histogram and BCB for each column memset(BCB, 0, sizeof(int)*nF); memset(H[0], 0, sizeof(int)*nF*nI); for(int i=0;i<nI;i++)Hf[i][0]=Hb[i][0]=0; BCBf[0]=BCBb[0]=0; // Reset cut-point int medianVal = -1; // Precompute "x" range and checks boundary int downX = max(0,x-r); int upX = min(cols-1,x+r); // Initialize joint-histogram and BCB for the first window { int upY = min(rows-1,r); for(int i=0;i<=upY;i++){ int *IPtr = I.ptr<int>(i); int *FPtr = F.ptr<int>(i); uchar *maskPtr = mask.ptr<uchar>(i); for(int j=downX;j<=upX;j++){ if(!maskPtr[j])continue; int fval = IPtr[j]; int *curHist = H[fval]; int gval = FPtr[j]; // Maintain necklace table of joint-histogram if(!curHist[gval] && gval){ int *curHf = Hf[fval]; int *curHb = Hb[fval]; int p1=0,p2=curHf[0]; curHf[p1]=gval; curHf[gval]=p2; curHb[p2]=gval; curHb[gval]=p1; } curHist[gval]++; // Maintain necklace table of BCB updateBCB(BCB[gval],BCBf,BCBb,gval,-1); } } } for(int y=0;y<rows;y++){ // Find weighted median with help of BCB and joint-histogram { float balanceWeight = 0; int curIndex = F.ptr<int>(y,x)[0]; float *fPtr = wMap[curIndex]; int &curMedianVal = medianVal; // Compute current balance int i=0; do{ balanceWeight += BCB[i]*fPtr[i]; i=BCBf[i]; }while(i); // Move cut-point to the left if(balanceWeight >= 0){ for(;balanceWeight >= 0 && curMedianVal;curMedianVal--){ float curWeight = 0; int *nextHist = H[curMedianVal]; int *nextHf = Hf[curMedianVal]; // Compute weight change by shift cut-point int i=0; do{ curWeight += (nextHist[i]<<1)*fPtr[i]; // Update BCB and maintain the necklace table of BCB updateBCB(BCB[i],BCBf,BCBb,i,-(nextHist[i]<<1)); i=nextHf[i]; }while(i); balanceWeight -= curWeight; } } // Move cut-point to the right else if(balanceWeight < 0){ for(;balanceWeight < 0 && curMedianVal != nI-1; curMedianVal++){ float curWeight = 0; int *nextHist = H[curMedianVal+1]; int *nextHf = Hf[curMedianVal+1]; // Compute weight change by shift cut-point int i=0; do{ curWeight += (nextHist[i]<<1)*fPtr[i]; // Update BCB and maintain the necklace table of BCB updateBCB(BCB[i],BCBf,BCBb,i,nextHist[i]<<1); i=nextHf[i]; }while(i); balanceWeight += curWeight; } } // Weighted median is found and written to the output image if(balanceWeight<0)outImg.ptr<int>(y,x)[0] = curMedianVal+1; else outImg.ptr<int>(y,x)[0] = curMedianVal; } // Update joint-histogram and BCB when local window is shifted. { int fval,gval,*curHist; // Add entering pixels into joint-histogram and BCB { int rownum = y + r + 1; if(rownum < rows){ int *inputImgPtr = I.ptr<int>(rownum); int *guideImgPtr = F.ptr<int>(rownum); uchar *maskPtr = mask.ptr<uchar>(rownum); for(int j=downX;j<=upX;j++){ if(!maskPtr[j])continue; fval = inputImgPtr[j]; curHist = H[fval]; gval = guideImgPtr[j]; // Maintain necklace table of joint-histogram if(!curHist[gval] && gval){ int *curHf = Hf[fval]; int *curHb = Hb[fval]; int p1=0,p2=curHf[0]; curHf[gval]=p2; curHb[gval]=p1; curHf[p1]=curHb[p2]=gval; } curHist[gval]++; // Maintain necklace table of BCB updateBCB(BCB[gval],BCBf,BCBb,gval,((fval <= medianVal)<<1)-1); } } } // Delete leaving pixels into joint-histogram and BCB { int rownum = y - r; if(rownum >= 0){ int *inputImgPtr = I.ptr<int>(rownum); int *guideImgPtr = F.ptr<int>(rownum); uchar *maskPtr = mask.ptr<uchar>(rownum); for(int j=downX;j<=upX;j++){ if(!maskPtr[j])continue; fval = inputImgPtr[j]; curHist = H[fval]; gval = guideImgPtr[j]; curHist[gval]--; // Maintain necklace table of joint-histogram if(!curHist[gval] && gval){ int *curHf = Hf[fval]; int *curHb = Hb[fval]; int p1=curHb[gval],p2=curHf[gval]; curHf[p1]=p2; curHb[p2]=p1; } // Maintain necklace table of BCB updateBCB(BCB[gval],BCBf,BCBb,gval,-((fval <= medianVal)<<1)+1); } } } } } } // Deallocate the memory { delete []BCB; delete []BCBf; delete []BCBb; int2D_release(H); int2D_release(Hf); int2D_release(Hb); } // end of the function return outImg; } private: static float get_rt(){ struct timeval realtime; clock_gettime(0,&realtime); return (float)(realtime.tv_sec*1000000+realtime.tv_usec); } /***************************************************************/ /* Function: updateBCB * Description: maintain the necklace table of BCB /***************************************************************/ static inline void updateBCB(int &num,int *f,int *b,int i,int v){ static int p1,p2; if(i){ if(!num){ // cell is becoming non-empty p2=f[0]; f[0]=i; f[i]=p2; b[p2]=i; b[i]=0; } else if(!(num+v)){// cell is becoming empty p1=b[i],p2=f[i]; f[p1]=p2; b[p2]=p1; } } // update the cell count num += v; } /***************************************************************/ /* Function: float2D * Description: allocate a 2D float array with dimension "dim1 x dim2" /***************************************************************/ static float** float2D(int dim1, int dim2){ float **ret = new float*[dim1]; ret[0] = new float[dim1*dim2]; for(int i=1;i<dim1;i++)ret[i] = ret[i-1]+dim2; return ret; } /***************************************************************/ /* Function: float2D_release * Description: deallocate the 2D array created by float2D() /***************************************************************/ static void float2D_release(float **p){ delete []p[0]; delete []p; } /***************************************************************/ /* Function: int2D * Description: allocate a 2D integer array with dimension "dim1 x dim2" /***************************************************************/ static int** int2D(int dim1, int dim2){ int **ret = new int*[dim1]; ret[0] = new int[dim1*dim2]; for(int i=1;i<dim1;i++)ret[i] = ret[i-1]+dim2; return ret; } /***************************************************************/ /* Function: int2D_release * Description: deallocate the 2D array created by int2D() /***************************************************************/ static void int2D_release(int **p){ delete []p[0]; delete []p; } /***************************************************************/ /* Function: featureIndexing * Description: convert uchar feature image "F" to CV_32SC1 type. * If F is 3-channel, perform k-means clustering * If F is 1-channel, only perform type-casting /***************************************************************/ static void featureIndexing(Mat &F, float **&wMap, int &nF, float sigmaI, string weightType){ // Configuration and Declaration Mat FNew; int cols = F.cols, rows = F.rows; int alls = cols * rows; int KmeansAttempts=1; vector<string> ops; ops.push_back("exp"); ops.push_back("iv1"); ops.push_back("iv2"); ops.push_back("cos"); ops.push_back("jac"); ops.push_back("off"); // Get weight type number int numOfOps = (int)ops.size(); int op = 0; for(;op<numOfOps;op++)if(ops[op] == weightType)break; if(op>=numOfOps)op=0; /* For 1 channel feature image (uchar)*/ if(F.channels() == 1){ nF = 256; // Type-casting F.convertTo(FNew, CV_32S); // Computer weight map (weight between each pair of feature index) { wMap = float2D(nF,nF); float nSigmaI = sigmaI; float divider = (1.0f/(2*nSigmaI*nSigmaI)); for(int i=0;i<nF;i++){ for(int j=i;j<nF;j++){ float diff = fabs((float)(i-j)); if(op==0)wMap[i][j] = wMap[j][i] = exp(-(diff*diff)*divider); // EXP 2 else if(op==2)wMap[i][j] = wMap[j][i] = 1.0f / (diff*diff+nSigmaI*nSigmaI); // IV2 else if(op==1)wMap[i][j] = wMap[j][i] = 1.0f/(diff+nSigmaI);// IV1 else if(op==3)wMap[i][j] = wMap[j][i] = 1.0f; // COS else if(op==4)wMap[i][j] = wMap[j][i] = (float)(min(i,j)*1.0/max(i,j)); // Jacard else if(op==5)wMap[i][j] = wMap[j][i] = 1.0f; // Unweighted } } } } /* For 3 channel feature image (uchar)*/ else if(F.channels() == 3){ const int shift = 2; // 256(8-bit)->64(6-bit) const int LOW_NUM = 256>>shift; static int hash[LOW_NUM][LOW_NUM][LOW_NUM]={0}; memset(hash,0,sizeof(hash)); // throw pixels into a 2D histogram int candCnt = 0; { int lowR,lowG,lowB; uchar *FPtr = F.ptr<uchar>(); for(int i=0,i3=0;i<alls;i++,i3+=3){ lowB = FPtr[i3]>>shift; lowG = FPtr[i3+1]>>shift; lowR = FPtr[i3+2]>>shift; if(hash[lowB][lowG][lowR]==0){ candCnt++; hash[lowB][lowG][lowR]=1; } } } nF = min(nF, candCnt); Mat samples(candCnt,3,CV_32F); //prepare for K-means { int top=0; for(int i=0;i<LOW_NUM;i++)for(int j=0;j<LOW_NUM;j++)for(int k=0;k<LOW_NUM;k++){ if(hash[i][j][k]){ samples.ptr<float>(top)[0] = (float)i; samples.ptr<float>(top)[1] = (float)j; samples.ptr<float>(top)[2] = (float)k; top++; } } } //do K-means Mat labels; Mat centers; { kmeans(samples, nF, labels, TermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 0, 10000), KmeansAttempts, KMEANS_PP_CENTERS, centers ); } //make connection (i,j,k) <-> index { int top = 0; for(int i=0;i<LOW_NUM;i++)for(int j=0;j<LOW_NUM;j++)for(int k=0;k<LOW_NUM;k++){ if(hash[i][j][k]){ hash[i][j][k] = labels.ptr<int>(top)[0]; top++; } } } // generate index map { FNew = Mat(F.size(),CV_32SC1); int lowR,lowG,lowB; uchar *FPtr = F.ptr<uchar>(); for(int i=0,i3=0;i<alls;i++,i3+=3){ lowB = FPtr[i3]>>shift; lowG = FPtr[i3+1]>>shift; lowR = FPtr[i3+2]>>shift; FNew.ptr<int>()[i] = hash[lowB][lowG][lowR]; } } // Computer weight map (weight between each pair of feature index) { wMap = float2D(nF,nF); float nSigmaI = sigmaI/256.0f*LOW_NUM; float divider = (1.0f/(2*nSigmaI*nSigmaI)); float *length = new float[nF]; for(int i=0;i<nF;i++){ float a0 = centers.ptr<float>(i)[0]; float a1 = centers.ptr<float>(i)[1]; float a2 = centers.ptr<float>(i)[2]; length[i] = sqrt(a0*a0+a1*a1+a2*a2); } for(int i=0;i<nF;i++){ for(int j=i;j<nF;j++){ float a0 = centers.ptr<float>(i)[0], b0 = centers.ptr<float>(j)[0]; float a1 = centers.ptr<float>(i)[1], b1 = centers.ptr<float>(j)[1]; float a2 = centers.ptr<float>(i)[2], b2 = centers.ptr<float>(j)[2]; float diff0 = a0-b0; float diff1 = a1-b1; float diff2 = a2-b2; if(op==0)wMap[i][j] = wMap[j][i] = exp(-(diff0*diff0+diff1*diff1+diff2*diff2)*divider); // EXP 2 else if(op==2)wMap[i][j] = wMap[j][i] = 1.0f / (diff0*diff0+diff1*diff1+diff2*diff2+nSigmaI*nSigmaI); // IV2 else if(op==1)wMap[i][j] = wMap[j][i] = 1.0f/(fabs(diff0)+fabs(diff1)+fabs(diff2)+nSigmaI);// IV1 else if(op==3)wMap[i][j] = wMap[j][i] = (a0*b0+a1*b1+a2*b2)/(length[i]*length[j]); // COS else if(op==4)wMap[i][j] = wMap[j][i] = (min(a0,b0)+min(a1,b1)+min(a2,b2))/(max(a0,b0)+max(a1,b1)+max(a2,b2)); // Jacard else if(op==5)wMap[i][j] = wMap[j][i] = 1.0f; // Unweighted } } delete []length; } } //end of the function F = FNew; } /***************************************************************/ /* Function: from32FTo32S * Description: adaptive quantization for changing a floating-point 1D image to integer image. * The adaptive quantization strategy is based on binary search, which searches an * upper bound of quantization error. * The function also return a mapping between quantized value (32F) and quantized index (32S). * The mapping is used to convert integer image back to floating-point image after filtering. /***************************************************************/ static void from32FTo32S(Mat &img, Mat &outImg, int nI, float *mapping){ int rows = img.rows, cols = img.cols; int alls = rows * cols; float *imgPtr = img.ptr<float>(); typedef pair<float,int> pairFI; pairFI *data = (pairFI *)malloc(alls*sizeof(pairFI)); // Sort all pixels of the image by ascending order of pixel value { #pragma omp parallel for for(int i=0;i<alls;i++){ data[i].second = i; data[i].first = imgPtr[i]; } sort(data,data+alls); } // Find lower bound and upper bound of the pixel values double maxVal,minVal; minMaxLoc(img,&minVal,&maxVal); float maxRange = (float)(maxVal - minVal); float th = 1e-5f; float l = 0, r = maxRange*2.0f/nI; // Perform binary search on error bound while(r-l > th){ float m = (r+l)*0.5f; bool suc = true; float base = (float)minVal; int cnt=0; for(int i=0;i<alls;i++){ if(data[i].first>base+m){ cnt++; base = data[i].first; if(cnt==nI){ suc = false; break; } } } if(suc)r=m; else l=m; } Mat retImg(img.size(),CV_32SC1); int *retImgPtr = retImg.ptr<int>(); // In the sorted list, divide pixel values into clusters according to the minimum error bound // Quantize each value to the median of its cluster // Also record the mapping of quantized value and quantized index. float base = (float)minVal; int baseI = 0; int cnt = 0; for(int i=0;i<=alls;i++){ if(i==alls || data[i].first>base+r){ mapping[cnt] = data[(baseI+i-1)>>1].first; //median if(i==alls)break; cnt++; base = data[i].first; baseI = i; } retImgPtr[data[i].second] = cnt; } free(data); //end of the function outImg = retImg; } /***************************************************************/ /* Function: from32STo32F * Description: convert the quantization index image back to the floating-point image accroding to the mapping /***************************************************************/ static void from32STo32F(Mat &img, Mat &outImg, float *mapping){ Mat retImg(img.size(),CV_32F); int rows = img.rows, cols = img.cols, alls = rows*cols; float *retImgPtr = retImg.ptr<float>(); int *imgPtr = img.ptr<int>(); // convert 32S index to 32F real value #pragma omp parallel for for(int i=0;i<alls;i++){ retImgPtr[i] = mapping[imgPtr[i]]; } // end of the function outImg = retImg; } }; #endif
3d7pt_var.c
/* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 16; tile_size[3] = 128; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[t%2][i ][j ][k ] + coef[1][i][j][k] * A[t%2][i-1][j ][k ] + coef[2][i][j][k] * A[t%2][i ][j-1][k ] + coef[3][i][j][k] * A[t%2][i ][j ][k-1] + coef[4][i][j][k] * A[t%2][i+1][j ][k ] + coef[5][i][j][k] * A[t%2][i ][j+1][k ] + coef[6][i][j][k] * A[t%2][i ][j ][k+1]; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
Cone.h
#ifndef CONE_HEADER #define CONE_HEADER #ifdef DOPARALLEL #include <omp.h> #endif #include "basic.h" #include "PointCloud.h" #include <GfxTL/HyperplaneCoordinateSystem.h> #include <stdexcept> #include <ostream> #include <istream> #include <stdio.h> #if !defined(_WIN32) && !defined(WIN32) #include <unistd.h> #endif #include <MiscLib/NoShrinkVector.h> #include "LevMarLSWeight.h" #include "LevMarFitting.h" #ifndef DLL_LINKAGE #define DLL_LINKAGE #endif // This implements a one sided cone! class DLL_LINKAGE Cone { public: struct ConeInfo { Vec3f center; Vec3f axisDirection; float angle; Vec3f minPoint; Vec3f maxPoint; float height; float minHeight; float maxHeight; float minRadius; float maxRadius; }; struct ParallelPlanesError : public std::runtime_error { ParallelPlanesError() : std::runtime_error("Parallel planes in cone construction") {} }; enum { RequiredSamples = 3 }; Cone(); Cone(const Vec3f &center, const Vec3f &axisDir, float angle); Cone(const Vec3f &p1, const Vec3f &p2, const Vec3f &p3, const Vec3f &n1, const Vec3f &n2, const Vec3f &n3); bool Init(const MiscLib::Vector< Vec3f > &samples); bool InitAverage(const MiscLib::Vector< Vec3f > &samples); bool Init(const Vec3f &center, const Vec3f &axisDir, float angle); bool Init(const Vec3f &p1, const Vec3f &p2, const Vec3f &p3, const Vec3f &n1, const Vec3f &n2, const Vec3f &n3); bool Init(bool binary, std::istream *i); void Init(FILE *i); void Init(float* array); inline float Distance(const Vec3f &p) const; inline void Normal(const Vec3f &p, Vec3f *n) const; inline float DistanceAndNormal(const Vec3f &p, Vec3f *n) const; inline float SignedDistance(const Vec3f &p) const; inline float SignedDistanceAndNormal(const Vec3f &p, Vec3f *n) const; void Project(const Vec3f &p, Vec3f *pp) const; // Paramterizes into (length, angle) void Parameters(const Vec3f &p, std::pair< float, float > *param) const; inline float Height(const Vec3f &p) const; inline float Angle() const; inline const Vec3f &Center() const; inline const Vec3f &AxisDirection() const; Vec3f &AxisDirection() { return m_axisDir; } inline const Vec3f AngularDirection() const; //void AngularDirection(const Vec3f &angular); void RotateAngularDirection(float radians); inline float RadiusAtLength(float length) const; bool LeastSquaresFit(const PointCloud &pc, MiscLib::Vector< size_t >::const_iterator begin, MiscLib::Vector< size_t >::const_iterator end); template< class IteratorT > bool LeastSquaresFit(IteratorT begin, IteratorT end); bool Fit(const PointCloud &pc, MiscLib::Vector< size_t >::const_iterator begin, MiscLib::Vector< size_t >::const_iterator end) { return LeastSquaresFit(pc, begin, end); } static bool Interpolate(const MiscLib::Vector< Cone > &cones, const MiscLib::Vector< float > &weights, Cone *ic); void Serialize(bool binary, std::ostream *o) const; static size_t SerializedSize(); void Serialize(FILE *o) const; void Serialize(float* array) const; static size_t SerializedFloatSize(); void Transform(float scale, const Vec3f &translate); void Transform(const GfxTL::MatrixXX< 3, 3, float > &rot, const GfxTL::Vector3Df &trans); inline unsigned int Intersect(const Vec3f &p, const Vec3f &r, float lambda[2], Vec3f interPts[2]) const; ConeInfo GetInfo(const PointCloud& pc, size_t startingIndx, size_t endingIndx) const; ConeInfo GetInfo(const MiscLib::Vector< Vec3f >& samples) const; private: template< class WeightT > class LevMarCone : public WeightT { public: enum { NumParams = 7 }; typedef float ScalarType; template< class IteratorT > ScalarType Chi(const ScalarType *params, IteratorT begin, IteratorT end, ScalarType *values, ScalarType *temp) const { ScalarType chi = 0; ScalarType cosPhi = std::cos(params[6]); ScalarType sinPhi = std::sin(params[6]); size_t size = end - begin; #ifdef DOPARALLEL #pragma omp parallel for schedule(static) reduction(+:chi) #endif for(int idx = 0; idx < size; ++idx) { Vec3f s; for(unsigned int j = 0; j < 3; ++j) s[j] = begin[idx][j] - params[j]; ScalarType g = fabs(s[0] * params[3] + s[1] * params[4] + s[2] * params[5]); ScalarType f = s.sqrLength() - (g * g); if(f <= 0) f = 0; else f = std::sqrt(f); temp[idx] = f; chi += (values[idx] = WeightT::Weigh(cosPhi * f - sinPhi * g)) * values[idx]; } return chi; } template< class IteratorT > void Derivatives(const ScalarType *params, IteratorT begin, IteratorT end, const ScalarType *values, const ScalarType *temp, ScalarType *matrix) const { ScalarType sinPhi = -std::sin(params[6]); ScalarType cosPhi = std::cos(params[6]); size_t size = end - begin; #ifdef DOPARALLEL #pragma omp parallel for schedule(static) #endif for(int idx = 0; idx < size; ++idx) { Vec3f s; for(unsigned int j = 0; j < 3; ++j) s[j] = begin[idx][j] - params[j]; ScalarType g = fabs(s[0] * params[3] + s[1] * params[4] + s[2] * params[5]); ScalarType ggradient[6]; for(unsigned int j = 0; j < 3; ++j) ggradient[j] = -params[j + 3]; for(unsigned int j = 0; j < 3; ++j) ggradient[j + 3] = s[j] - params[j + 3] * g; ScalarType fgradient[6]; if(temp[idx] < 1.0e-6) { fgradient[0] = std::sqrt(1 - params[3] * params[3]); fgradient[1] = std::sqrt(1 - params[4] * params[4]); fgradient[2] = std::sqrt(1 - params[5] * params[5]); } else { fgradient[0] = (params[3] * g - s[0]) / temp[idx]; fgradient[1] = (params[4] * g - s[1]) / temp[idx]; fgradient[2] = (params[5] * g - s[2]) / temp[idx]; } fgradient[3] = g * fgradient[0]; fgradient[4] = g * fgradient[1]; fgradient[5] = g * fgradient[2]; for(unsigned int j = 0; j < 6; ++j) matrix[idx * NumParams + j] = cosPhi * fgradient[j] + sinPhi * ggradient[j]; matrix[idx * NumParams + 6] = temp[idx] * sinPhi - g * cosPhi; WeightT::template DerivWeigh< NumParams >(cosPhi * temp[idx] + sinPhi * g, matrix + idx * NumParams); } } void Normalize(float *params) const { // normalize direction ScalarType l = std::sqrt(params[3] * params[3] + params[4] * params[4] + params[5] * params[5]); for(unsigned int i = 3; i < 6; ++i) params[i] /= l; // normalize angle params[6] -= std::floor(params[6] / (2 * ScalarType(M_PI))) * (2 * ScalarType(M_PI)); // params[6] %= 2*M_PI if(params[6] > M_PI) { params[6] -= std::floor(params[6] / ScalarType(M_PI)) * ScalarType(M_PI); // params[6] %= M_PI for(unsigned int i = 3; i < 6; ++i) params[i] *= -1; } if(params[6] > ScalarType(M_PI) / 2) params[6] = ScalarType(M_PI) - params[6]; } }; private: Vec3f m_center; // this is the apex of the cone Vec3f m_axisDir; // the axis points into the interior of the cone float m_angle; // the opening angle Vec3f m_normal; Vec3f m_normalY; // precomputed normal part float m_n2d[2]; GfxTL::HyperplaneCoordinateSystem< float, 3 > m_hcs; float m_angularRotatedRadians; }; inline float Cone::Distance(const Vec3f &p) const { // this is for one sided cone! Vec3f s = p - m_center; float g = s.dot(m_axisDir); // distance to plane orhogonal to // axisdir through center // distance to axis float sqrS = s.sqrLength(); float f = sqrS - (g * g); if(f <= 0) f = 0; else f = std::sqrt(f); float da = m_n2d[0] * f; float db = m_n2d[1] * g; if(g < 0 && da - db < 0) // is inside other side of cone -> disallow return std::sqrt(sqrS); return fabs(da + db); } inline void Cone::Normal(const Vec3f &p, Vec3f *n) const { Vec3f s = p - m_center; Vec3f pln = s.cross(m_axisDir); Vec3f plx = m_axisDir.cross(pln); plx.normalize(); // we are not dealing with two-sided cone *n = m_normal[0] * plx + m_normalY; } inline float Cone::DistanceAndNormal(const Vec3f &p, Vec3f *n) const { // this is for one-sided cone !!! Vec3f s = p - m_center; float g = s.dot(m_axisDir); // distance to plane orhogonal to // axisdir through center // distance to axis float sqrS = s.sqrLength(); float f = sqrS - (g * g); if(f <= 0) f = 0; else f = std::sqrt(f); float da = m_n2d[0] * f; float db = m_n2d[1] * g; float dist; if(g < 0 && da - db < 0) // is inside other side of cone -> disallow dist = std::sqrt(sqrS); else dist = fabs(da + db); // need normal Vec3f plx = s - g * m_axisDir; plx.normalize(); *n = m_normal[0] * plx + m_normalY; return dist; } inline float Cone::SignedDistance(const Vec3f &p) const { // this is for one sided cone! Vec3f s = p - m_center; float g = s.dot(m_axisDir); // distance to plane orhogonal to // axisdir through center // distance to axis float sqrS = s.sqrLength(); float f = sqrS - (g * g); if(f <= 0) f = 0; else f = std::sqrt(f); float da = m_n2d[0] * f; float db = m_n2d[1] * g; if(g < 0 && da - db < 0) // is inside other side of cone -> disallow return std::sqrt(sqrS); return da + db; } inline float Cone::SignedDistanceAndNormal(const Vec3f &p, Vec3f *n) const { // this is for one-sided cone !!! Vec3f s = p - m_center; float g = s.dot(m_axisDir); // distance to plane orhogonal to // axisdir through center // distance to axis float sqrS = s.sqrLength(); float f = sqrS - (g * g); if(f <= 0) f = 0; else f = std::sqrt(f); float da = m_n2d[0] * f; float db = m_n2d[1] * g; float dist; if(g < 0 && da - db < 0) // is inside other side of cone -> disallow dist = std::sqrt(sqrS); else dist = da + db; // need normal Vec3f plx = s - g * m_axisDir; plx.normalize(); *n = m_normal[0] * plx + m_normalY; return dist; } float Cone::Angle() const { return m_angle; } const Vec3f &Cone::Center() const { return m_center; } const Vec3f &Cone::AxisDirection() const { return m_axisDir; } const Vec3f Cone::AngularDirection() const { return Vec3f(m_hcs[0].Data()); } float Cone::RadiusAtLength(float length) const { return std::sin(m_angle) * fabs(length); } float Cone::Height(const Vec3f &p) const { Vec3f s = p - m_center; return m_axisDir.dot(s); } template< class IteratorT > bool Cone::LeastSquaresFit(IteratorT begin, IteratorT end) { float param[7]; for(unsigned int i = 0; i < 3; ++i) param[i] = m_center[i]; for(unsigned int i = 0; i < 3; ++i) param[i + 3] = m_axisDir[i]; param[6] = m_angle; LevMarCone< LevMarLSWeight > levMarCone; if(!LevMar(begin, end, levMarCone, param)) return false; if(param[6] < 1.0e-6 || param[6] > float(M_PI) / 2 - 1.0e-6) return false; for(unsigned int i = 0; i < 3; ++i) m_center[i] = param[i]; for(unsigned int i = 0; i < 3; ++i) m_axisDir[i] = param[i + 3]; m_angle = param[6]; m_normal = Vec3f(std::cos(-m_angle), std::sin(-m_angle), 0); m_normalY = m_normal[1] * m_axisDir; m_n2d[0] = std::cos(m_angle); m_n2d[1] = -std::sin(m_angle); m_hcs.FromNormal(m_axisDir); m_angularRotatedRadians = 0; // it could be that the axis has flipped during fitting // we need to detect such a case // for this we run over all points and compute the sum // of their respective heights. If that sum is negative // the axis needs to be flipped. float heightSum = 0; intptr_t size = end - begin; //#ifndef _WIN64 // for some reason the Microsoft x64 compiler crashes at the next line #ifdef DOPARALLEL #pragma omp parallel for schedule(static) reduction(+:heightSum) #endif //#endif for(intptr_t i = 0; i < size; ++i) heightSum += Height(begin[i]); if(heightSum < 0) { m_axisDir *= -1; m_hcs.FromNormal(m_axisDir); } return true; } inline unsigned int Cone::Intersect(const Vec3f &p, const Vec3f &r, float lambda[2], Vec3f interPts[2]) const { // Set up the quadratic Q(t) = c2*t^2 + 2*c1*t + c0 that corresponds to // the cone. Let the vertex be V, the unit-length direction vector be A, // and the angle measured from the cone axis to the cone wall be Theta, // and define g = cos(Theta). A point X is on the cone wall whenever // Dot(A,(X-V)/|X-V|) = g. Square this equation and factor to obtain // (X-V)^T * (A*A^T - g^2*I) * (X-V) = 0 // where the superscript T denotes the transpose operator. This defines // a double-sided cone. The line is L(t) = P + t*D, where P is the line // origin and D is a unit-length direction vector. Substituting // X = L(t) into the cone equation above leads to Q(t) = 0. Since we // want only intersection points on the single-sided cone that lives in // the half-space pointed to by A, any point L(t) generated by a root of // Q(t) = 0 must be tested for Dot(A,L(t)-V) >= 0. using namespace std; float fAdD = m_axisDir.dot(r); float tmp = cos(m_angle); float fCosSqr = tmp*tmp; Vec3f kE = p - m_center; float fAdE = m_axisDir.dot(kE); float fDdE = r.dot(kE); float fEdE = kE.dot(kE); float fC2 = fAdD*fAdD - fCosSqr; float fC1 = fAdD*fAdE - fCosSqr*fDdE; float fC0 = fAdE*fAdE - fCosSqr*fEdE; float fdot; // Solve the quadratic. Keep only those X for which Dot(A,X-V) >= 0. unsigned int interCount = 0; if (fabs(fC2) >= 1e-7) { // c2 != 0 float fDiscr = fC1*fC1 - fC0*fC2; if (fDiscr < 0) { // Q(t) = 0 has no real-valued roots. The line does not // intersect the double-sided cone. return 0; } else if (fDiscr > 1e-7) { // Q(t) = 0 has two distinct real-valued roots. However, one or // both of them might intersect the portion of the double-sided // cone "behind" the vertex. We are interested only in those // intersections "in front" of the vertex. float fRoot = sqrt(fDiscr); float fInvC2 = 1.0f/fC2; interCount = 0; float fT = (-fC1 - fRoot)*fInvC2; if(fT > 0) // intersect only in positive direction of ray { interPts[interCount] = p + fT*r; kE = interPts[interCount] - m_center; fdot = kE.dot(m_axisDir); if (fdot > 0) { lambda[interCount] = fT; interCount++; } } fT = (-fC1 + fRoot)*fInvC2; if(fT > 0) { interPts[interCount] = p + fT*r; kE = interPts[interCount] - m_center; fdot = kE.dot(m_axisDir); if (fdot > 0) { lambda[interCount] = fT; interCount++; } } } else if(fC1 / fC2 < 0) { // one repeated real root (line is tangent to the cone) interPts[0] = p - (fC1/fC2)*r; lambda[0] = -(fC1 / fC2); kE = interPts[0] - m_center; if (kE.dot(m_axisDir) > 0) interCount = 1; else interCount = 0; } } else if (fabs(fC1) >= 1.0e-7f) { // c2 = 0, c1 != 0 (D is a direction vector on the cone boundary) lambda[0] = -(0.5f * fC0/fC1); if(lambda[0] < 0) return 0; interPts[0] = p + lambda[0] *r; kE = interPts[0] - m_center; fdot = kE.dot(m_axisDir); if (fdot > 0) interCount = 1; else interCount = 0; } else if (abs(fC0) >= 1e-7) { // c2 = c1 = 0, c0 != 0 interCount = 0; } else { // c2 = c1 = c0 = 0, cone contains ray V+t*D where V is cone vertex // and D is the line direction. interCount = 1; lambda[0] = (m_center - p).dot(r); interPts[0] = m_center; } return interCount; } #endif
GB_unaryop__ainv_uint16_int16.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__ainv_uint16_int16 // op(A') function: GB_tran__ainv_uint16_int16 // C type: uint16_t // A type: int16_t // cast: uint16_t cij = (uint16_t) aij // unaryop: cij = -aij #define GB_ATYPE \ int16_t #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CASTING(z, aij) \ uint16_t z = (uint16_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_UINT16 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_uint16_int16 ( uint16_t *Cx, // Cx and Ax may be aliased int16_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__ainv_uint16_int16 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_split_full_template.c
//------------------------------------------------------------------------------ // GB_split_full_template: split a full matrix into a full tile //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // This method is not used when the matrices are iso. { //-------------------------------------------------------------------------- // get C and the tile A //-------------------------------------------------------------------------- const GB_CTYPE *restrict Ax = (GB_CTYPE *) A->x ; GB_CTYPE *restrict Cx = (GB_CTYPE *) C->x ; ASSERT (!A->iso) ; int64_t pC ; #pragma omp parallel for num_threads(C_nthreads) schedule(static) for (pC = 0 ; pC < cnz ; pC++) { int64_t i = pC % cvlen ; int64_t j = pC / cvlen ; int64_t iA = aistart + i ; int64_t jA = avstart + j ; int64_t pA = iA + jA * avlen ; // Cx [pC] = Ax [pA] ; GB_COPY (pC, pA) ; } done = true ; } #undef GB_CTYPE
raw_wrapper.c
/* * Copyright (c) 2017, Marcel Heing-Becker, University of Hamburg * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <assert.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <dlfcn.h> #include "raw_wrapper.h" /* Replay settings. */ uint8_t isolation_mode = 0; int unit_rank = 0, comm_size = 0; /* Capture frame data. */ uint64_t receive_counter = 0; int current_rank = 0; uint8_t wrapper_enabled = 0; void *wrapper_backend_handle = NULL; /* Backend calls. */ void (*backend_capture_data) ( int rank , int call_number , const void* src_buf , int count_source_elements , MPI_Datatype type , int source , int tag ) = NULL; int (*backend_create_pending_request) ( int rank , RW_AsyncMarker *marker , int8_t *request_token_sha256 ) = NULL; void (*backend_finalize)() = NULL; void (*backend_init)(int *argc, char ***argv, int rank) = NULL; int (*backend_obtain_pending_request) ( int rank , int8_t *request_token_sha256 , RW_AsyncMarker *marker ) = NULL; void (*backend_replay_data) ( int rank , int call_number , void *dest_buf , MPI_Datatype type , int count_dest_elements , MPI_Status *result_status ) = NULL; /* ============= WRAPPER GENERATOR STUFF ============= */ #ifndef _EXTERN_C_ #ifdef __cplusplus #define _EXTERN_C_ extern "C" #else /* __cplusplus */ #define _EXTERN_C_ #endif /* __cplusplus */ #endif /* _EXTERN_C_ */ #ifdef MPICH_HAS_C2F _EXTERN_C_ void *MPIR_ToPointer(int); #endif // MPICH_HAS_C2F #ifdef PIC /* For shared libraries, declare these weak and figure out which one was linked based on which init wrapper was called. See mpi_init wrappers. */ #pragma weak pmpi_init #pragma weak PMPI_INIT #pragma weak pmpi_init_ #pragma weak pmpi_init__ #endif /* PIC */ /* MPI_IN_PLACE issue fix, taken from: https://github.com/PRUNERS/ReMPI/blob/a8e0567a37d879ab7887bc79bcff8c5a709603b0/src/rempi_pmpi.cpp */ #ifndef MPI_F_STATUS_SIZE #if defined(MPI_STATUS_SIZE) && MPI_STATUS_SIZE > 0 #define MPI_F_STATUS_SIZE MPI_STATUS_SIZE #else _EXTERN_C_ void get_mpi_f_status_size___(int*); inline int __get_mpi_f_status_size() { int size; get_mpi_f_status_size___(&size); return size; } #define MPI_F_STATUS_SIZE __get_mpi_f_status_size() #endif #endif _EXTERN_C_ void get_mpi_f_in_place___(int*); inline int __get_mpi_f_in_place() { int in_place = 0; get_mpi_f_in_place___(&in_place); return in_place; } #define MPI_F_IN_PLACE __get_mpi_f_in_place() _EXTERN_C_ void get_mpi_f_bottom___(int*); inline int __get_mpi_f_bottom() { int bottom; get_mpi_f_bottom___(&bottom); return bottom; } #define MPI_F_BOTTOM __get_mpi_f_bottom() #if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__PGI) || defined(_CRAYC) #if defined(__GNUC__) #define WEAK_POSTFIX __attribute__ ((weak)) #else #define WEAK_POSTFIX #define USE_WEAK_PRAGMA #endif /* OpenMPI */ _EXTERN_C_ MPI_Fint mpi_fortran_in_place WEAK_POSTFIX; _EXTERN_C_ MPI_Fint MPI_FORTRAN_IN_PLACE WEAK_POSTFIX; _EXTERN_C_ MPI_Fint mpi_fortran_in_place_ WEAK_POSTFIX; _EXTERN_C_ MPI_Fint MPI_FORTRAN_IN_PLACE_ WEAK_POSTFIX; _EXTERN_C_ MPI_Fint mpi_fortran_in_place__ WEAK_POSTFIX; _EXTERN_C_ MPI_Fint MPI_FORTRAN_IN_PLACE__ WEAK_POSTFIX; _EXTERN_C_ MPI_Fint mpi_fortran_bottom WEAK_POSTFIX; _EXTERN_C_ MPI_Fint MPI_FORTRAN_BOTTOM WEAK_POSTFIX; _EXTERN_C_ MPI_Fint mpi_fortran_bottom_ WEAK_POSTFIX; _EXTERN_C_ MPI_Fint MPI_FORTRAN_BOTTOM_ WEAK_POSTFIX; _EXTERN_C_ MPI_Fint mpi_fortran_bottom__ WEAK_POSTFIX; _EXTERN_C_ MPI_Fint MPI_FORTRAN_BOTTOM__ WEAK_POSTFIX; /* MPICH 2 */ _EXTERN_C_ MPI_Fint MPIFCMB3 WEAK_POSTFIX; _EXTERN_C_ MPI_Fint mpifcmb3 WEAK_POSTFIX; _EXTERN_C_ MPI_Fint MPIFCMB3_ WEAK_POSTFIX; _EXTERN_C_ MPI_Fint mpifcmb3_ WEAK_POSTFIX; _EXTERN_C_ MPI_Fint MPIFCMB3__ WEAK_POSTFIX; _EXTERN_C_ MPI_Fint mpifcmb3__ WEAK_POSTFIX; _EXTERN_C_ MPI_Fint MPIFCMB4 WEAK_POSTFIX; _EXTERN_C_ MPI_Fint mpifcmb4 WEAK_POSTFIX; _EXTERN_C_ MPI_Fint MPIFCMB4_ WEAK_POSTFIX; _EXTERN_C_ MPI_Fint mpifcmb4_ WEAK_POSTFIX; _EXTERN_C_ MPI_Fint MPIFCMB4__ WEAK_POSTFIX; _EXTERN_C_ MPI_Fint mpifcmb4__ WEAK_POSTFIX; /* Argonne Fortran MPI wrappers */ _EXTERN_C_ void *MPIR_F_MPI_BOTTOM WEAK_POSTFIX; _EXTERN_C_ void *MPIR_F_MPI_IN_PLACE WEAK_POSTFIX; _EXTERN_C_ void *MPI_F_MPI_BOTTOM WEAK_POSTFIX; _EXTERN_C_ void *MPI_F_MPI_IN_PLACE WEAK_POSTFIX; /* MPICH 2 requires no special handling - MPI_BOTTOM may (must!) be passed through as-is. */ #define IsBottom(x) ((x) == (void *) &mpi_fortran_bottom || (x) == (void *) &MPI_FORTRAN_BOTTOM || (x) == (void *) &mpi_fortran_bottom_ || (x) == (void *) &MPI_FORTRAN_BOTTOM_ || (x) == (void *) & mpi_fortran_bottom__ || (x) == (void *) &MPI_FORTRAN_BOTTOM__) #define IsInPlace(x) ((x) == (void *) &mpi_fortran_in_place || (x) == (void *) &MPI_FORTRAN_IN_PLACE || (x) == (void *) &mpi_fortran_in_place_ || (x) == (void *) &MPI_FORTRAN_IN_PLACE_ || (x) == (void *) &mpi_fortran_in_place__ || (x) == (void *) &MPI_FORTRAN_IN_PLACE__ || (x) == (void *) &MPIFCMB4 || (x) == (void *) &mpifcmb4 || (x) == (void *) &MPIFCMB4_ || (x) == (void *) &mpifcmb4_ || (x) == (void *) &MPIFCMB4__ || (x) == (void *) &mpifcmb4__ || (x) == MPIR_F_MPI_IN_PLACE || (x) == MPI_F_MPI_IN_PLACE) #ifdef USE_WEAK_PRAGMA #pragma weak mpi_fortran_in_place #pragma weak MPI_FORTRAN_IN_PLACE #pragma weak mpi_fortran_in_place_ #pragma weak MPI_FORTRAN_IN_PLACE_ #pragma weak mpi_fortran_in_place__ #pragma weak MPI_FORTRAN_IN_PLACE__ #pragma weak mpi_fortran_bottom #pragma weak MPI_FORTRAN_BOTTOM #pragma weak mpi_fortran_bottom_ #pragma weak MPI_FORTRAN_BOTTOM_ #pragma weak mpi_fortran_bottom__ #pragma weak MPI_FORTRAN_BOTTOM__ /* MPICH 2 */ #pragma weak MPIFCMB3 #pragma weak mpifcmb3 #pragma weak MPIFCMB3_ #pragma weak mpifcmb3_ #pragma weak MPIFCMB3__ #pragma weak mpifcmb3__ #pragma weak MPIFCMB4 #pragma weak mpifcmb4 #pragma weak MPIFCMB4_ #pragma weak mpifcmb4_ #pragma weak MPIFCMB4__ #pragma weak mpifcmb4__ /* Argonne Fortran MPI wrappers */ #pragma weak MPIR_F_MPI_BOTTOM #pragma weak MPIR_F_MPI_IN_PLACE #pragma weak MPI_F_MPI_BOTTOM #pragma weak MPI_F_MPI_IN_PLACE #endif #if defined(MPICH_NAME) && (MPICH_NAME == 1) /* MPICH has no MPI_IN_PLACE */ #define BufferF2C(x) (x) #else #define BufferF2C(x) (IsBottom(x) ? MPI_BOTTOM : (IsInPlace(x) ? MPI_IN_PLACE : (x))) #endif /* defined(MPICH_NAME) && (MPICH_NAME == 1) */ #else #define BufferF2C(x) (x) #endif /* defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__PGI) || defined(_CRAYC) */ _EXTERN_C_ void pmpi_init(MPI_Fint *ierr); _EXTERN_C_ void PMPI_INIT(MPI_Fint *ierr); _EXTERN_C_ void pmpi_init_(MPI_Fint *ierr); _EXTERN_C_ void pmpi_init__(MPI_Fint *ierr); /* Macros to enable and disable compiler warnings for deprecated functions. * These macros will be used to silent warnings about deprecated MPI functions, * as these should be wrapped, even if they are deprecated. * * Note: The macros support GCC and clang compilers only. For other compilers * just add similar macros for your compiler. */ #if (defined(__GNUC__) && !defined(__clang__)) && \ ((__GNUC__ == 4 && __GNUC_MINOR__ >= 6) || __GNUC__ > 4) #define WRAP_MPI_CALL_PREFIX \ _Pragma("GCC diagnostic push"); \ _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\""); #define WRAP_MPI_CALL_POSTFIX _Pragma("GCC diagnostic pop"); #elif defined(__clang__) #define WRAP_MPI_CALL_PREFIX \ _Pragma("clang diagnostic push"); \ _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\""); #define WRAP_MPI_CALL_POSTFIX _Pragma("clang diagnostic pop"); #else #define WRAP_MPI_CALL_PREFIX #define WRAP_MPI_CALL_POSTFIX #endif /* ================== C Wrappers for MPI_Abort ================== */ _EXTERN_C_ int PMPI_Abort(MPI_Comm comm, int errorcode); _EXTERN_C_ int MPI_Abort(MPI_Comm comm, int errorcode) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Abort(comm, errorcode); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Abort =============== */ static void MPI_Abort_fortran_wrapper(MPI_Fint *comm, MPI_Fint *errorcode, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Abort((MPI_Comm)(*comm), *errorcode); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Abort(MPI_Comm_f2c(*comm), *errorcode); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ABORT(MPI_Fint *comm, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_Abort_fortran_wrapper(comm, errorcode, ierr); } _EXTERN_C_ void mpi_abort(MPI_Fint *comm, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_Abort_fortran_wrapper(comm, errorcode, ierr); } _EXTERN_C_ void mpi_abort_(MPI_Fint *comm, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_Abort_fortran_wrapper(comm, errorcode, ierr); } _EXTERN_C_ void mpi_abort__(MPI_Fint *comm, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_Abort_fortran_wrapper(comm, errorcode, ierr); } /* ================= End Wrappers for MPI_Abort ================= */ /* ================== C Wrappers for MPI_Accumulate ================== */ _EXTERN_C_ int PMPI_Accumulate(const void *origin_addr, int origin_count, MPI_Datatype origin_datatype, int target_rank, MPI_Aint target_disp, int target_count, MPI_Datatype target_datatype, MPI_Op op, MPI_Win win); _EXTERN_C_ int MPI_Accumulate(const void *origin_addr, int origin_count, MPI_Datatype origin_datatype, int target_rank, MPI_Aint target_disp, int target_count, MPI_Datatype target_datatype, MPI_Op op, MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Accumulate(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, op, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Accumulate =============== */ static void MPI_Accumulate_fortran_wrapper(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Accumulate((const void*)origin_addr, *origin_count, (MPI_Datatype)(*origin_datatype), *target_rank, *target_disp, *target_count, (MPI_Datatype)(*target_datatype), (MPI_Op)(*op), (MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Accumulate((const void*)origin_addr, *origin_count, MPI_Type_f2c(*origin_datatype), *target_rank, *target_disp, *target_count, MPI_Type_f2c(*target_datatype), MPI_Op_f2c(*op), MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ACCUMULATE(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *ierr) { MPI_Accumulate_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, op, win, ierr); } _EXTERN_C_ void mpi_accumulate(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *ierr) { MPI_Accumulate_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, op, win, ierr); } _EXTERN_C_ void mpi_accumulate_(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *ierr) { MPI_Accumulate_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, op, win, ierr); } _EXTERN_C_ void mpi_accumulate__(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *ierr) { MPI_Accumulate_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, op, win, ierr); } /* ================= End Wrappers for MPI_Accumulate ================= */ /* ================== C Wrappers for MPI_Add_error_class ================== */ _EXTERN_C_ int PMPI_Add_error_class(int *errorclass); _EXTERN_C_ int MPI_Add_error_class(int *errorclass) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Add_error_class(errorclass); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Add_error_class =============== */ static void MPI_Add_error_class_fortran_wrapper(MPI_Fint *errorclass, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Add_error_class((int*)errorclass); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ADD_ERROR_CLASS(MPI_Fint *errorclass, MPI_Fint *ierr) { MPI_Add_error_class_fortran_wrapper(errorclass, ierr); } _EXTERN_C_ void mpi_add_error_class(MPI_Fint *errorclass, MPI_Fint *ierr) { MPI_Add_error_class_fortran_wrapper(errorclass, ierr); } _EXTERN_C_ void mpi_add_error_class_(MPI_Fint *errorclass, MPI_Fint *ierr) { MPI_Add_error_class_fortran_wrapper(errorclass, ierr); } _EXTERN_C_ void mpi_add_error_class__(MPI_Fint *errorclass, MPI_Fint *ierr) { MPI_Add_error_class_fortran_wrapper(errorclass, ierr); } /* ================= End Wrappers for MPI_Add_error_class ================= */ /* ================== C Wrappers for MPI_Add_error_code ================== */ _EXTERN_C_ int PMPI_Add_error_code(int errorclass, int *errorcode); _EXTERN_C_ int MPI_Add_error_code(int errorclass, int *errorcode) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Add_error_code(errorclass, errorcode); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Add_error_code =============== */ static void MPI_Add_error_code_fortran_wrapper(MPI_Fint *errorclass, MPI_Fint *errorcode, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Add_error_code(*errorclass, (int*)errorcode); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ADD_ERROR_CODE(MPI_Fint *errorclass, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_Add_error_code_fortran_wrapper(errorclass, errorcode, ierr); } _EXTERN_C_ void mpi_add_error_code(MPI_Fint *errorclass, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_Add_error_code_fortran_wrapper(errorclass, errorcode, ierr); } _EXTERN_C_ void mpi_add_error_code_(MPI_Fint *errorclass, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_Add_error_code_fortran_wrapper(errorclass, errorcode, ierr); } _EXTERN_C_ void mpi_add_error_code__(MPI_Fint *errorclass, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_Add_error_code_fortran_wrapper(errorclass, errorcode, ierr); } /* ================= End Wrappers for MPI_Add_error_code ================= */ /* ================== C Wrappers for MPI_Add_error_string ================== */ _EXTERN_C_ int PMPI_Add_error_string(int errorcode, const char *string); _EXTERN_C_ int MPI_Add_error_string(int errorcode, const char *string) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Add_error_string(errorcode, string); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Add_error_string =============== */ static void MPI_Add_error_string_fortran_wrapper(MPI_Fint *errorcode, MPI_Fint *string, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Add_error_string(*errorcode, (const char*)string); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ADD_ERROR_STRING(MPI_Fint *errorcode, MPI_Fint *string, MPI_Fint *ierr) { MPI_Add_error_string_fortran_wrapper(errorcode, string, ierr); } _EXTERN_C_ void mpi_add_error_string(MPI_Fint *errorcode, MPI_Fint *string, MPI_Fint *ierr) { MPI_Add_error_string_fortran_wrapper(errorcode, string, ierr); } _EXTERN_C_ void mpi_add_error_string_(MPI_Fint *errorcode, MPI_Fint *string, MPI_Fint *ierr) { MPI_Add_error_string_fortran_wrapper(errorcode, string, ierr); } _EXTERN_C_ void mpi_add_error_string__(MPI_Fint *errorcode, MPI_Fint *string, MPI_Fint *ierr) { MPI_Add_error_string_fortran_wrapper(errorcode, string, ierr); } /* ================= End Wrappers for MPI_Add_error_string ================= */ /* ================== C Wrappers for MPI_Address ================== */ _EXTERN_C_ int PMPI_Address(void *location, MPI_Aint *address); _EXTERN_C_ int MPI_Address(void *location, MPI_Aint *address) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Address(location, address); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Address =============== */ static void MPI_Address_fortran_wrapper(MPI_Fint *location, MPI_Aint *address, MPI_Fint *ierr) { int _wrap_py_return_val = 0; WRAP_MPI_CALL_PREFIX _wrap_py_return_val = MPI_Address((void*)location, (MPI_Aint*)address); WRAP_MPI_CALL_POSTFIX *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ADDRESS(MPI_Fint *location, MPI_Aint *address, MPI_Fint *ierr) { MPI_Address_fortran_wrapper(location, address, ierr); } _EXTERN_C_ void mpi_address(MPI_Fint *location, MPI_Aint *address, MPI_Fint *ierr) { MPI_Address_fortran_wrapper(location, address, ierr); } _EXTERN_C_ void mpi_address_(MPI_Fint *location, MPI_Aint *address, MPI_Fint *ierr) { MPI_Address_fortran_wrapper(location, address, ierr); } _EXTERN_C_ void mpi_address__(MPI_Fint *location, MPI_Aint *address, MPI_Fint *ierr) { MPI_Address_fortran_wrapper(location, address, ierr); } /* ================= End Wrappers for MPI_Address ================= */ /* ================== C Wrappers for MPI_Allgather ================== */ _EXTERN_C_ int PMPI_Allgather(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm); _EXTERN_C_ int MPI_Allgather(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Allgather(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Allgather =============== */ static void MPI_Allgather_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Allgather(BufferF2C((const void*)sendbuf), *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, *recvcount, (MPI_Datatype)(*recvtype), (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Allgather(BufferF2C((const void*)sendbuf), *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, *recvcount, MPI_Type_f2c(*recvtype), MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ALLGATHER(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Allgather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, ierr); } _EXTERN_C_ void mpi_allgather(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Allgather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, ierr); } _EXTERN_C_ void mpi_allgather_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Allgather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, ierr); } _EXTERN_C_ void mpi_allgather__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Allgather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, ierr); } /* ================= End Wrappers for MPI_Allgather ================= */ /* ================== C Wrappers for MPI_Allgatherv ================== */ _EXTERN_C_ int PMPI_Allgatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int displs[], MPI_Datatype recvtype, MPI_Comm comm); _EXTERN_C_ int MPI_Allgatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int displs[], MPI_Datatype recvtype, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Allgatherv(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Allgatherv =============== */ static void MPI_Allgatherv_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Allgatherv((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)displs, (MPI_Datatype)(*recvtype), (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Allgatherv((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)displs, MPI_Type_f2c(*recvtype), MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ALLGATHERV(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Allgatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, ierr); } _EXTERN_C_ void mpi_allgatherv(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Allgatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, ierr); } _EXTERN_C_ void mpi_allgatherv_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Allgatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, ierr); } _EXTERN_C_ void mpi_allgatherv__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Allgatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, ierr); } /* ================= End Wrappers for MPI_Allgatherv ================= */ /* ================== C Wrappers for MPI_Alloc_mem ================== */ _EXTERN_C_ int PMPI_Alloc_mem(MPI_Aint size, MPI_Info info, void *baseptr); _EXTERN_C_ int MPI_Alloc_mem(MPI_Aint size, MPI_Info info, void *baseptr) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Alloc_mem(size, info, baseptr); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Alloc_mem =============== */ static void MPI_Alloc_mem_fortran_wrapper(MPI_Aint *size, MPI_Fint *info, MPI_Fint *baseptr, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Alloc_mem(*size, (MPI_Info)(*info), (void*)baseptr); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Alloc_mem(*size, MPI_Info_f2c(*info), (void*)baseptr); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ALLOC_MEM(MPI_Aint *size, MPI_Fint *info, MPI_Fint *baseptr, MPI_Fint *ierr) { MPI_Alloc_mem_fortran_wrapper(size, info, baseptr, ierr); } _EXTERN_C_ void mpi_alloc_mem(MPI_Aint *size, MPI_Fint *info, MPI_Fint *baseptr, MPI_Fint *ierr) { MPI_Alloc_mem_fortran_wrapper(size, info, baseptr, ierr); } _EXTERN_C_ void mpi_alloc_mem_(MPI_Aint *size, MPI_Fint *info, MPI_Fint *baseptr, MPI_Fint *ierr) { MPI_Alloc_mem_fortran_wrapper(size, info, baseptr, ierr); } _EXTERN_C_ void mpi_alloc_mem__(MPI_Aint *size, MPI_Fint *info, MPI_Fint *baseptr, MPI_Fint *ierr) { MPI_Alloc_mem_fortran_wrapper(size, info, baseptr, ierr); } /* ================= End Wrappers for MPI_Alloc_mem ================= */ /* ================== C Wrappers for MPI_Allreduce ================== */ _EXTERN_C_ int PMPI_Allreduce(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm); _EXTERN_C_ int MPI_Allreduce(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX uint64_t local_call_counter = 0; if (!wrapper_enabled) { _wrap_py_return_val = PMPI_Allreduce(sendbuf, recvbuf, count, datatype, op, comm); goto end; } #pragma omp atomic capture local_call_counter = ++receive_counter; if (isolation_mode) { MPI_Status dummy_status; backend_replay_data(current_rank, local_call_counter - 1, recvbuf, datatype, count, &dummy_status); _wrap_py_return_val = MPI_SUCCESS; } else { _wrap_py_return_val = PMPI_Allreduce(sendbuf, recvbuf, count, datatype, op, comm); if (MPI_SUCCESS == _wrap_py_return_val) { backend_capture_data(current_rank, local_call_counter - 1, recvbuf, count, datatype, 0, 0); } } WRAP_MPI_CALL_POSTFIX } end: return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Allreduce =============== */ static void MPI_Allreduce_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Allreduce(BufferF2C((const void*)sendbuf), (void*)recvbuf, *count, (MPI_Datatype)(*datatype), (MPI_Op)(*op), (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Allreduce(BufferF2C((const void*)sendbuf), (void*)recvbuf, *count, MPI_Type_f2c(*datatype), MPI_Op_f2c(*op), MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ALLREDUCE(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Allreduce_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, ierr); } _EXTERN_C_ void mpi_allreduce(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Allreduce_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, ierr); } _EXTERN_C_ void mpi_allreduce_(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Allreduce_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, ierr); } _EXTERN_C_ void mpi_allreduce__(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Allreduce_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, ierr); } /* ================= End Wrappers for MPI_Allreduce ================= */ /* ================== C Wrappers for MPI_Alltoall ================== */ _EXTERN_C_ int PMPI_Alltoall(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm); _EXTERN_C_ int MPI_Alltoall(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Alltoall(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Alltoall =============== */ static void MPI_Alltoall_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Alltoall((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, *recvcount, (MPI_Datatype)(*recvtype), (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Alltoall((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, *recvcount, MPI_Type_f2c(*recvtype), MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ALLTOALL(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Alltoall_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, ierr); } _EXTERN_C_ void mpi_alltoall(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Alltoall_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, ierr); } _EXTERN_C_ void mpi_alltoall_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Alltoall_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, ierr); } _EXTERN_C_ void mpi_alltoall__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Alltoall_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, ierr); } /* ================= End Wrappers for MPI_Alltoall ================= */ /* ================== C Wrappers for MPI_Alltoallv ================== */ _EXTERN_C_ int PMPI_Alltoallv(const void *sendbuf, const int sendcounts[], const int sdispls[], MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int rdispls[], MPI_Datatype recvtype, MPI_Comm comm); _EXTERN_C_ int MPI_Alltoallv(const void *sendbuf, const int sendcounts[], const int sdispls[], MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int rdispls[], MPI_Datatype recvtype, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Alltoallv(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Alltoallv =============== */ static void MPI_Alltoallv_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Alltoallv((const void*)sendbuf, (const int*)sendcounts, (const int*)sdispls, (MPI_Datatype)(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)rdispls, (MPI_Datatype)(*recvtype), (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Alltoallv((const void*)sendbuf, (const int*)sendcounts, (const int*)sdispls, MPI_Type_f2c(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)rdispls, MPI_Type_f2c(*recvtype), MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ALLTOALLV(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Alltoallv_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, ierr); } _EXTERN_C_ void mpi_alltoallv(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Alltoallv_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, ierr); } _EXTERN_C_ void mpi_alltoallv_(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Alltoallv_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, ierr); } _EXTERN_C_ void mpi_alltoallv__(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Alltoallv_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, ierr); } /* ================= End Wrappers for MPI_Alltoallv ================= */ /* ================== C Wrappers for MPI_Alltoallw ================== */ _EXTERN_C_ int PMPI_Alltoallw(const void *sendbuf, const int sendcounts[], const int sdispls[], const MPI_Datatype sendtypes[], void *recvbuf, const int recvcounts[], const int rdispls[], const MPI_Datatype recvtypes[], MPI_Comm comm); _EXTERN_C_ int MPI_Alltoallw(const void *sendbuf, const int sendcounts[], const int sdispls[], const MPI_Datatype sendtypes[], void *recvbuf, const int recvcounts[], const int rdispls[], const MPI_Datatype recvtypes[], MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Alltoallw(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Alltoallw =============== */ static void MPI_Alltoallw_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Alltoallw((const void*)sendbuf, (const int*)sendcounts, (const int*)sdispls, (const MPI_Datatype*)sendtypes, (void*)recvbuf, (const int*)recvcounts, (const int*)rdispls, (const MPI_Datatype*)recvtypes, (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Alltoallw((const void*)sendbuf, (const int*)sendcounts, (const int*)sdispls, (const MPI_Datatype*)sendtypes, (void*)recvbuf, (const int*)recvcounts, (const int*)rdispls, (const MPI_Datatype*)recvtypes, MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ALLTOALLW(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *ierr) { MPI_Alltoallw_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, ierr); } _EXTERN_C_ void mpi_alltoallw(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *ierr) { MPI_Alltoallw_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, ierr); } _EXTERN_C_ void mpi_alltoallw_(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *ierr) { MPI_Alltoallw_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, ierr); } _EXTERN_C_ void mpi_alltoallw__(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *ierr) { MPI_Alltoallw_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, ierr); } /* ================= End Wrappers for MPI_Alltoallw ================= */ /* ================== C Wrappers for MPI_Attr_delete ================== */ _EXTERN_C_ int PMPI_Attr_delete(MPI_Comm comm, int keyval); _EXTERN_C_ int MPI_Attr_delete(MPI_Comm comm, int keyval) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Attr_delete(comm, keyval); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Attr_delete =============== */ static void MPI_Attr_delete_fortran_wrapper(MPI_Fint *comm, MPI_Fint *keyval, MPI_Fint *ierr) { int _wrap_py_return_val = 0; WRAP_MPI_CALL_PREFIX #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Attr_delete((MPI_Comm)(*comm), *keyval); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Attr_delete(MPI_Comm_f2c(*comm), *keyval); #endif /* MPICH test */ WRAP_MPI_CALL_POSTFIX *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ATTR_DELETE(MPI_Fint *comm, MPI_Fint *keyval, MPI_Fint *ierr) { MPI_Attr_delete_fortran_wrapper(comm, keyval, ierr); } _EXTERN_C_ void mpi_attr_delete(MPI_Fint *comm, MPI_Fint *keyval, MPI_Fint *ierr) { MPI_Attr_delete_fortran_wrapper(comm, keyval, ierr); } _EXTERN_C_ void mpi_attr_delete_(MPI_Fint *comm, MPI_Fint *keyval, MPI_Fint *ierr) { MPI_Attr_delete_fortran_wrapper(comm, keyval, ierr); } _EXTERN_C_ void mpi_attr_delete__(MPI_Fint *comm, MPI_Fint *keyval, MPI_Fint *ierr) { MPI_Attr_delete_fortran_wrapper(comm, keyval, ierr); } /* ================= End Wrappers for MPI_Attr_delete ================= */ /* ================== C Wrappers for MPI_Attr_get ================== */ _EXTERN_C_ int PMPI_Attr_get(MPI_Comm comm, int keyval, void *attribute_val, int *flag); _EXTERN_C_ int MPI_Attr_get(MPI_Comm comm, int keyval, void *attribute_val, int *flag) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Attr_get(comm, keyval, attribute_val, flag); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Attr_get =============== */ static void MPI_Attr_get_fortran_wrapper(MPI_Fint *comm, MPI_Fint *keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { int _wrap_py_return_val = 0; WRAP_MPI_CALL_PREFIX #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Attr_get((MPI_Comm)(*comm), *keyval, (void*)attribute_val, (int*)flag); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Attr_get(MPI_Comm_f2c(*comm), *keyval, (void*)attribute_val, (int*)flag); #endif /* MPICH test */ WRAP_MPI_CALL_POSTFIX *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ATTR_GET(MPI_Fint *comm, MPI_Fint *keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Attr_get_fortran_wrapper(comm, keyval, attribute_val, flag, ierr); } _EXTERN_C_ void mpi_attr_get(MPI_Fint *comm, MPI_Fint *keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Attr_get_fortran_wrapper(comm, keyval, attribute_val, flag, ierr); } _EXTERN_C_ void mpi_attr_get_(MPI_Fint *comm, MPI_Fint *keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Attr_get_fortran_wrapper(comm, keyval, attribute_val, flag, ierr); } _EXTERN_C_ void mpi_attr_get__(MPI_Fint *comm, MPI_Fint *keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Attr_get_fortran_wrapper(comm, keyval, attribute_val, flag, ierr); } /* ================= End Wrappers for MPI_Attr_get ================= */ /* ================== C Wrappers for MPI_Attr_put ================== */ _EXTERN_C_ int PMPI_Attr_put(MPI_Comm comm, int keyval, void *attribute_val); _EXTERN_C_ int MPI_Attr_put(MPI_Comm comm, int keyval, void *attribute_val) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Attr_put(comm, keyval, attribute_val); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Attr_put =============== */ static void MPI_Attr_put_fortran_wrapper(MPI_Fint *comm, MPI_Fint *keyval, MPI_Fint *attribute_val, MPI_Fint *ierr) { int _wrap_py_return_val = 0; WRAP_MPI_CALL_PREFIX #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Attr_put((MPI_Comm)(*comm), *keyval, (void*)attribute_val); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Attr_put(MPI_Comm_f2c(*comm), *keyval, (void*)attribute_val); #endif /* MPICH test */ WRAP_MPI_CALL_POSTFIX *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ATTR_PUT(MPI_Fint *comm, MPI_Fint *keyval, MPI_Fint *attribute_val, MPI_Fint *ierr) { MPI_Attr_put_fortran_wrapper(comm, keyval, attribute_val, ierr); } _EXTERN_C_ void mpi_attr_put(MPI_Fint *comm, MPI_Fint *keyval, MPI_Fint *attribute_val, MPI_Fint *ierr) { MPI_Attr_put_fortran_wrapper(comm, keyval, attribute_val, ierr); } _EXTERN_C_ void mpi_attr_put_(MPI_Fint *comm, MPI_Fint *keyval, MPI_Fint *attribute_val, MPI_Fint *ierr) { MPI_Attr_put_fortran_wrapper(comm, keyval, attribute_val, ierr); } _EXTERN_C_ void mpi_attr_put__(MPI_Fint *comm, MPI_Fint *keyval, MPI_Fint *attribute_val, MPI_Fint *ierr) { MPI_Attr_put_fortran_wrapper(comm, keyval, attribute_val, ierr); } /* ================= End Wrappers for MPI_Attr_put ================= */ /* ================== C Wrappers for MPI_Barrier ================== */ _EXTERN_C_ int PMPI_Barrier(MPI_Comm comm); _EXTERN_C_ int MPI_Barrier(MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Barrier(comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Barrier =============== */ static void MPI_Barrier_fortran_wrapper(MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Barrier((MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Barrier(MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_BARRIER(MPI_Fint *comm, MPI_Fint *ierr) { MPI_Barrier_fortran_wrapper(comm, ierr); } _EXTERN_C_ void mpi_barrier(MPI_Fint *comm, MPI_Fint *ierr) { MPI_Barrier_fortran_wrapper(comm, ierr); } _EXTERN_C_ void mpi_barrier_(MPI_Fint *comm, MPI_Fint *ierr) { MPI_Barrier_fortran_wrapper(comm, ierr); } _EXTERN_C_ void mpi_barrier__(MPI_Fint *comm, MPI_Fint *ierr) { MPI_Barrier_fortran_wrapper(comm, ierr); } /* ================= End Wrappers for MPI_Barrier ================= */ /* ================== C Wrappers for MPI_Bcast ================== */ _EXTERN_C_ int PMPI_Bcast(void *buffer, int count, MPI_Datatype datatype, int root, MPI_Comm comm); _EXTERN_C_ int MPI_Bcast(void *buffer, int count, MPI_Datatype datatype, int root, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Bcast(buffer, count, datatype, root, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Bcast =============== */ static void MPI_Bcast_fortran_wrapper(MPI_Fint *buffer, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Bcast((void*)buffer, *count, (MPI_Datatype)(*datatype), *root, (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Bcast((void*)buffer, *count, MPI_Type_f2c(*datatype), *root, MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_BCAST(MPI_Fint *buffer, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Bcast_fortran_wrapper(buffer, count, datatype, root, comm, ierr); } _EXTERN_C_ void mpi_bcast(MPI_Fint *buffer, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Bcast_fortran_wrapper(buffer, count, datatype, root, comm, ierr); } _EXTERN_C_ void mpi_bcast_(MPI_Fint *buffer, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Bcast_fortran_wrapper(buffer, count, datatype, root, comm, ierr); } _EXTERN_C_ void mpi_bcast__(MPI_Fint *buffer, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Bcast_fortran_wrapper(buffer, count, datatype, root, comm, ierr); } /* ================= End Wrappers for MPI_Bcast ================= */ /* ================== C Wrappers for MPI_Bsend ================== */ _EXTERN_C_ int PMPI_Bsend(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm); _EXTERN_C_ int MPI_Bsend(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Bsend(buf, count, datatype, dest, tag, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Bsend =============== */ static void MPI_Bsend_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Bsend((const void*)buf, *count, (MPI_Datatype)(*datatype), *dest, *tag, (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Bsend((const void*)buf, *count, MPI_Type_f2c(*datatype), *dest, *tag, MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_BSEND(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Bsend_fortran_wrapper(buf, count, datatype, dest, tag, comm, ierr); } _EXTERN_C_ void mpi_bsend(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Bsend_fortran_wrapper(buf, count, datatype, dest, tag, comm, ierr); } _EXTERN_C_ void mpi_bsend_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Bsend_fortran_wrapper(buf, count, datatype, dest, tag, comm, ierr); } _EXTERN_C_ void mpi_bsend__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Bsend_fortran_wrapper(buf, count, datatype, dest, tag, comm, ierr); } /* ================= End Wrappers for MPI_Bsend ================= */ /* ================== C Wrappers for MPI_Bsend_init ================== */ _EXTERN_C_ int PMPI_Bsend_init(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Bsend_init(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Bsend_init(buf, count, datatype, dest, tag, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Bsend_init =============== */ static void MPI_Bsend_init_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Bsend_init((const void*)buf, *count, (MPI_Datatype)(*datatype), *dest, *tag, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Bsend_init((const void*)buf, *count, MPI_Type_f2c(*datatype), *dest, *tag, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_BSEND_INIT(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Bsend_init_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_bsend_init(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Bsend_init_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_bsend_init_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Bsend_init_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_bsend_init__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Bsend_init_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } /* ================= End Wrappers for MPI_Bsend_init ================= */ /* ================== C Wrappers for MPI_Buffer_attach ================== */ _EXTERN_C_ int PMPI_Buffer_attach(void *buffer, int size); _EXTERN_C_ int MPI_Buffer_attach(void *buffer, int size) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Buffer_attach(buffer, size); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Buffer_attach =============== */ static void MPI_Buffer_attach_fortran_wrapper(MPI_Fint *buffer, MPI_Fint *size, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Buffer_attach((void*)buffer, *size); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_BUFFER_ATTACH(MPI_Fint *buffer, MPI_Fint *size, MPI_Fint *ierr) { MPI_Buffer_attach_fortran_wrapper(buffer, size, ierr); } _EXTERN_C_ void mpi_buffer_attach(MPI_Fint *buffer, MPI_Fint *size, MPI_Fint *ierr) { MPI_Buffer_attach_fortran_wrapper(buffer, size, ierr); } _EXTERN_C_ void mpi_buffer_attach_(MPI_Fint *buffer, MPI_Fint *size, MPI_Fint *ierr) { MPI_Buffer_attach_fortran_wrapper(buffer, size, ierr); } _EXTERN_C_ void mpi_buffer_attach__(MPI_Fint *buffer, MPI_Fint *size, MPI_Fint *ierr) { MPI_Buffer_attach_fortran_wrapper(buffer, size, ierr); } /* ================= End Wrappers for MPI_Buffer_attach ================= */ /* ================== C Wrappers for MPI_Buffer_detach ================== */ _EXTERN_C_ int PMPI_Buffer_detach(void *buffer, int *size); _EXTERN_C_ int MPI_Buffer_detach(void *buffer, int *size) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Buffer_detach(buffer, size); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Buffer_detach =============== */ static void MPI_Buffer_detach_fortran_wrapper(MPI_Fint *buffer, MPI_Fint *size, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Buffer_detach((void*)buffer, (int*)size); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_BUFFER_DETACH(MPI_Fint *buffer, MPI_Fint *size, MPI_Fint *ierr) { MPI_Buffer_detach_fortran_wrapper(buffer, size, ierr); } _EXTERN_C_ void mpi_buffer_detach(MPI_Fint *buffer, MPI_Fint *size, MPI_Fint *ierr) { MPI_Buffer_detach_fortran_wrapper(buffer, size, ierr); } _EXTERN_C_ void mpi_buffer_detach_(MPI_Fint *buffer, MPI_Fint *size, MPI_Fint *ierr) { MPI_Buffer_detach_fortran_wrapper(buffer, size, ierr); } _EXTERN_C_ void mpi_buffer_detach__(MPI_Fint *buffer, MPI_Fint *size, MPI_Fint *ierr) { MPI_Buffer_detach_fortran_wrapper(buffer, size, ierr); } /* ================= End Wrappers for MPI_Buffer_detach ================= */ /* ================== C Wrappers for MPI_Cancel ================== */ _EXTERN_C_ int PMPI_Cancel(MPI_Request *request); _EXTERN_C_ int MPI_Cancel(MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Cancel(request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Cancel =============== */ static void MPI_Cancel_fortran_wrapper(MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Cancel((MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Cancel(&temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_CANCEL(MPI_Fint *request, MPI_Fint *ierr) { MPI_Cancel_fortran_wrapper(request, ierr); } _EXTERN_C_ void mpi_cancel(MPI_Fint *request, MPI_Fint *ierr) { MPI_Cancel_fortran_wrapper(request, ierr); } _EXTERN_C_ void mpi_cancel_(MPI_Fint *request, MPI_Fint *ierr) { MPI_Cancel_fortran_wrapper(request, ierr); } _EXTERN_C_ void mpi_cancel__(MPI_Fint *request, MPI_Fint *ierr) { MPI_Cancel_fortran_wrapper(request, ierr); } /* ================= End Wrappers for MPI_Cancel ================= */ /* ================== C Wrappers for MPI_Cart_coords ================== */ _EXTERN_C_ int PMPI_Cart_coords(MPI_Comm comm, int rank, int maxdims, int coords[]); _EXTERN_C_ int MPI_Cart_coords(MPI_Comm comm, int rank, int maxdims, int coords[]) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Cart_coords(comm, rank, maxdims, coords); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Cart_coords =============== */ static void MPI_Cart_coords_fortran_wrapper(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *maxdims, MPI_Fint coords[], MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Cart_coords((MPI_Comm)(*comm), *rank, *maxdims, (int*)coords); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Cart_coords(MPI_Comm_f2c(*comm), *rank, *maxdims, (int*)coords); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_CART_COORDS(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *maxdims, MPI_Fint coords[], MPI_Fint *ierr) { MPI_Cart_coords_fortran_wrapper(comm, rank, maxdims, coords, ierr); } _EXTERN_C_ void mpi_cart_coords(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *maxdims, MPI_Fint coords[], MPI_Fint *ierr) { MPI_Cart_coords_fortran_wrapper(comm, rank, maxdims, coords, ierr); } _EXTERN_C_ void mpi_cart_coords_(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *maxdims, MPI_Fint coords[], MPI_Fint *ierr) { MPI_Cart_coords_fortran_wrapper(comm, rank, maxdims, coords, ierr); } _EXTERN_C_ void mpi_cart_coords__(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *maxdims, MPI_Fint coords[], MPI_Fint *ierr) { MPI_Cart_coords_fortran_wrapper(comm, rank, maxdims, coords, ierr); } /* ================= End Wrappers for MPI_Cart_coords ================= */ /* ================== C Wrappers for MPI_Cart_create ================== */ _EXTERN_C_ int PMPI_Cart_create(MPI_Comm old_comm, int ndims, const int dims[], const int periods[], int reorder, MPI_Comm *comm_cart); _EXTERN_C_ int MPI_Cart_create(MPI_Comm old_comm, int ndims, const int dims[], const int periods[], int reorder, MPI_Comm *comm_cart) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Cart_create(old_comm, ndims, dims, periods, reorder, comm_cart); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Cart_create =============== */ static void MPI_Cart_create_fortran_wrapper(MPI_Fint *old_comm, MPI_Fint *ndims, MPI_Fint dims[], MPI_Fint periods[], MPI_Fint *reorder, MPI_Fint *comm_cart, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Cart_create((MPI_Comm)(*old_comm), *ndims, (const int*)dims, (const int*)periods, *reorder, (MPI_Comm*)comm_cart); #else /* MPI-2 safe call */ MPI_Comm temp_comm_cart; temp_comm_cart = MPI_Comm_f2c(*comm_cart); _wrap_py_return_val = MPI_Cart_create(MPI_Comm_f2c(*old_comm), *ndims, (const int*)dims, (const int*)periods, *reorder, &temp_comm_cart); *comm_cart = MPI_Comm_c2f(temp_comm_cart); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_CART_CREATE(MPI_Fint *old_comm, MPI_Fint *ndims, MPI_Fint dims[], MPI_Fint periods[], MPI_Fint *reorder, MPI_Fint *comm_cart, MPI_Fint *ierr) { MPI_Cart_create_fortran_wrapper(old_comm, ndims, dims, periods, reorder, comm_cart, ierr); } _EXTERN_C_ void mpi_cart_create(MPI_Fint *old_comm, MPI_Fint *ndims, MPI_Fint dims[], MPI_Fint periods[], MPI_Fint *reorder, MPI_Fint *comm_cart, MPI_Fint *ierr) { MPI_Cart_create_fortran_wrapper(old_comm, ndims, dims, periods, reorder, comm_cart, ierr); } _EXTERN_C_ void mpi_cart_create_(MPI_Fint *old_comm, MPI_Fint *ndims, MPI_Fint dims[], MPI_Fint periods[], MPI_Fint *reorder, MPI_Fint *comm_cart, MPI_Fint *ierr) { MPI_Cart_create_fortran_wrapper(old_comm, ndims, dims, periods, reorder, comm_cart, ierr); } _EXTERN_C_ void mpi_cart_create__(MPI_Fint *old_comm, MPI_Fint *ndims, MPI_Fint dims[], MPI_Fint periods[], MPI_Fint *reorder, MPI_Fint *comm_cart, MPI_Fint *ierr) { MPI_Cart_create_fortran_wrapper(old_comm, ndims, dims, periods, reorder, comm_cart, ierr); } /* ================= End Wrappers for MPI_Cart_create ================= */ /* ================== C Wrappers for MPI_Cart_get ================== */ _EXTERN_C_ int PMPI_Cart_get(MPI_Comm comm, int maxdims, int dims[], int periods[], int coords[]); _EXTERN_C_ int MPI_Cart_get(MPI_Comm comm, int maxdims, int dims[], int periods[], int coords[]) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Cart_get(comm, maxdims, dims, periods, coords); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Cart_get =============== */ static void MPI_Cart_get_fortran_wrapper(MPI_Fint *comm, MPI_Fint *maxdims, MPI_Fint dims[], MPI_Fint periods[], MPI_Fint coords[], MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Cart_get((MPI_Comm)(*comm), *maxdims, (int*)dims, (int*)periods, (int*)coords); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Cart_get(MPI_Comm_f2c(*comm), *maxdims, (int*)dims, (int*)periods, (int*)coords); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_CART_GET(MPI_Fint *comm, MPI_Fint *maxdims, MPI_Fint dims[], MPI_Fint periods[], MPI_Fint coords[], MPI_Fint *ierr) { MPI_Cart_get_fortran_wrapper(comm, maxdims, dims, periods, coords, ierr); } _EXTERN_C_ void mpi_cart_get(MPI_Fint *comm, MPI_Fint *maxdims, MPI_Fint dims[], MPI_Fint periods[], MPI_Fint coords[], MPI_Fint *ierr) { MPI_Cart_get_fortran_wrapper(comm, maxdims, dims, periods, coords, ierr); } _EXTERN_C_ void mpi_cart_get_(MPI_Fint *comm, MPI_Fint *maxdims, MPI_Fint dims[], MPI_Fint periods[], MPI_Fint coords[], MPI_Fint *ierr) { MPI_Cart_get_fortran_wrapper(comm, maxdims, dims, periods, coords, ierr); } _EXTERN_C_ void mpi_cart_get__(MPI_Fint *comm, MPI_Fint *maxdims, MPI_Fint dims[], MPI_Fint periods[], MPI_Fint coords[], MPI_Fint *ierr) { MPI_Cart_get_fortran_wrapper(comm, maxdims, dims, periods, coords, ierr); } /* ================= End Wrappers for MPI_Cart_get ================= */ /* ================== C Wrappers for MPI_Cart_map ================== */ _EXTERN_C_ int PMPI_Cart_map(MPI_Comm comm, int ndims, const int dims[], const int periods[], int *newrank); _EXTERN_C_ int MPI_Cart_map(MPI_Comm comm, int ndims, const int dims[], const int periods[], int *newrank) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Cart_map(comm, ndims, dims, periods, newrank); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Cart_map =============== */ static void MPI_Cart_map_fortran_wrapper(MPI_Fint *comm, MPI_Fint *ndims, MPI_Fint dims[], MPI_Fint periods[], MPI_Fint *newrank, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Cart_map((MPI_Comm)(*comm), *ndims, (const int*)dims, (const int*)periods, (int*)newrank); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Cart_map(MPI_Comm_f2c(*comm), *ndims, (const int*)dims, (const int*)periods, (int*)newrank); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_CART_MAP(MPI_Fint *comm, MPI_Fint *ndims, MPI_Fint dims[], MPI_Fint periods[], MPI_Fint *newrank, MPI_Fint *ierr) { MPI_Cart_map_fortran_wrapper(comm, ndims, dims, periods, newrank, ierr); } _EXTERN_C_ void mpi_cart_map(MPI_Fint *comm, MPI_Fint *ndims, MPI_Fint dims[], MPI_Fint periods[], MPI_Fint *newrank, MPI_Fint *ierr) { MPI_Cart_map_fortran_wrapper(comm, ndims, dims, periods, newrank, ierr); } _EXTERN_C_ void mpi_cart_map_(MPI_Fint *comm, MPI_Fint *ndims, MPI_Fint dims[], MPI_Fint periods[], MPI_Fint *newrank, MPI_Fint *ierr) { MPI_Cart_map_fortran_wrapper(comm, ndims, dims, periods, newrank, ierr); } _EXTERN_C_ void mpi_cart_map__(MPI_Fint *comm, MPI_Fint *ndims, MPI_Fint dims[], MPI_Fint periods[], MPI_Fint *newrank, MPI_Fint *ierr) { MPI_Cart_map_fortran_wrapper(comm, ndims, dims, periods, newrank, ierr); } /* ================= End Wrappers for MPI_Cart_map ================= */ /* ================== C Wrappers for MPI_Cart_rank ================== */ _EXTERN_C_ int PMPI_Cart_rank(MPI_Comm comm, const int coords[], int *rank); _EXTERN_C_ int MPI_Cart_rank(MPI_Comm comm, const int coords[], int *rank) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Cart_rank(comm, coords, rank); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Cart_rank =============== */ static void MPI_Cart_rank_fortran_wrapper(MPI_Fint *comm, MPI_Fint coords[], MPI_Fint *rank, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Cart_rank((MPI_Comm)(*comm), (const int*)coords, (int*)rank); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Cart_rank(MPI_Comm_f2c(*comm), (const int*)coords, (int*)rank); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_CART_RANK(MPI_Fint *comm, MPI_Fint coords[], MPI_Fint *rank, MPI_Fint *ierr) { MPI_Cart_rank_fortran_wrapper(comm, coords, rank, ierr); } _EXTERN_C_ void mpi_cart_rank(MPI_Fint *comm, MPI_Fint coords[], MPI_Fint *rank, MPI_Fint *ierr) { MPI_Cart_rank_fortran_wrapper(comm, coords, rank, ierr); } _EXTERN_C_ void mpi_cart_rank_(MPI_Fint *comm, MPI_Fint coords[], MPI_Fint *rank, MPI_Fint *ierr) { MPI_Cart_rank_fortran_wrapper(comm, coords, rank, ierr); } _EXTERN_C_ void mpi_cart_rank__(MPI_Fint *comm, MPI_Fint coords[], MPI_Fint *rank, MPI_Fint *ierr) { MPI_Cart_rank_fortran_wrapper(comm, coords, rank, ierr); } /* ================= End Wrappers for MPI_Cart_rank ================= */ /* ================== C Wrappers for MPI_Cart_shift ================== */ _EXTERN_C_ int PMPI_Cart_shift(MPI_Comm comm, int direction, int disp, int *rank_source, int *rank_dest); _EXTERN_C_ int MPI_Cart_shift(MPI_Comm comm, int direction, int disp, int *rank_source, int *rank_dest) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Cart_shift(comm, direction, disp, rank_source, rank_dest); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Cart_shift =============== */ static void MPI_Cart_shift_fortran_wrapper(MPI_Fint *comm, MPI_Fint *direction, MPI_Fint *disp, MPI_Fint *rank_source, MPI_Fint *rank_dest, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Cart_shift((MPI_Comm)(*comm), *direction, *disp, (int*)rank_source, (int*)rank_dest); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Cart_shift(MPI_Comm_f2c(*comm), *direction, *disp, (int*)rank_source, (int*)rank_dest); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_CART_SHIFT(MPI_Fint *comm, MPI_Fint *direction, MPI_Fint *disp, MPI_Fint *rank_source, MPI_Fint *rank_dest, MPI_Fint *ierr) { MPI_Cart_shift_fortran_wrapper(comm, direction, disp, rank_source, rank_dest, ierr); } _EXTERN_C_ void mpi_cart_shift(MPI_Fint *comm, MPI_Fint *direction, MPI_Fint *disp, MPI_Fint *rank_source, MPI_Fint *rank_dest, MPI_Fint *ierr) { MPI_Cart_shift_fortran_wrapper(comm, direction, disp, rank_source, rank_dest, ierr); } _EXTERN_C_ void mpi_cart_shift_(MPI_Fint *comm, MPI_Fint *direction, MPI_Fint *disp, MPI_Fint *rank_source, MPI_Fint *rank_dest, MPI_Fint *ierr) { MPI_Cart_shift_fortran_wrapper(comm, direction, disp, rank_source, rank_dest, ierr); } _EXTERN_C_ void mpi_cart_shift__(MPI_Fint *comm, MPI_Fint *direction, MPI_Fint *disp, MPI_Fint *rank_source, MPI_Fint *rank_dest, MPI_Fint *ierr) { MPI_Cart_shift_fortran_wrapper(comm, direction, disp, rank_source, rank_dest, ierr); } /* ================= End Wrappers for MPI_Cart_shift ================= */ /* ================== C Wrappers for MPI_Cart_sub ================== */ _EXTERN_C_ int PMPI_Cart_sub(MPI_Comm comm, const int remain_dims[], MPI_Comm *new_comm); _EXTERN_C_ int MPI_Cart_sub(MPI_Comm comm, const int remain_dims[], MPI_Comm *new_comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Cart_sub(comm, remain_dims, new_comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Cart_sub =============== */ static void MPI_Cart_sub_fortran_wrapper(MPI_Fint *comm, MPI_Fint remain_dims[], MPI_Fint *new_comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Cart_sub((MPI_Comm)(*comm), (const int*)remain_dims, (MPI_Comm*)new_comm); #else /* MPI-2 safe call */ MPI_Comm temp_new_comm; temp_new_comm = MPI_Comm_f2c(*new_comm); _wrap_py_return_val = MPI_Cart_sub(MPI_Comm_f2c(*comm), (const int*)remain_dims, &temp_new_comm); *new_comm = MPI_Comm_c2f(temp_new_comm); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_CART_SUB(MPI_Fint *comm, MPI_Fint remain_dims[], MPI_Fint *new_comm, MPI_Fint *ierr) { MPI_Cart_sub_fortran_wrapper(comm, remain_dims, new_comm, ierr); } _EXTERN_C_ void mpi_cart_sub(MPI_Fint *comm, MPI_Fint remain_dims[], MPI_Fint *new_comm, MPI_Fint *ierr) { MPI_Cart_sub_fortran_wrapper(comm, remain_dims, new_comm, ierr); } _EXTERN_C_ void mpi_cart_sub_(MPI_Fint *comm, MPI_Fint remain_dims[], MPI_Fint *new_comm, MPI_Fint *ierr) { MPI_Cart_sub_fortran_wrapper(comm, remain_dims, new_comm, ierr); } _EXTERN_C_ void mpi_cart_sub__(MPI_Fint *comm, MPI_Fint remain_dims[], MPI_Fint *new_comm, MPI_Fint *ierr) { MPI_Cart_sub_fortran_wrapper(comm, remain_dims, new_comm, ierr); } /* ================= End Wrappers for MPI_Cart_sub ================= */ /* ================== C Wrappers for MPI_Cartdim_get ================== */ _EXTERN_C_ int PMPI_Cartdim_get(MPI_Comm comm, int *ndims); _EXTERN_C_ int MPI_Cartdim_get(MPI_Comm comm, int *ndims) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Cartdim_get(comm, ndims); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Cartdim_get =============== */ static void MPI_Cartdim_get_fortran_wrapper(MPI_Fint *comm, MPI_Fint *ndims, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Cartdim_get((MPI_Comm)(*comm), (int*)ndims); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Cartdim_get(MPI_Comm_f2c(*comm), (int*)ndims); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_CARTDIM_GET(MPI_Fint *comm, MPI_Fint *ndims, MPI_Fint *ierr) { MPI_Cartdim_get_fortran_wrapper(comm, ndims, ierr); } _EXTERN_C_ void mpi_cartdim_get(MPI_Fint *comm, MPI_Fint *ndims, MPI_Fint *ierr) { MPI_Cartdim_get_fortran_wrapper(comm, ndims, ierr); } _EXTERN_C_ void mpi_cartdim_get_(MPI_Fint *comm, MPI_Fint *ndims, MPI_Fint *ierr) { MPI_Cartdim_get_fortran_wrapper(comm, ndims, ierr); } _EXTERN_C_ void mpi_cartdim_get__(MPI_Fint *comm, MPI_Fint *ndims, MPI_Fint *ierr) { MPI_Cartdim_get_fortran_wrapper(comm, ndims, ierr); } /* ================= End Wrappers for MPI_Cartdim_get ================= */ /* ================== C Wrappers for MPI_Close_port ================== */ _EXTERN_C_ int PMPI_Close_port(const char *port_name); _EXTERN_C_ int MPI_Close_port(const char *port_name) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Close_port(port_name); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Close_port =============== */ static void MPI_Close_port_fortran_wrapper(MPI_Fint *port_name, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Close_port((const char*)port_name); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_CLOSE_PORT(MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Close_port_fortran_wrapper(port_name, ierr); } _EXTERN_C_ void mpi_close_port(MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Close_port_fortran_wrapper(port_name, ierr); } _EXTERN_C_ void mpi_close_port_(MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Close_port_fortran_wrapper(port_name, ierr); } _EXTERN_C_ void mpi_close_port__(MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Close_port_fortran_wrapper(port_name, ierr); } /* ================= End Wrappers for MPI_Close_port ================= */ /* ================== C Wrappers for MPI_Comm_accept ================== */ _EXTERN_C_ int PMPI_Comm_accept(const char *port_name, MPI_Info info, int root, MPI_Comm comm, MPI_Comm *newcomm); _EXTERN_C_ int MPI_Comm_accept(const char *port_name, MPI_Info info, int root, MPI_Comm comm, MPI_Comm *newcomm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_accept(port_name, info, root, comm, newcomm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_accept =============== */ static void MPI_Comm_accept_fortran_wrapper(MPI_Fint *port_name, MPI_Fint *info, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_accept((const char*)port_name, (MPI_Info)(*info), *root, (MPI_Comm)(*comm), (MPI_Comm*)newcomm); #else /* MPI-2 safe call */ MPI_Comm temp_newcomm; temp_newcomm = MPI_Comm_f2c(*newcomm); _wrap_py_return_val = MPI_Comm_accept((const char*)port_name, MPI_Info_f2c(*info), *root, MPI_Comm_f2c(*comm), &temp_newcomm); *newcomm = MPI_Comm_c2f(temp_newcomm); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_ACCEPT(MPI_Fint *port_name, MPI_Fint *info, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_accept_fortran_wrapper(port_name, info, root, comm, newcomm, ierr); } _EXTERN_C_ void mpi_comm_accept(MPI_Fint *port_name, MPI_Fint *info, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_accept_fortran_wrapper(port_name, info, root, comm, newcomm, ierr); } _EXTERN_C_ void mpi_comm_accept_(MPI_Fint *port_name, MPI_Fint *info, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_accept_fortran_wrapper(port_name, info, root, comm, newcomm, ierr); } _EXTERN_C_ void mpi_comm_accept__(MPI_Fint *port_name, MPI_Fint *info, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_accept_fortran_wrapper(port_name, info, root, comm, newcomm, ierr); } /* ================= End Wrappers for MPI_Comm_accept ================= */ /* ================== C Wrappers for MPI_Comm_call_errhandler ================== */ _EXTERN_C_ int PMPI_Comm_call_errhandler(MPI_Comm comm, int errorcode); _EXTERN_C_ int MPI_Comm_call_errhandler(MPI_Comm comm, int errorcode) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_call_errhandler(comm, errorcode); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_call_errhandler =============== */ static void MPI_Comm_call_errhandler_fortran_wrapper(MPI_Fint *comm, MPI_Fint *errorcode, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_call_errhandler((MPI_Comm)(*comm), *errorcode); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Comm_call_errhandler(MPI_Comm_f2c(*comm), *errorcode); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_CALL_ERRHANDLER(MPI_Fint *comm, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_Comm_call_errhandler_fortran_wrapper(comm, errorcode, ierr); } _EXTERN_C_ void mpi_comm_call_errhandler(MPI_Fint *comm, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_Comm_call_errhandler_fortran_wrapper(comm, errorcode, ierr); } _EXTERN_C_ void mpi_comm_call_errhandler_(MPI_Fint *comm, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_Comm_call_errhandler_fortran_wrapper(comm, errorcode, ierr); } _EXTERN_C_ void mpi_comm_call_errhandler__(MPI_Fint *comm, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_Comm_call_errhandler_fortran_wrapper(comm, errorcode, ierr); } /* ================= End Wrappers for MPI_Comm_call_errhandler ================= */ /* ================== C Wrappers for MPI_Comm_compare ================== */ _EXTERN_C_ int PMPI_Comm_compare(MPI_Comm comm1, MPI_Comm comm2, int *result); _EXTERN_C_ int MPI_Comm_compare(MPI_Comm comm1, MPI_Comm comm2, int *result) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_compare(comm1, comm2, result); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_compare =============== */ static void MPI_Comm_compare_fortran_wrapper(MPI_Fint *comm1, MPI_Fint *comm2, MPI_Fint *result, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_compare((MPI_Comm)(*comm1), (MPI_Comm)(*comm2), (int*)result); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Comm_compare(MPI_Comm_f2c(*comm1), MPI_Comm_f2c(*comm2), (int*)result); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_COMPARE(MPI_Fint *comm1, MPI_Fint *comm2, MPI_Fint *result, MPI_Fint *ierr) { MPI_Comm_compare_fortran_wrapper(comm1, comm2, result, ierr); } _EXTERN_C_ void mpi_comm_compare(MPI_Fint *comm1, MPI_Fint *comm2, MPI_Fint *result, MPI_Fint *ierr) { MPI_Comm_compare_fortran_wrapper(comm1, comm2, result, ierr); } _EXTERN_C_ void mpi_comm_compare_(MPI_Fint *comm1, MPI_Fint *comm2, MPI_Fint *result, MPI_Fint *ierr) { MPI_Comm_compare_fortran_wrapper(comm1, comm2, result, ierr); } _EXTERN_C_ void mpi_comm_compare__(MPI_Fint *comm1, MPI_Fint *comm2, MPI_Fint *result, MPI_Fint *ierr) { MPI_Comm_compare_fortran_wrapper(comm1, comm2, result, ierr); } /* ================= End Wrappers for MPI_Comm_compare ================= */ /* ================== C Wrappers for MPI_Comm_connect ================== */ _EXTERN_C_ int PMPI_Comm_connect(const char *port_name, MPI_Info info, int root, MPI_Comm comm, MPI_Comm *newcomm); _EXTERN_C_ int MPI_Comm_connect(const char *port_name, MPI_Info info, int root, MPI_Comm comm, MPI_Comm *newcomm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_connect(port_name, info, root, comm, newcomm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_connect =============== */ static void MPI_Comm_connect_fortran_wrapper(MPI_Fint *port_name, MPI_Fint *info, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_connect((const char*)port_name, (MPI_Info)(*info), *root, (MPI_Comm)(*comm), (MPI_Comm*)newcomm); #else /* MPI-2 safe call */ MPI_Comm temp_newcomm; temp_newcomm = MPI_Comm_f2c(*newcomm); _wrap_py_return_val = MPI_Comm_connect((const char*)port_name, MPI_Info_f2c(*info), *root, MPI_Comm_f2c(*comm), &temp_newcomm); *newcomm = MPI_Comm_c2f(temp_newcomm); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_CONNECT(MPI_Fint *port_name, MPI_Fint *info, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_connect_fortran_wrapper(port_name, info, root, comm, newcomm, ierr); } _EXTERN_C_ void mpi_comm_connect(MPI_Fint *port_name, MPI_Fint *info, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_connect_fortran_wrapper(port_name, info, root, comm, newcomm, ierr); } _EXTERN_C_ void mpi_comm_connect_(MPI_Fint *port_name, MPI_Fint *info, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_connect_fortran_wrapper(port_name, info, root, comm, newcomm, ierr); } _EXTERN_C_ void mpi_comm_connect__(MPI_Fint *port_name, MPI_Fint *info, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_connect_fortran_wrapper(port_name, info, root, comm, newcomm, ierr); } /* ================= End Wrappers for MPI_Comm_connect ================= */ /* ================== C Wrappers for MPI_Comm_create ================== */ _EXTERN_C_ int PMPI_Comm_create(MPI_Comm comm, MPI_Group group, MPI_Comm *newcomm); _EXTERN_C_ int MPI_Comm_create(MPI_Comm comm, MPI_Group group, MPI_Comm *newcomm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_create(comm, group, newcomm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_create =============== */ static void MPI_Comm_create_fortran_wrapper(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *newcomm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_create((MPI_Comm)(*comm), (MPI_Group)(*group), (MPI_Comm*)newcomm); #else /* MPI-2 safe call */ MPI_Comm temp_newcomm; temp_newcomm = MPI_Comm_f2c(*newcomm); _wrap_py_return_val = MPI_Comm_create(MPI_Comm_f2c(*comm), MPI_Group_f2c(*group), &temp_newcomm); *newcomm = MPI_Comm_c2f(temp_newcomm); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_CREATE(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_create_fortran_wrapper(comm, group, newcomm, ierr); } _EXTERN_C_ void mpi_comm_create(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_create_fortran_wrapper(comm, group, newcomm, ierr); } _EXTERN_C_ void mpi_comm_create_(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_create_fortran_wrapper(comm, group, newcomm, ierr); } _EXTERN_C_ void mpi_comm_create__(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_create_fortran_wrapper(comm, group, newcomm, ierr); } /* ================= End Wrappers for MPI_Comm_create ================= */ /* ================== C Wrappers for MPI_Comm_create_errhandler ================== */ _EXTERN_C_ int PMPI_Comm_create_errhandler(MPI_Comm_errhandler_function *function, MPI_Errhandler *errhandler); _EXTERN_C_ int MPI_Comm_create_errhandler(MPI_Comm_errhandler_function *function, MPI_Errhandler *errhandler) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_create_errhandler(function, errhandler); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_create_errhandler =============== */ static void MPI_Comm_create_errhandler_fortran_wrapper(MPI_Comm_errhandler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_create_errhandler((MPI_Comm_errhandler_function*)function, (MPI_Errhandler*)errhandler); #else /* MPI-2 safe call */ MPI_Errhandler temp_errhandler; temp_errhandler = MPI_Errhandler_f2c(*errhandler); _wrap_py_return_val = MPI_Comm_create_errhandler((MPI_Comm_errhandler_function*)function, &temp_errhandler); *errhandler = MPI_Errhandler_c2f(temp_errhandler); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_CREATE_ERRHANDLER(MPI_Comm_errhandler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Comm_create_errhandler_fortran_wrapper(function, errhandler, ierr); } _EXTERN_C_ void mpi_comm_create_errhandler(MPI_Comm_errhandler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Comm_create_errhandler_fortran_wrapper(function, errhandler, ierr); } _EXTERN_C_ void mpi_comm_create_errhandler_(MPI_Comm_errhandler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Comm_create_errhandler_fortran_wrapper(function, errhandler, ierr); } _EXTERN_C_ void mpi_comm_create_errhandler__(MPI_Comm_errhandler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Comm_create_errhandler_fortran_wrapper(function, errhandler, ierr); } /* ================= End Wrappers for MPI_Comm_create_errhandler ================= */ /* ================== C Wrappers for MPI_Comm_create_group ================== */ _EXTERN_C_ int PMPI_Comm_create_group(MPI_Comm comm, MPI_Group group, int tag, MPI_Comm *newcomm); _EXTERN_C_ int MPI_Comm_create_group(MPI_Comm comm, MPI_Group group, int tag, MPI_Comm *newcomm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_create_group(comm, group, tag, newcomm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_create_group =============== */ static void MPI_Comm_create_group_fortran_wrapper(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *tag, MPI_Fint *newcomm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_create_group((MPI_Comm)(*comm), (MPI_Group)(*group), *tag, (MPI_Comm*)newcomm); #else /* MPI-2 safe call */ MPI_Comm temp_newcomm; temp_newcomm = MPI_Comm_f2c(*newcomm); _wrap_py_return_val = MPI_Comm_create_group(MPI_Comm_f2c(*comm), MPI_Group_f2c(*group), *tag, &temp_newcomm); *newcomm = MPI_Comm_c2f(temp_newcomm); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_CREATE_GROUP(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *tag, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_create_group_fortran_wrapper(comm, group, tag, newcomm, ierr); } _EXTERN_C_ void mpi_comm_create_group(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *tag, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_create_group_fortran_wrapper(comm, group, tag, newcomm, ierr); } _EXTERN_C_ void mpi_comm_create_group_(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *tag, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_create_group_fortran_wrapper(comm, group, tag, newcomm, ierr); } _EXTERN_C_ void mpi_comm_create_group__(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *tag, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_create_group_fortran_wrapper(comm, group, tag, newcomm, ierr); } /* ================= End Wrappers for MPI_Comm_create_group ================= */ /* ================== C Wrappers for MPI_Comm_create_keyval ================== */ _EXTERN_C_ int PMPI_Comm_create_keyval(MPI_Comm_copy_attr_function *comm_copy_attr_fn, MPI_Comm_delete_attr_function *comm_delete_attr_fn, int *comm_keyval, void *extra_state); _EXTERN_C_ int MPI_Comm_create_keyval(MPI_Comm_copy_attr_function *comm_copy_attr_fn, MPI_Comm_delete_attr_function *comm_delete_attr_fn, int *comm_keyval, void *extra_state) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_create_keyval(comm_copy_attr_fn, comm_delete_attr_fn, comm_keyval, extra_state); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_create_keyval =============== */ static void MPI_Comm_create_keyval_fortran_wrapper(MPI_Comm_copy_attr_function *comm_copy_attr_fn, MPI_Comm_delete_attr_function *comm_delete_attr_fn, MPI_Fint *comm_keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Comm_create_keyval((MPI_Comm_copy_attr_function*)comm_copy_attr_fn, (MPI_Comm_delete_attr_function*)comm_delete_attr_fn, (int*)comm_keyval, (void*)extra_state); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_CREATE_KEYVAL(MPI_Comm_copy_attr_function *comm_copy_attr_fn, MPI_Comm_delete_attr_function *comm_delete_attr_fn, MPI_Fint *comm_keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Comm_create_keyval_fortran_wrapper(comm_copy_attr_fn, comm_delete_attr_fn, comm_keyval, extra_state, ierr); } _EXTERN_C_ void mpi_comm_create_keyval(MPI_Comm_copy_attr_function *comm_copy_attr_fn, MPI_Comm_delete_attr_function *comm_delete_attr_fn, MPI_Fint *comm_keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Comm_create_keyval_fortran_wrapper(comm_copy_attr_fn, comm_delete_attr_fn, comm_keyval, extra_state, ierr); } _EXTERN_C_ void mpi_comm_create_keyval_(MPI_Comm_copy_attr_function *comm_copy_attr_fn, MPI_Comm_delete_attr_function *comm_delete_attr_fn, MPI_Fint *comm_keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Comm_create_keyval_fortran_wrapper(comm_copy_attr_fn, comm_delete_attr_fn, comm_keyval, extra_state, ierr); } _EXTERN_C_ void mpi_comm_create_keyval__(MPI_Comm_copy_attr_function *comm_copy_attr_fn, MPI_Comm_delete_attr_function *comm_delete_attr_fn, MPI_Fint *comm_keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Comm_create_keyval_fortran_wrapper(comm_copy_attr_fn, comm_delete_attr_fn, comm_keyval, extra_state, ierr); } /* ================= End Wrappers for MPI_Comm_create_keyval ================= */ /* ================== C Wrappers for MPI_Comm_delete_attr ================== */ _EXTERN_C_ int PMPI_Comm_delete_attr(MPI_Comm comm, int comm_keyval); _EXTERN_C_ int MPI_Comm_delete_attr(MPI_Comm comm, int comm_keyval) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_delete_attr(comm, comm_keyval); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_delete_attr =============== */ static void MPI_Comm_delete_attr_fortran_wrapper(MPI_Fint *comm, MPI_Fint *comm_keyval, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_delete_attr((MPI_Comm)(*comm), *comm_keyval); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Comm_delete_attr(MPI_Comm_f2c(*comm), *comm_keyval); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_DELETE_ATTR(MPI_Fint *comm, MPI_Fint *comm_keyval, MPI_Fint *ierr) { MPI_Comm_delete_attr_fortran_wrapper(comm, comm_keyval, ierr); } _EXTERN_C_ void mpi_comm_delete_attr(MPI_Fint *comm, MPI_Fint *comm_keyval, MPI_Fint *ierr) { MPI_Comm_delete_attr_fortran_wrapper(comm, comm_keyval, ierr); } _EXTERN_C_ void mpi_comm_delete_attr_(MPI_Fint *comm, MPI_Fint *comm_keyval, MPI_Fint *ierr) { MPI_Comm_delete_attr_fortran_wrapper(comm, comm_keyval, ierr); } _EXTERN_C_ void mpi_comm_delete_attr__(MPI_Fint *comm, MPI_Fint *comm_keyval, MPI_Fint *ierr) { MPI_Comm_delete_attr_fortran_wrapper(comm, comm_keyval, ierr); } /* ================= End Wrappers for MPI_Comm_delete_attr ================= */ /* ================== C Wrappers for MPI_Comm_disconnect ================== */ _EXTERN_C_ int PMPI_Comm_disconnect(MPI_Comm *comm); _EXTERN_C_ int MPI_Comm_disconnect(MPI_Comm *comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_disconnect(comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_disconnect =============== */ static void MPI_Comm_disconnect_fortran_wrapper(MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_disconnect((MPI_Comm*)comm); #else /* MPI-2 safe call */ MPI_Comm temp_comm; temp_comm = MPI_Comm_f2c(*comm); _wrap_py_return_val = MPI_Comm_disconnect(&temp_comm); *comm = MPI_Comm_c2f(temp_comm); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_DISCONNECT(MPI_Fint *comm, MPI_Fint *ierr) { MPI_Comm_disconnect_fortran_wrapper(comm, ierr); } _EXTERN_C_ void mpi_comm_disconnect(MPI_Fint *comm, MPI_Fint *ierr) { MPI_Comm_disconnect_fortran_wrapper(comm, ierr); } _EXTERN_C_ void mpi_comm_disconnect_(MPI_Fint *comm, MPI_Fint *ierr) { MPI_Comm_disconnect_fortran_wrapper(comm, ierr); } _EXTERN_C_ void mpi_comm_disconnect__(MPI_Fint *comm, MPI_Fint *ierr) { MPI_Comm_disconnect_fortran_wrapper(comm, ierr); } /* ================= End Wrappers for MPI_Comm_disconnect ================= */ /* ================== C Wrappers for MPI_Comm_dup ================== */ _EXTERN_C_ int PMPI_Comm_dup(MPI_Comm comm, MPI_Comm *newcomm); _EXTERN_C_ int MPI_Comm_dup(MPI_Comm comm, MPI_Comm *newcomm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_dup(comm, newcomm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_dup =============== */ static void MPI_Comm_dup_fortran_wrapper(MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_dup((MPI_Comm)(*comm), (MPI_Comm*)newcomm); #else /* MPI-2 safe call */ MPI_Comm temp_newcomm; temp_newcomm = MPI_Comm_f2c(*newcomm); _wrap_py_return_val = MPI_Comm_dup(MPI_Comm_f2c(*comm), &temp_newcomm); *newcomm = MPI_Comm_c2f(temp_newcomm); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_DUP(MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_dup_fortran_wrapper(comm, newcomm, ierr); } _EXTERN_C_ void mpi_comm_dup(MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_dup_fortran_wrapper(comm, newcomm, ierr); } _EXTERN_C_ void mpi_comm_dup_(MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_dup_fortran_wrapper(comm, newcomm, ierr); } _EXTERN_C_ void mpi_comm_dup__(MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_dup_fortran_wrapper(comm, newcomm, ierr); } /* ================= End Wrappers for MPI_Comm_dup ================= */ /* ================== C Wrappers for MPI_Comm_dup_with_info ================== */ _EXTERN_C_ int PMPI_Comm_dup_with_info(MPI_Comm comm, MPI_Info info, MPI_Comm *newcomm); _EXTERN_C_ int MPI_Comm_dup_with_info(MPI_Comm comm, MPI_Info info, MPI_Comm *newcomm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_dup_with_info(comm, info, newcomm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_dup_with_info =============== */ static void MPI_Comm_dup_with_info_fortran_wrapper(MPI_Fint *comm, MPI_Fint *info, MPI_Fint *newcomm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_dup_with_info((MPI_Comm)(*comm), (MPI_Info)(*info), (MPI_Comm*)newcomm); #else /* MPI-2 safe call */ MPI_Comm temp_newcomm; temp_newcomm = MPI_Comm_f2c(*newcomm); _wrap_py_return_val = MPI_Comm_dup_with_info(MPI_Comm_f2c(*comm), MPI_Info_f2c(*info), &temp_newcomm); *newcomm = MPI_Comm_c2f(temp_newcomm); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_DUP_WITH_INFO(MPI_Fint *comm, MPI_Fint *info, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_dup_with_info_fortran_wrapper(comm, info, newcomm, ierr); } _EXTERN_C_ void mpi_comm_dup_with_info(MPI_Fint *comm, MPI_Fint *info, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_dup_with_info_fortran_wrapper(comm, info, newcomm, ierr); } _EXTERN_C_ void mpi_comm_dup_with_info_(MPI_Fint *comm, MPI_Fint *info, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_dup_with_info_fortran_wrapper(comm, info, newcomm, ierr); } _EXTERN_C_ void mpi_comm_dup_with_info__(MPI_Fint *comm, MPI_Fint *info, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_dup_with_info_fortran_wrapper(comm, info, newcomm, ierr); } /* ================= End Wrappers for MPI_Comm_dup_with_info ================= */ /* ================== C Wrappers for MPI_Comm_free ================== */ _EXTERN_C_ int PMPI_Comm_free(MPI_Comm *comm); _EXTERN_C_ int MPI_Comm_free(MPI_Comm *comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_free(comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_free =============== */ static void MPI_Comm_free_fortran_wrapper(MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_free((MPI_Comm*)comm); #else /* MPI-2 safe call */ MPI_Comm temp_comm; temp_comm = MPI_Comm_f2c(*comm); _wrap_py_return_val = MPI_Comm_free(&temp_comm); *comm = MPI_Comm_c2f(temp_comm); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_FREE(MPI_Fint *comm, MPI_Fint *ierr) { MPI_Comm_free_fortran_wrapper(comm, ierr); } _EXTERN_C_ void mpi_comm_free(MPI_Fint *comm, MPI_Fint *ierr) { MPI_Comm_free_fortran_wrapper(comm, ierr); } _EXTERN_C_ void mpi_comm_free_(MPI_Fint *comm, MPI_Fint *ierr) { MPI_Comm_free_fortran_wrapper(comm, ierr); } _EXTERN_C_ void mpi_comm_free__(MPI_Fint *comm, MPI_Fint *ierr) { MPI_Comm_free_fortran_wrapper(comm, ierr); } /* ================= End Wrappers for MPI_Comm_free ================= */ /* ================== C Wrappers for MPI_Comm_free_keyval ================== */ _EXTERN_C_ int PMPI_Comm_free_keyval(int *comm_keyval); _EXTERN_C_ int MPI_Comm_free_keyval(int *comm_keyval) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_free_keyval(comm_keyval); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_free_keyval =============== */ static void MPI_Comm_free_keyval_fortran_wrapper(MPI_Fint *comm_keyval, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Comm_free_keyval((int*)comm_keyval); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_FREE_KEYVAL(MPI_Fint *comm_keyval, MPI_Fint *ierr) { MPI_Comm_free_keyval_fortran_wrapper(comm_keyval, ierr); } _EXTERN_C_ void mpi_comm_free_keyval(MPI_Fint *comm_keyval, MPI_Fint *ierr) { MPI_Comm_free_keyval_fortran_wrapper(comm_keyval, ierr); } _EXTERN_C_ void mpi_comm_free_keyval_(MPI_Fint *comm_keyval, MPI_Fint *ierr) { MPI_Comm_free_keyval_fortran_wrapper(comm_keyval, ierr); } _EXTERN_C_ void mpi_comm_free_keyval__(MPI_Fint *comm_keyval, MPI_Fint *ierr) { MPI_Comm_free_keyval_fortran_wrapper(comm_keyval, ierr); } /* ================= End Wrappers for MPI_Comm_free_keyval ================= */ /* ================== C Wrappers for MPI_Comm_get_attr ================== */ _EXTERN_C_ int PMPI_Comm_get_attr(MPI_Comm comm, int comm_keyval, void *attribute_val, int *flag); _EXTERN_C_ int MPI_Comm_get_attr(MPI_Comm comm, int comm_keyval, void *attribute_val, int *flag) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_get_attr(comm, comm_keyval, attribute_val, flag); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_get_attr =============== */ static void MPI_Comm_get_attr_fortran_wrapper(MPI_Fint *comm, MPI_Fint *comm_keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_get_attr((MPI_Comm)(*comm), *comm_keyval, (void*)attribute_val, (int*)flag); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Comm_get_attr(MPI_Comm_f2c(*comm), *comm_keyval, (void*)attribute_val, (int*)flag); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_GET_ATTR(MPI_Fint *comm, MPI_Fint *comm_keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Comm_get_attr_fortran_wrapper(comm, comm_keyval, attribute_val, flag, ierr); } _EXTERN_C_ void mpi_comm_get_attr(MPI_Fint *comm, MPI_Fint *comm_keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Comm_get_attr_fortran_wrapper(comm, comm_keyval, attribute_val, flag, ierr); } _EXTERN_C_ void mpi_comm_get_attr_(MPI_Fint *comm, MPI_Fint *comm_keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Comm_get_attr_fortran_wrapper(comm, comm_keyval, attribute_val, flag, ierr); } _EXTERN_C_ void mpi_comm_get_attr__(MPI_Fint *comm, MPI_Fint *comm_keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Comm_get_attr_fortran_wrapper(comm, comm_keyval, attribute_val, flag, ierr); } /* ================= End Wrappers for MPI_Comm_get_attr ================= */ /* ================== C Wrappers for MPI_Comm_get_errhandler ================== */ _EXTERN_C_ int PMPI_Comm_get_errhandler(MPI_Comm comm, MPI_Errhandler *erhandler); _EXTERN_C_ int MPI_Comm_get_errhandler(MPI_Comm comm, MPI_Errhandler *erhandler) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_get_errhandler(comm, erhandler); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_get_errhandler =============== */ static void MPI_Comm_get_errhandler_fortran_wrapper(MPI_Fint *comm, MPI_Fint *erhandler, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_get_errhandler((MPI_Comm)(*comm), (MPI_Errhandler*)erhandler); #else /* MPI-2 safe call */ MPI_Errhandler temp_erhandler; temp_erhandler = MPI_Errhandler_f2c(*erhandler); _wrap_py_return_val = MPI_Comm_get_errhandler(MPI_Comm_f2c(*comm), &temp_erhandler); *erhandler = MPI_Errhandler_c2f(temp_erhandler); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_GET_ERRHANDLER(MPI_Fint *comm, MPI_Fint *erhandler, MPI_Fint *ierr) { MPI_Comm_get_errhandler_fortran_wrapper(comm, erhandler, ierr); } _EXTERN_C_ void mpi_comm_get_errhandler(MPI_Fint *comm, MPI_Fint *erhandler, MPI_Fint *ierr) { MPI_Comm_get_errhandler_fortran_wrapper(comm, erhandler, ierr); } _EXTERN_C_ void mpi_comm_get_errhandler_(MPI_Fint *comm, MPI_Fint *erhandler, MPI_Fint *ierr) { MPI_Comm_get_errhandler_fortran_wrapper(comm, erhandler, ierr); } _EXTERN_C_ void mpi_comm_get_errhandler__(MPI_Fint *comm, MPI_Fint *erhandler, MPI_Fint *ierr) { MPI_Comm_get_errhandler_fortran_wrapper(comm, erhandler, ierr); } /* ================= End Wrappers for MPI_Comm_get_errhandler ================= */ /* ================== C Wrappers for MPI_Comm_get_info ================== */ _EXTERN_C_ int PMPI_Comm_get_info(MPI_Comm comm, MPI_Info *info_used); _EXTERN_C_ int MPI_Comm_get_info(MPI_Comm comm, MPI_Info *info_used) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_get_info(comm, info_used); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_get_info =============== */ static void MPI_Comm_get_info_fortran_wrapper(MPI_Fint *comm, MPI_Fint *info_used, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_get_info((MPI_Comm)(*comm), (MPI_Info*)info_used); #else /* MPI-2 safe call */ MPI_Info temp_info_used; temp_info_used = MPI_Info_f2c(*info_used); _wrap_py_return_val = MPI_Comm_get_info(MPI_Comm_f2c(*comm), &temp_info_used); *info_used = MPI_Info_c2f(temp_info_used); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_GET_INFO(MPI_Fint *comm, MPI_Fint *info_used, MPI_Fint *ierr) { MPI_Comm_get_info_fortran_wrapper(comm, info_used, ierr); } _EXTERN_C_ void mpi_comm_get_info(MPI_Fint *comm, MPI_Fint *info_used, MPI_Fint *ierr) { MPI_Comm_get_info_fortran_wrapper(comm, info_used, ierr); } _EXTERN_C_ void mpi_comm_get_info_(MPI_Fint *comm, MPI_Fint *info_used, MPI_Fint *ierr) { MPI_Comm_get_info_fortran_wrapper(comm, info_used, ierr); } _EXTERN_C_ void mpi_comm_get_info__(MPI_Fint *comm, MPI_Fint *info_used, MPI_Fint *ierr) { MPI_Comm_get_info_fortran_wrapper(comm, info_used, ierr); } /* ================= End Wrappers for MPI_Comm_get_info ================= */ /* ================== C Wrappers for MPI_Comm_get_name ================== */ _EXTERN_C_ int PMPI_Comm_get_name(MPI_Comm comm, char *comm_name, int *resultlen); _EXTERN_C_ int MPI_Comm_get_name(MPI_Comm comm, char *comm_name, int *resultlen) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_get_name(comm, comm_name, resultlen); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_get_name =============== */ static void MPI_Comm_get_name_fortran_wrapper(MPI_Fint *comm, MPI_Fint *comm_name, MPI_Fint *resultlen, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_get_name((MPI_Comm)(*comm), (char*)comm_name, (int*)resultlen); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Comm_get_name(MPI_Comm_f2c(*comm), (char*)comm_name, (int*)resultlen); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_GET_NAME(MPI_Fint *comm, MPI_Fint *comm_name, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Comm_get_name_fortran_wrapper(comm, comm_name, resultlen, ierr); } _EXTERN_C_ void mpi_comm_get_name(MPI_Fint *comm, MPI_Fint *comm_name, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Comm_get_name_fortran_wrapper(comm, comm_name, resultlen, ierr); } _EXTERN_C_ void mpi_comm_get_name_(MPI_Fint *comm, MPI_Fint *comm_name, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Comm_get_name_fortran_wrapper(comm, comm_name, resultlen, ierr); } _EXTERN_C_ void mpi_comm_get_name__(MPI_Fint *comm, MPI_Fint *comm_name, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Comm_get_name_fortran_wrapper(comm, comm_name, resultlen, ierr); } /* ================= End Wrappers for MPI_Comm_get_name ================= */ /* ================== C Wrappers for MPI_Comm_get_parent ================== */ _EXTERN_C_ int PMPI_Comm_get_parent(MPI_Comm *parent); _EXTERN_C_ int MPI_Comm_get_parent(MPI_Comm *parent) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_get_parent(parent); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_get_parent =============== */ static void MPI_Comm_get_parent_fortran_wrapper(MPI_Fint *parent, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_get_parent((MPI_Comm*)parent); #else /* MPI-2 safe call */ MPI_Comm temp_parent; temp_parent = MPI_Comm_f2c(*parent); _wrap_py_return_val = MPI_Comm_get_parent(&temp_parent); *parent = MPI_Comm_c2f(temp_parent); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_GET_PARENT(MPI_Fint *parent, MPI_Fint *ierr) { MPI_Comm_get_parent_fortran_wrapper(parent, ierr); } _EXTERN_C_ void mpi_comm_get_parent(MPI_Fint *parent, MPI_Fint *ierr) { MPI_Comm_get_parent_fortran_wrapper(parent, ierr); } _EXTERN_C_ void mpi_comm_get_parent_(MPI_Fint *parent, MPI_Fint *ierr) { MPI_Comm_get_parent_fortran_wrapper(parent, ierr); } _EXTERN_C_ void mpi_comm_get_parent__(MPI_Fint *parent, MPI_Fint *ierr) { MPI_Comm_get_parent_fortran_wrapper(parent, ierr); } /* ================= End Wrappers for MPI_Comm_get_parent ================= */ /* ================== C Wrappers for MPI_Comm_group ================== */ _EXTERN_C_ int PMPI_Comm_group(MPI_Comm comm, MPI_Group *group); _EXTERN_C_ int MPI_Comm_group(MPI_Comm comm, MPI_Group *group) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_group(comm, group); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_group =============== */ static void MPI_Comm_group_fortran_wrapper(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_group((MPI_Comm)(*comm), (MPI_Group*)group); #else /* MPI-2 safe call */ MPI_Group temp_group; temp_group = MPI_Group_f2c(*group); _wrap_py_return_val = MPI_Comm_group(MPI_Comm_f2c(*comm), &temp_group); *group = MPI_Group_c2f(temp_group); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_GROUP(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *ierr) { MPI_Comm_group_fortran_wrapper(comm, group, ierr); } _EXTERN_C_ void mpi_comm_group(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *ierr) { MPI_Comm_group_fortran_wrapper(comm, group, ierr); } _EXTERN_C_ void mpi_comm_group_(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *ierr) { MPI_Comm_group_fortran_wrapper(comm, group, ierr); } _EXTERN_C_ void mpi_comm_group__(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *ierr) { MPI_Comm_group_fortran_wrapper(comm, group, ierr); } /* ================= End Wrappers for MPI_Comm_group ================= */ /* ================== C Wrappers for MPI_Comm_idup ================== */ _EXTERN_C_ int PMPI_Comm_idup(MPI_Comm comm, MPI_Comm *newcomm, MPI_Request *request); _EXTERN_C_ int MPI_Comm_idup(MPI_Comm comm, MPI_Comm *newcomm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_idup(comm, newcomm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_idup =============== */ static void MPI_Comm_idup_fortran_wrapper(MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_idup((MPI_Comm)(*comm), (MPI_Comm*)newcomm, (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; MPI_Comm temp_newcomm; temp_newcomm = MPI_Comm_f2c(*newcomm); temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Comm_idup(MPI_Comm_f2c(*comm), &temp_newcomm, &temp_request); *newcomm = MPI_Comm_c2f(temp_newcomm); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_IDUP(MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Comm_idup_fortran_wrapper(comm, newcomm, request, ierr); } _EXTERN_C_ void mpi_comm_idup(MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Comm_idup_fortran_wrapper(comm, newcomm, request, ierr); } _EXTERN_C_ void mpi_comm_idup_(MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Comm_idup_fortran_wrapper(comm, newcomm, request, ierr); } _EXTERN_C_ void mpi_comm_idup__(MPI_Fint *comm, MPI_Fint *newcomm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Comm_idup_fortran_wrapper(comm, newcomm, request, ierr); } /* ================= End Wrappers for MPI_Comm_idup ================= */ /* ================== C Wrappers for MPI_Comm_join ================== */ _EXTERN_C_ int PMPI_Comm_join(int fd, MPI_Comm *intercomm); _EXTERN_C_ int MPI_Comm_join(int fd, MPI_Comm *intercomm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_join(fd, intercomm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_join =============== */ static void MPI_Comm_join_fortran_wrapper(MPI_Fint *fd, MPI_Fint *intercomm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_join(*fd, (MPI_Comm*)intercomm); #else /* MPI-2 safe call */ MPI_Comm temp_intercomm; temp_intercomm = MPI_Comm_f2c(*intercomm); _wrap_py_return_val = MPI_Comm_join(*fd, &temp_intercomm); *intercomm = MPI_Comm_c2f(temp_intercomm); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_JOIN(MPI_Fint *fd, MPI_Fint *intercomm, MPI_Fint *ierr) { MPI_Comm_join_fortran_wrapper(fd, intercomm, ierr); } _EXTERN_C_ void mpi_comm_join(MPI_Fint *fd, MPI_Fint *intercomm, MPI_Fint *ierr) { MPI_Comm_join_fortran_wrapper(fd, intercomm, ierr); } _EXTERN_C_ void mpi_comm_join_(MPI_Fint *fd, MPI_Fint *intercomm, MPI_Fint *ierr) { MPI_Comm_join_fortran_wrapper(fd, intercomm, ierr); } _EXTERN_C_ void mpi_comm_join__(MPI_Fint *fd, MPI_Fint *intercomm, MPI_Fint *ierr) { MPI_Comm_join_fortran_wrapper(fd, intercomm, ierr); } /* ================= End Wrappers for MPI_Comm_join ================= */ /* ================== C Wrappers for MPI_Comm_rank ================== */ _EXTERN_C_ int PMPI_Comm_rank(MPI_Comm comm, int *rank); _EXTERN_C_ int MPI_Comm_rank(MPI_Comm comm, int *rank) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX if (isolation_mode) { *rank = current_rank; _wrap_py_return_val = MPI_SUCCESS; } else { _wrap_py_return_val = PMPI_Comm_rank(comm, rank); } WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_rank =============== */ static void MPI_Comm_rank_fortran_wrapper(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_rank((MPI_Comm)(*comm), (int*)rank); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Comm_rank(MPI_Comm_f2c(*comm), (int*)rank); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_RANK(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *ierr) { MPI_Comm_rank_fortran_wrapper(comm, rank, ierr); } _EXTERN_C_ void mpi_comm_rank(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *ierr) { MPI_Comm_rank_fortran_wrapper(comm, rank, ierr); } _EXTERN_C_ void mpi_comm_rank_(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *ierr) { MPI_Comm_rank_fortran_wrapper(comm, rank, ierr); } _EXTERN_C_ void mpi_comm_rank__(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *ierr) { MPI_Comm_rank_fortran_wrapper(comm, rank, ierr); } /* ================= End Wrappers for MPI_Comm_rank ================= */ /* ================== C Wrappers for MPI_Comm_remote_group ================== */ _EXTERN_C_ int PMPI_Comm_remote_group(MPI_Comm comm, MPI_Group *group); _EXTERN_C_ int MPI_Comm_remote_group(MPI_Comm comm, MPI_Group *group) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_remote_group(comm, group); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_remote_group =============== */ static void MPI_Comm_remote_group_fortran_wrapper(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_remote_group((MPI_Comm)(*comm), (MPI_Group*)group); #else /* MPI-2 safe call */ MPI_Group temp_group; temp_group = MPI_Group_f2c(*group); _wrap_py_return_val = MPI_Comm_remote_group(MPI_Comm_f2c(*comm), &temp_group); *group = MPI_Group_c2f(temp_group); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_REMOTE_GROUP(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *ierr) { MPI_Comm_remote_group_fortran_wrapper(comm, group, ierr); } _EXTERN_C_ void mpi_comm_remote_group(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *ierr) { MPI_Comm_remote_group_fortran_wrapper(comm, group, ierr); } _EXTERN_C_ void mpi_comm_remote_group_(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *ierr) { MPI_Comm_remote_group_fortran_wrapper(comm, group, ierr); } _EXTERN_C_ void mpi_comm_remote_group__(MPI_Fint *comm, MPI_Fint *group, MPI_Fint *ierr) { MPI_Comm_remote_group_fortran_wrapper(comm, group, ierr); } /* ================= End Wrappers for MPI_Comm_remote_group ================= */ /* ================== C Wrappers for MPI_Comm_remote_size ================== */ _EXTERN_C_ int PMPI_Comm_remote_size(MPI_Comm comm, int *size); _EXTERN_C_ int MPI_Comm_remote_size(MPI_Comm comm, int *size) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_remote_size(comm, size); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_remote_size =============== */ static void MPI_Comm_remote_size_fortran_wrapper(MPI_Fint *comm, MPI_Fint *size, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_remote_size((MPI_Comm)(*comm), (int*)size); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Comm_remote_size(MPI_Comm_f2c(*comm), (int*)size); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_REMOTE_SIZE(MPI_Fint *comm, MPI_Fint *size, MPI_Fint *ierr) { MPI_Comm_remote_size_fortran_wrapper(comm, size, ierr); } _EXTERN_C_ void mpi_comm_remote_size(MPI_Fint *comm, MPI_Fint *size, MPI_Fint *ierr) { MPI_Comm_remote_size_fortran_wrapper(comm, size, ierr); } _EXTERN_C_ void mpi_comm_remote_size_(MPI_Fint *comm, MPI_Fint *size, MPI_Fint *ierr) { MPI_Comm_remote_size_fortran_wrapper(comm, size, ierr); } _EXTERN_C_ void mpi_comm_remote_size__(MPI_Fint *comm, MPI_Fint *size, MPI_Fint *ierr) { MPI_Comm_remote_size_fortran_wrapper(comm, size, ierr); } /* ================= End Wrappers for MPI_Comm_remote_size ================= */ /* ================== C Wrappers for MPI_Comm_set_attr ================== */ _EXTERN_C_ int PMPI_Comm_set_attr(MPI_Comm comm, int comm_keyval, void *attribute_val); _EXTERN_C_ int MPI_Comm_set_attr(MPI_Comm comm, int comm_keyval, void *attribute_val) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_set_attr(comm, comm_keyval, attribute_val); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_set_attr =============== */ static void MPI_Comm_set_attr_fortran_wrapper(MPI_Fint *comm, MPI_Fint *comm_keyval, MPI_Fint *attribute_val, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_set_attr((MPI_Comm)(*comm), *comm_keyval, (void*)attribute_val); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Comm_set_attr(MPI_Comm_f2c(*comm), *comm_keyval, (void*)attribute_val); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_SET_ATTR(MPI_Fint *comm, MPI_Fint *comm_keyval, MPI_Fint *attribute_val, MPI_Fint *ierr) { MPI_Comm_set_attr_fortran_wrapper(comm, comm_keyval, attribute_val, ierr); } _EXTERN_C_ void mpi_comm_set_attr(MPI_Fint *comm, MPI_Fint *comm_keyval, MPI_Fint *attribute_val, MPI_Fint *ierr) { MPI_Comm_set_attr_fortran_wrapper(comm, comm_keyval, attribute_val, ierr); } _EXTERN_C_ void mpi_comm_set_attr_(MPI_Fint *comm, MPI_Fint *comm_keyval, MPI_Fint *attribute_val, MPI_Fint *ierr) { MPI_Comm_set_attr_fortran_wrapper(comm, comm_keyval, attribute_val, ierr); } _EXTERN_C_ void mpi_comm_set_attr__(MPI_Fint *comm, MPI_Fint *comm_keyval, MPI_Fint *attribute_val, MPI_Fint *ierr) { MPI_Comm_set_attr_fortran_wrapper(comm, comm_keyval, attribute_val, ierr); } /* ================= End Wrappers for MPI_Comm_set_attr ================= */ /* ================== C Wrappers for MPI_Comm_set_errhandler ================== */ _EXTERN_C_ int PMPI_Comm_set_errhandler(MPI_Comm comm, MPI_Errhandler errhandler); _EXTERN_C_ int MPI_Comm_set_errhandler(MPI_Comm comm, MPI_Errhandler errhandler) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_set_errhandler(comm, errhandler); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_set_errhandler =============== */ static void MPI_Comm_set_errhandler_fortran_wrapper(MPI_Fint *comm, MPI_Fint *errhandler, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_set_errhandler((MPI_Comm)(*comm), (MPI_Errhandler)(*errhandler)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Comm_set_errhandler(MPI_Comm_f2c(*comm), MPI_Errhandler_f2c(*errhandler)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_SET_ERRHANDLER(MPI_Fint *comm, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Comm_set_errhandler_fortran_wrapper(comm, errhandler, ierr); } _EXTERN_C_ void mpi_comm_set_errhandler(MPI_Fint *comm, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Comm_set_errhandler_fortran_wrapper(comm, errhandler, ierr); } _EXTERN_C_ void mpi_comm_set_errhandler_(MPI_Fint *comm, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Comm_set_errhandler_fortran_wrapper(comm, errhandler, ierr); } _EXTERN_C_ void mpi_comm_set_errhandler__(MPI_Fint *comm, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Comm_set_errhandler_fortran_wrapper(comm, errhandler, ierr); } /* ================= End Wrappers for MPI_Comm_set_errhandler ================= */ /* ================== C Wrappers for MPI_Comm_set_info ================== */ _EXTERN_C_ int PMPI_Comm_set_info(MPI_Comm comm, MPI_Info info); _EXTERN_C_ int MPI_Comm_set_info(MPI_Comm comm, MPI_Info info) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_set_info(comm, info); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_set_info =============== */ static void MPI_Comm_set_info_fortran_wrapper(MPI_Fint *comm, MPI_Fint *info, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_set_info((MPI_Comm)(*comm), (MPI_Info)(*info)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Comm_set_info(MPI_Comm_f2c(*comm), MPI_Info_f2c(*info)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_SET_INFO(MPI_Fint *comm, MPI_Fint *info, MPI_Fint *ierr) { MPI_Comm_set_info_fortran_wrapper(comm, info, ierr); } _EXTERN_C_ void mpi_comm_set_info(MPI_Fint *comm, MPI_Fint *info, MPI_Fint *ierr) { MPI_Comm_set_info_fortran_wrapper(comm, info, ierr); } _EXTERN_C_ void mpi_comm_set_info_(MPI_Fint *comm, MPI_Fint *info, MPI_Fint *ierr) { MPI_Comm_set_info_fortran_wrapper(comm, info, ierr); } _EXTERN_C_ void mpi_comm_set_info__(MPI_Fint *comm, MPI_Fint *info, MPI_Fint *ierr) { MPI_Comm_set_info_fortran_wrapper(comm, info, ierr); } /* ================= End Wrappers for MPI_Comm_set_info ================= */ /* ================== C Wrappers for MPI_Comm_set_name ================== */ _EXTERN_C_ int PMPI_Comm_set_name(MPI_Comm comm, const char *comm_name); _EXTERN_C_ int MPI_Comm_set_name(MPI_Comm comm, const char *comm_name) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_set_name(comm, comm_name); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_set_name =============== */ static void MPI_Comm_set_name_fortran_wrapper(MPI_Fint *comm, MPI_Fint *comm_name, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_set_name((MPI_Comm)(*comm), (const char*)comm_name); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Comm_set_name(MPI_Comm_f2c(*comm), (const char*)comm_name); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_SET_NAME(MPI_Fint *comm, MPI_Fint *comm_name, MPI_Fint *ierr) { MPI_Comm_set_name_fortran_wrapper(comm, comm_name, ierr); } _EXTERN_C_ void mpi_comm_set_name(MPI_Fint *comm, MPI_Fint *comm_name, MPI_Fint *ierr) { MPI_Comm_set_name_fortran_wrapper(comm, comm_name, ierr); } _EXTERN_C_ void mpi_comm_set_name_(MPI_Fint *comm, MPI_Fint *comm_name, MPI_Fint *ierr) { MPI_Comm_set_name_fortran_wrapper(comm, comm_name, ierr); } _EXTERN_C_ void mpi_comm_set_name__(MPI_Fint *comm, MPI_Fint *comm_name, MPI_Fint *ierr) { MPI_Comm_set_name_fortran_wrapper(comm, comm_name, ierr); } /* ================= End Wrappers for MPI_Comm_set_name ================= */ /* ================== C Wrappers for MPI_Comm_size ================== */ _EXTERN_C_ int PMPI_Comm_size(MPI_Comm comm, int *size); _EXTERN_C_ int MPI_Comm_size(MPI_Comm comm, int *size) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX if (isolation_mode && wrapper_enabled && 0 != comm_size) { *size = comm_size; _wrap_py_return_val = MPI_SUCCESS; } else { _wrap_py_return_val = PMPI_Comm_size(comm, size); } WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_size =============== */ static void MPI_Comm_size_fortran_wrapper(MPI_Fint *comm, MPI_Fint *size, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_size((MPI_Comm)(*comm), (int*)size); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Comm_size(MPI_Comm_f2c(*comm), (int*)size); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_SIZE(MPI_Fint *comm, MPI_Fint *size, MPI_Fint *ierr) { MPI_Comm_size_fortran_wrapper(comm, size, ierr); } _EXTERN_C_ void mpi_comm_size(MPI_Fint *comm, MPI_Fint *size, MPI_Fint *ierr) { MPI_Comm_size_fortran_wrapper(comm, size, ierr); } _EXTERN_C_ void mpi_comm_size_(MPI_Fint *comm, MPI_Fint *size, MPI_Fint *ierr) { MPI_Comm_size_fortran_wrapper(comm, size, ierr); } _EXTERN_C_ void mpi_comm_size__(MPI_Fint *comm, MPI_Fint *size, MPI_Fint *ierr) { MPI_Comm_size_fortran_wrapper(comm, size, ierr); } /* ================= End Wrappers for MPI_Comm_size ================= */ /* ================== C Wrappers for MPI_Comm_split ================== */ _EXTERN_C_ int PMPI_Comm_split(MPI_Comm comm, int color, int key, MPI_Comm *newcomm); _EXTERN_C_ int MPI_Comm_split(MPI_Comm comm, int color, int key, MPI_Comm *newcomm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_split(comm, color, key, newcomm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_split =============== */ static void MPI_Comm_split_fortran_wrapper(MPI_Fint *comm, MPI_Fint *color, MPI_Fint *key, MPI_Fint *newcomm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_split((MPI_Comm)(*comm), *color, *key, (MPI_Comm*)newcomm); #else /* MPI-2 safe call */ MPI_Comm temp_newcomm; temp_newcomm = MPI_Comm_f2c(*newcomm); _wrap_py_return_val = MPI_Comm_split(MPI_Comm_f2c(*comm), *color, *key, &temp_newcomm); *newcomm = MPI_Comm_c2f(temp_newcomm); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_SPLIT(MPI_Fint *comm, MPI_Fint *color, MPI_Fint *key, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_split_fortran_wrapper(comm, color, key, newcomm, ierr); } _EXTERN_C_ void mpi_comm_split(MPI_Fint *comm, MPI_Fint *color, MPI_Fint *key, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_split_fortran_wrapper(comm, color, key, newcomm, ierr); } _EXTERN_C_ void mpi_comm_split_(MPI_Fint *comm, MPI_Fint *color, MPI_Fint *key, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_split_fortran_wrapper(comm, color, key, newcomm, ierr); } _EXTERN_C_ void mpi_comm_split__(MPI_Fint *comm, MPI_Fint *color, MPI_Fint *key, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_split_fortran_wrapper(comm, color, key, newcomm, ierr); } /* ================= End Wrappers for MPI_Comm_split ================= */ /* ================== C Wrappers for MPI_Comm_split_type ================== */ _EXTERN_C_ int PMPI_Comm_split_type(MPI_Comm comm, int split_type, int key, MPI_Info info, MPI_Comm *newcomm); _EXTERN_C_ int MPI_Comm_split_type(MPI_Comm comm, int split_type, int key, MPI_Info info, MPI_Comm *newcomm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_split_type(comm, split_type, key, info, newcomm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_split_type =============== */ static void MPI_Comm_split_type_fortran_wrapper(MPI_Fint *comm, MPI_Fint *split_type, MPI_Fint *key, MPI_Fint *info, MPI_Fint *newcomm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_split_type((MPI_Comm)(*comm), *split_type, *key, (MPI_Info)(*info), (MPI_Comm*)newcomm); #else /* MPI-2 safe call */ MPI_Comm temp_newcomm; temp_newcomm = MPI_Comm_f2c(*newcomm); _wrap_py_return_val = MPI_Comm_split_type(MPI_Comm_f2c(*comm), *split_type, *key, MPI_Info_f2c(*info), &temp_newcomm); *newcomm = MPI_Comm_c2f(temp_newcomm); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_SPLIT_TYPE(MPI_Fint *comm, MPI_Fint *split_type, MPI_Fint *key, MPI_Fint *info, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_split_type_fortran_wrapper(comm, split_type, key, info, newcomm, ierr); } _EXTERN_C_ void mpi_comm_split_type(MPI_Fint *comm, MPI_Fint *split_type, MPI_Fint *key, MPI_Fint *info, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_split_type_fortran_wrapper(comm, split_type, key, info, newcomm, ierr); } _EXTERN_C_ void mpi_comm_split_type_(MPI_Fint *comm, MPI_Fint *split_type, MPI_Fint *key, MPI_Fint *info, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_split_type_fortran_wrapper(comm, split_type, key, info, newcomm, ierr); } _EXTERN_C_ void mpi_comm_split_type__(MPI_Fint *comm, MPI_Fint *split_type, MPI_Fint *key, MPI_Fint *info, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Comm_split_type_fortran_wrapper(comm, split_type, key, info, newcomm, ierr); } /* ================= End Wrappers for MPI_Comm_split_type ================= */ /* ================== C Wrappers for MPI_Comm_test_inter ================== */ _EXTERN_C_ int PMPI_Comm_test_inter(MPI_Comm comm, int *flag); _EXTERN_C_ int MPI_Comm_test_inter(MPI_Comm comm, int *flag) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Comm_test_inter(comm, flag); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Comm_test_inter =============== */ static void MPI_Comm_test_inter_fortran_wrapper(MPI_Fint *comm, MPI_Fint *flag, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Comm_test_inter((MPI_Comm)(*comm), (int*)flag); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Comm_test_inter(MPI_Comm_f2c(*comm), (int*)flag); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMM_TEST_INTER(MPI_Fint *comm, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Comm_test_inter_fortran_wrapper(comm, flag, ierr); } _EXTERN_C_ void mpi_comm_test_inter(MPI_Fint *comm, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Comm_test_inter_fortran_wrapper(comm, flag, ierr); } _EXTERN_C_ void mpi_comm_test_inter_(MPI_Fint *comm, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Comm_test_inter_fortran_wrapper(comm, flag, ierr); } _EXTERN_C_ void mpi_comm_test_inter__(MPI_Fint *comm, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Comm_test_inter_fortran_wrapper(comm, flag, ierr); } /* ================= End Wrappers for MPI_Comm_test_inter ================= */ /* ================== C Wrappers for MPI_Compare_and_swap ================== */ _EXTERN_C_ int PMPI_Compare_and_swap(const void *origin_addr, const void *compare_addr, void *result_addr, MPI_Datatype datatype, int target_rank, MPI_Aint target_disp, MPI_Win win); _EXTERN_C_ int MPI_Compare_and_swap(const void *origin_addr, const void *compare_addr, void *result_addr, MPI_Datatype datatype, int target_rank, MPI_Aint target_disp, MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Compare_and_swap(origin_addr, compare_addr, result_addr, datatype, target_rank, target_disp, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Compare_and_swap =============== */ static void MPI_Compare_and_swap_fortran_wrapper(MPI_Fint *origin_addr, MPI_Fint *compare_addr, MPI_Fint *result_addr, MPI_Fint *datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Compare_and_swap((const void*)origin_addr, (const void*)compare_addr, (void*)result_addr, (MPI_Datatype)(*datatype), *target_rank, *target_disp, (MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Compare_and_swap((const void*)origin_addr, (const void*)compare_addr, (void*)result_addr, MPI_Type_f2c(*datatype), *target_rank, *target_disp, MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_COMPARE_AND_SWAP(MPI_Fint *origin_addr, MPI_Fint *compare_addr, MPI_Fint *result_addr, MPI_Fint *datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *win, MPI_Fint *ierr) { MPI_Compare_and_swap_fortran_wrapper(origin_addr, compare_addr, result_addr, datatype, target_rank, target_disp, win, ierr); } _EXTERN_C_ void mpi_compare_and_swap(MPI_Fint *origin_addr, MPI_Fint *compare_addr, MPI_Fint *result_addr, MPI_Fint *datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *win, MPI_Fint *ierr) { MPI_Compare_and_swap_fortran_wrapper(origin_addr, compare_addr, result_addr, datatype, target_rank, target_disp, win, ierr); } _EXTERN_C_ void mpi_compare_and_swap_(MPI_Fint *origin_addr, MPI_Fint *compare_addr, MPI_Fint *result_addr, MPI_Fint *datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *win, MPI_Fint *ierr) { MPI_Compare_and_swap_fortran_wrapper(origin_addr, compare_addr, result_addr, datatype, target_rank, target_disp, win, ierr); } _EXTERN_C_ void mpi_compare_and_swap__(MPI_Fint *origin_addr, MPI_Fint *compare_addr, MPI_Fint *result_addr, MPI_Fint *datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *win, MPI_Fint *ierr) { MPI_Compare_and_swap_fortran_wrapper(origin_addr, compare_addr, result_addr, datatype, target_rank, target_disp, win, ierr); } /* ================= End Wrappers for MPI_Compare_and_swap ================= */ /* ================== C Wrappers for MPI_Dims_create ================== */ _EXTERN_C_ int PMPI_Dims_create(int nnodes, int ndims, int dims[]); _EXTERN_C_ int MPI_Dims_create(int nnodes, int ndims, int dims[]) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Dims_create(nnodes, ndims, dims); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Dims_create =============== */ static void MPI_Dims_create_fortran_wrapper(MPI_Fint *nnodes, MPI_Fint *ndims, MPI_Fint dims[], MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Dims_create(*nnodes, *ndims, (int*)dims); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_DIMS_CREATE(MPI_Fint *nnodes, MPI_Fint *ndims, MPI_Fint dims[], MPI_Fint *ierr) { MPI_Dims_create_fortran_wrapper(nnodes, ndims, dims, ierr); } _EXTERN_C_ void mpi_dims_create(MPI_Fint *nnodes, MPI_Fint *ndims, MPI_Fint dims[], MPI_Fint *ierr) { MPI_Dims_create_fortran_wrapper(nnodes, ndims, dims, ierr); } _EXTERN_C_ void mpi_dims_create_(MPI_Fint *nnodes, MPI_Fint *ndims, MPI_Fint dims[], MPI_Fint *ierr) { MPI_Dims_create_fortran_wrapper(nnodes, ndims, dims, ierr); } _EXTERN_C_ void mpi_dims_create__(MPI_Fint *nnodes, MPI_Fint *ndims, MPI_Fint dims[], MPI_Fint *ierr) { MPI_Dims_create_fortran_wrapper(nnodes, ndims, dims, ierr); } /* ================= End Wrappers for MPI_Dims_create ================= */ /* ================== C Wrappers for MPI_Dist_graph_create ================== */ _EXTERN_C_ int PMPI_Dist_graph_create(MPI_Comm comm_old, int n, const int nodes[], const int degrees[], const int targets[], const int weights[], MPI_Info info, int reorder, MPI_Comm *newcomm); _EXTERN_C_ int MPI_Dist_graph_create(MPI_Comm comm_old, int n, const int nodes[], const int degrees[], const int targets[], const int weights[], MPI_Info info, int reorder, MPI_Comm *newcomm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Dist_graph_create(comm_old, n, nodes, degrees, targets, weights, info, reorder, newcomm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Dist_graph_create =============== */ static void MPI_Dist_graph_create_fortran_wrapper(MPI_Fint *comm_old, MPI_Fint *n, MPI_Fint nodes[], MPI_Fint degrees[], MPI_Fint targets[], MPI_Fint weights[], MPI_Fint *info, MPI_Fint *reorder, MPI_Fint *newcomm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Dist_graph_create((MPI_Comm)(*comm_old), *n, (const int*)nodes, (const int*)degrees, (const int*)targets, (const int*)weights, (MPI_Info)(*info), *reorder, (MPI_Comm*)newcomm); #else /* MPI-2 safe call */ MPI_Comm temp_newcomm; temp_newcomm = MPI_Comm_f2c(*newcomm); _wrap_py_return_val = MPI_Dist_graph_create(MPI_Comm_f2c(*comm_old), *n, (const int*)nodes, (const int*)degrees, (const int*)targets, (const int*)weights, MPI_Info_f2c(*info), *reorder, &temp_newcomm); *newcomm = MPI_Comm_c2f(temp_newcomm); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_DIST_GRAPH_CREATE(MPI_Fint *comm_old, MPI_Fint *n, MPI_Fint nodes[], MPI_Fint degrees[], MPI_Fint targets[], MPI_Fint weights[], MPI_Fint *info, MPI_Fint *reorder, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Dist_graph_create_fortran_wrapper(comm_old, n, nodes, degrees, targets, weights, info, reorder, newcomm, ierr); } _EXTERN_C_ void mpi_dist_graph_create(MPI_Fint *comm_old, MPI_Fint *n, MPI_Fint nodes[], MPI_Fint degrees[], MPI_Fint targets[], MPI_Fint weights[], MPI_Fint *info, MPI_Fint *reorder, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Dist_graph_create_fortran_wrapper(comm_old, n, nodes, degrees, targets, weights, info, reorder, newcomm, ierr); } _EXTERN_C_ void mpi_dist_graph_create_(MPI_Fint *comm_old, MPI_Fint *n, MPI_Fint nodes[], MPI_Fint degrees[], MPI_Fint targets[], MPI_Fint weights[], MPI_Fint *info, MPI_Fint *reorder, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Dist_graph_create_fortran_wrapper(comm_old, n, nodes, degrees, targets, weights, info, reorder, newcomm, ierr); } _EXTERN_C_ void mpi_dist_graph_create__(MPI_Fint *comm_old, MPI_Fint *n, MPI_Fint nodes[], MPI_Fint degrees[], MPI_Fint targets[], MPI_Fint weights[], MPI_Fint *info, MPI_Fint *reorder, MPI_Fint *newcomm, MPI_Fint *ierr) { MPI_Dist_graph_create_fortran_wrapper(comm_old, n, nodes, degrees, targets, weights, info, reorder, newcomm, ierr); } /* ================= End Wrappers for MPI_Dist_graph_create ================= */ /* ================== C Wrappers for MPI_Dist_graph_create_adjacent ================== */ _EXTERN_C_ int PMPI_Dist_graph_create_adjacent(MPI_Comm comm_old, int indegree, const int sources[], const int sourceweights[], int outdegree, const int destinations[], const int destweights[], MPI_Info info, int reorder, MPI_Comm *comm_dist_graph); _EXTERN_C_ int MPI_Dist_graph_create_adjacent(MPI_Comm comm_old, int indegree, const int sources[], const int sourceweights[], int outdegree, const int destinations[], const int destweights[], MPI_Info info, int reorder, MPI_Comm *comm_dist_graph) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Dist_graph_create_adjacent(comm_old, indegree, sources, sourceweights, outdegree, destinations, destweights, info, reorder, comm_dist_graph); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Dist_graph_create_adjacent =============== */ static void MPI_Dist_graph_create_adjacent_fortran_wrapper(MPI_Fint *comm_old, MPI_Fint *indegree, MPI_Fint sources[], MPI_Fint sourceweights[], MPI_Fint *outdegree, MPI_Fint destinations[], MPI_Fint destweights[], MPI_Fint *info, MPI_Fint *reorder, MPI_Fint *comm_dist_graph, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Dist_graph_create_adjacent((MPI_Comm)(*comm_old), *indegree, (const int*)sources, (const int*)sourceweights, *outdegree, (const int*)destinations, (const int*)destweights, (MPI_Info)(*info), *reorder, (MPI_Comm*)comm_dist_graph); #else /* MPI-2 safe call */ MPI_Comm temp_comm_dist_graph; temp_comm_dist_graph = MPI_Comm_f2c(*comm_dist_graph); _wrap_py_return_val = MPI_Dist_graph_create_adjacent(MPI_Comm_f2c(*comm_old), *indegree, (const int*)sources, (const int*)sourceweights, *outdegree, (const int*)destinations, (const int*)destweights, MPI_Info_f2c(*info), *reorder, &temp_comm_dist_graph); *comm_dist_graph = MPI_Comm_c2f(temp_comm_dist_graph); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_DIST_GRAPH_CREATE_ADJACENT(MPI_Fint *comm_old, MPI_Fint *indegree, MPI_Fint sources[], MPI_Fint sourceweights[], MPI_Fint *outdegree, MPI_Fint destinations[], MPI_Fint destweights[], MPI_Fint *info, MPI_Fint *reorder, MPI_Fint *comm_dist_graph, MPI_Fint *ierr) { MPI_Dist_graph_create_adjacent_fortran_wrapper(comm_old, indegree, sources, sourceweights, outdegree, destinations, destweights, info, reorder, comm_dist_graph, ierr); } _EXTERN_C_ void mpi_dist_graph_create_adjacent(MPI_Fint *comm_old, MPI_Fint *indegree, MPI_Fint sources[], MPI_Fint sourceweights[], MPI_Fint *outdegree, MPI_Fint destinations[], MPI_Fint destweights[], MPI_Fint *info, MPI_Fint *reorder, MPI_Fint *comm_dist_graph, MPI_Fint *ierr) { MPI_Dist_graph_create_adjacent_fortran_wrapper(comm_old, indegree, sources, sourceweights, outdegree, destinations, destweights, info, reorder, comm_dist_graph, ierr); } _EXTERN_C_ void mpi_dist_graph_create_adjacent_(MPI_Fint *comm_old, MPI_Fint *indegree, MPI_Fint sources[], MPI_Fint sourceweights[], MPI_Fint *outdegree, MPI_Fint destinations[], MPI_Fint destweights[], MPI_Fint *info, MPI_Fint *reorder, MPI_Fint *comm_dist_graph, MPI_Fint *ierr) { MPI_Dist_graph_create_adjacent_fortran_wrapper(comm_old, indegree, sources, sourceweights, outdegree, destinations, destweights, info, reorder, comm_dist_graph, ierr); } _EXTERN_C_ void mpi_dist_graph_create_adjacent__(MPI_Fint *comm_old, MPI_Fint *indegree, MPI_Fint sources[], MPI_Fint sourceweights[], MPI_Fint *outdegree, MPI_Fint destinations[], MPI_Fint destweights[], MPI_Fint *info, MPI_Fint *reorder, MPI_Fint *comm_dist_graph, MPI_Fint *ierr) { MPI_Dist_graph_create_adjacent_fortran_wrapper(comm_old, indegree, sources, sourceweights, outdegree, destinations, destweights, info, reorder, comm_dist_graph, ierr); } /* ================= End Wrappers for MPI_Dist_graph_create_adjacent ================= */ /* ================== C Wrappers for MPI_Dist_graph_neighbors ================== */ _EXTERN_C_ int PMPI_Dist_graph_neighbors(MPI_Comm comm, int maxindegree, int sources[], int sourceweights[], int maxoutdegree, int destinations[], int destweights[]); _EXTERN_C_ int MPI_Dist_graph_neighbors(MPI_Comm comm, int maxindegree, int sources[], int sourceweights[], int maxoutdegree, int destinations[], int destweights[]) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Dist_graph_neighbors(comm, maxindegree, sources, sourceweights, maxoutdegree, destinations, destweights); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Dist_graph_neighbors =============== */ static void MPI_Dist_graph_neighbors_fortran_wrapper(MPI_Fint *comm, MPI_Fint *maxindegree, MPI_Fint sources[], MPI_Fint sourceweights[], MPI_Fint *maxoutdegree, MPI_Fint destinations[], MPI_Fint destweights[], MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Dist_graph_neighbors((MPI_Comm)(*comm), *maxindegree, (int*)sources, (int*)sourceweights, *maxoutdegree, (int*)destinations, (int*)destweights); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Dist_graph_neighbors(MPI_Comm_f2c(*comm), *maxindegree, (int*)sources, (int*)sourceweights, *maxoutdegree, (int*)destinations, (int*)destweights); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_DIST_GRAPH_NEIGHBORS(MPI_Fint *comm, MPI_Fint *maxindegree, MPI_Fint sources[], MPI_Fint sourceweights[], MPI_Fint *maxoutdegree, MPI_Fint destinations[], MPI_Fint destweights[], MPI_Fint *ierr) { MPI_Dist_graph_neighbors_fortran_wrapper(comm, maxindegree, sources, sourceweights, maxoutdegree, destinations, destweights, ierr); } _EXTERN_C_ void mpi_dist_graph_neighbors(MPI_Fint *comm, MPI_Fint *maxindegree, MPI_Fint sources[], MPI_Fint sourceweights[], MPI_Fint *maxoutdegree, MPI_Fint destinations[], MPI_Fint destweights[], MPI_Fint *ierr) { MPI_Dist_graph_neighbors_fortran_wrapper(comm, maxindegree, sources, sourceweights, maxoutdegree, destinations, destweights, ierr); } _EXTERN_C_ void mpi_dist_graph_neighbors_(MPI_Fint *comm, MPI_Fint *maxindegree, MPI_Fint sources[], MPI_Fint sourceweights[], MPI_Fint *maxoutdegree, MPI_Fint destinations[], MPI_Fint destweights[], MPI_Fint *ierr) { MPI_Dist_graph_neighbors_fortran_wrapper(comm, maxindegree, sources, sourceweights, maxoutdegree, destinations, destweights, ierr); } _EXTERN_C_ void mpi_dist_graph_neighbors__(MPI_Fint *comm, MPI_Fint *maxindegree, MPI_Fint sources[], MPI_Fint sourceweights[], MPI_Fint *maxoutdegree, MPI_Fint destinations[], MPI_Fint destweights[], MPI_Fint *ierr) { MPI_Dist_graph_neighbors_fortran_wrapper(comm, maxindegree, sources, sourceweights, maxoutdegree, destinations, destweights, ierr); } /* ================= End Wrappers for MPI_Dist_graph_neighbors ================= */ /* ================== C Wrappers for MPI_Dist_graph_neighbors_count ================== */ _EXTERN_C_ int PMPI_Dist_graph_neighbors_count(MPI_Comm comm, int *inneighbors, int *outneighbors, int *weighted); _EXTERN_C_ int MPI_Dist_graph_neighbors_count(MPI_Comm comm, int *inneighbors, int *outneighbors, int *weighted) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Dist_graph_neighbors_count(comm, inneighbors, outneighbors, weighted); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Dist_graph_neighbors_count =============== */ static void MPI_Dist_graph_neighbors_count_fortran_wrapper(MPI_Fint *comm, MPI_Fint *inneighbors, MPI_Fint *outneighbors, MPI_Fint *weighted, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Dist_graph_neighbors_count((MPI_Comm)(*comm), (int*)inneighbors, (int*)outneighbors, (int*)weighted); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Dist_graph_neighbors_count(MPI_Comm_f2c(*comm), (int*)inneighbors, (int*)outneighbors, (int*)weighted); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_DIST_GRAPH_NEIGHBORS_COUNT(MPI_Fint *comm, MPI_Fint *inneighbors, MPI_Fint *outneighbors, MPI_Fint *weighted, MPI_Fint *ierr) { MPI_Dist_graph_neighbors_count_fortran_wrapper(comm, inneighbors, outneighbors, weighted, ierr); } _EXTERN_C_ void mpi_dist_graph_neighbors_count(MPI_Fint *comm, MPI_Fint *inneighbors, MPI_Fint *outneighbors, MPI_Fint *weighted, MPI_Fint *ierr) { MPI_Dist_graph_neighbors_count_fortran_wrapper(comm, inneighbors, outneighbors, weighted, ierr); } _EXTERN_C_ void mpi_dist_graph_neighbors_count_(MPI_Fint *comm, MPI_Fint *inneighbors, MPI_Fint *outneighbors, MPI_Fint *weighted, MPI_Fint *ierr) { MPI_Dist_graph_neighbors_count_fortran_wrapper(comm, inneighbors, outneighbors, weighted, ierr); } _EXTERN_C_ void mpi_dist_graph_neighbors_count__(MPI_Fint *comm, MPI_Fint *inneighbors, MPI_Fint *outneighbors, MPI_Fint *weighted, MPI_Fint *ierr) { MPI_Dist_graph_neighbors_count_fortran_wrapper(comm, inneighbors, outneighbors, weighted, ierr); } /* ================= End Wrappers for MPI_Dist_graph_neighbors_count ================= */ /* ================== C Wrappers for MPI_Errhandler_create ================== */ _EXTERN_C_ int PMPI_Errhandler_create(MPI_Handler_function *function, MPI_Errhandler *errhandler); _EXTERN_C_ int MPI_Errhandler_create(MPI_Handler_function *function, MPI_Errhandler *errhandler) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Errhandler_create(function, errhandler); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Errhandler_create =============== */ static void MPI_Errhandler_create_fortran_wrapper(MPI_Handler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { int _wrap_py_return_val = 0; WRAP_MPI_CALL_PREFIX #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Errhandler_create((MPI_Handler_function*)function, (MPI_Errhandler*)errhandler); #else /* MPI-2 safe call */ MPI_Errhandler temp_errhandler; temp_errhandler = MPI_Errhandler_f2c(*errhandler); _wrap_py_return_val = MPI_Errhandler_create((MPI_Handler_function*)function, &temp_errhandler); *errhandler = MPI_Errhandler_c2f(temp_errhandler); #endif /* MPICH test */ WRAP_MPI_CALL_POSTFIX *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ERRHANDLER_CREATE(MPI_Handler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Errhandler_create_fortran_wrapper(function, errhandler, ierr); } _EXTERN_C_ void mpi_errhandler_create(MPI_Handler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Errhandler_create_fortran_wrapper(function, errhandler, ierr); } _EXTERN_C_ void mpi_errhandler_create_(MPI_Handler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Errhandler_create_fortran_wrapper(function, errhandler, ierr); } _EXTERN_C_ void mpi_errhandler_create__(MPI_Handler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Errhandler_create_fortran_wrapper(function, errhandler, ierr); } /* ================= End Wrappers for MPI_Errhandler_create ================= */ /* ================== C Wrappers for MPI_Errhandler_free ================== */ _EXTERN_C_ int PMPI_Errhandler_free(MPI_Errhandler *errhandler); _EXTERN_C_ int MPI_Errhandler_free(MPI_Errhandler *errhandler) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Errhandler_free(errhandler); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Errhandler_free =============== */ static void MPI_Errhandler_free_fortran_wrapper(MPI_Fint *errhandler, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Errhandler_free((MPI_Errhandler*)errhandler); #else /* MPI-2 safe call */ MPI_Errhandler temp_errhandler; temp_errhandler = MPI_Errhandler_f2c(*errhandler); _wrap_py_return_val = MPI_Errhandler_free(&temp_errhandler); *errhandler = MPI_Errhandler_c2f(temp_errhandler); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ERRHANDLER_FREE(MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Errhandler_free_fortran_wrapper(errhandler, ierr); } _EXTERN_C_ void mpi_errhandler_free(MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Errhandler_free_fortran_wrapper(errhandler, ierr); } _EXTERN_C_ void mpi_errhandler_free_(MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Errhandler_free_fortran_wrapper(errhandler, ierr); } _EXTERN_C_ void mpi_errhandler_free__(MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Errhandler_free_fortran_wrapper(errhandler, ierr); } /* ================= End Wrappers for MPI_Errhandler_free ================= */ /* ================== C Wrappers for MPI_Errhandler_get ================== */ _EXTERN_C_ int PMPI_Errhandler_get(MPI_Comm comm, MPI_Errhandler *errhandler); _EXTERN_C_ int MPI_Errhandler_get(MPI_Comm comm, MPI_Errhandler *errhandler) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Errhandler_get(comm, errhandler); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Errhandler_get =============== */ static void MPI_Errhandler_get_fortran_wrapper(MPI_Fint *comm, MPI_Fint *errhandler, MPI_Fint *ierr) { int _wrap_py_return_val = 0; WRAP_MPI_CALL_PREFIX #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Errhandler_get((MPI_Comm)(*comm), (MPI_Errhandler*)errhandler); #else /* MPI-2 safe call */ MPI_Errhandler temp_errhandler; temp_errhandler = MPI_Errhandler_f2c(*errhandler); _wrap_py_return_val = MPI_Errhandler_get(MPI_Comm_f2c(*comm), &temp_errhandler); *errhandler = MPI_Errhandler_c2f(temp_errhandler); #endif /* MPICH test */ WRAP_MPI_CALL_POSTFIX *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ERRHANDLER_GET(MPI_Fint *comm, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Errhandler_get_fortran_wrapper(comm, errhandler, ierr); } _EXTERN_C_ void mpi_errhandler_get(MPI_Fint *comm, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Errhandler_get_fortran_wrapper(comm, errhandler, ierr); } _EXTERN_C_ void mpi_errhandler_get_(MPI_Fint *comm, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Errhandler_get_fortran_wrapper(comm, errhandler, ierr); } _EXTERN_C_ void mpi_errhandler_get__(MPI_Fint *comm, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Errhandler_get_fortran_wrapper(comm, errhandler, ierr); } /* ================= End Wrappers for MPI_Errhandler_get ================= */ /* ================== C Wrappers for MPI_Errhandler_set ================== */ _EXTERN_C_ int PMPI_Errhandler_set(MPI_Comm comm, MPI_Errhandler errhandler); _EXTERN_C_ int MPI_Errhandler_set(MPI_Comm comm, MPI_Errhandler errhandler) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Errhandler_set(comm, errhandler); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Errhandler_set =============== */ static void MPI_Errhandler_set_fortran_wrapper(MPI_Fint *comm, MPI_Fint *errhandler, MPI_Fint *ierr) { int _wrap_py_return_val = 0; WRAP_MPI_CALL_PREFIX #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Errhandler_set((MPI_Comm)(*comm), (MPI_Errhandler)(*errhandler)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Errhandler_set(MPI_Comm_f2c(*comm), MPI_Errhandler_f2c(*errhandler)); #endif /* MPICH test */ WRAP_MPI_CALL_POSTFIX *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ERRHANDLER_SET(MPI_Fint *comm, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Errhandler_set_fortran_wrapper(comm, errhandler, ierr); } _EXTERN_C_ void mpi_errhandler_set(MPI_Fint *comm, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Errhandler_set_fortran_wrapper(comm, errhandler, ierr); } _EXTERN_C_ void mpi_errhandler_set_(MPI_Fint *comm, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Errhandler_set_fortran_wrapper(comm, errhandler, ierr); } _EXTERN_C_ void mpi_errhandler_set__(MPI_Fint *comm, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Errhandler_set_fortran_wrapper(comm, errhandler, ierr); } /* ================= End Wrappers for MPI_Errhandler_set ================= */ /* ================== C Wrappers for MPI_Error_class ================== */ _EXTERN_C_ int PMPI_Error_class(int errorcode, int *errorclass); _EXTERN_C_ int MPI_Error_class(int errorcode, int *errorclass) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Error_class(errorcode, errorclass); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Error_class =============== */ static void MPI_Error_class_fortran_wrapper(MPI_Fint *errorcode, MPI_Fint *errorclass, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Error_class(*errorcode, (int*)errorclass); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ERROR_CLASS(MPI_Fint *errorcode, MPI_Fint *errorclass, MPI_Fint *ierr) { MPI_Error_class_fortran_wrapper(errorcode, errorclass, ierr); } _EXTERN_C_ void mpi_error_class(MPI_Fint *errorcode, MPI_Fint *errorclass, MPI_Fint *ierr) { MPI_Error_class_fortran_wrapper(errorcode, errorclass, ierr); } _EXTERN_C_ void mpi_error_class_(MPI_Fint *errorcode, MPI_Fint *errorclass, MPI_Fint *ierr) { MPI_Error_class_fortran_wrapper(errorcode, errorclass, ierr); } _EXTERN_C_ void mpi_error_class__(MPI_Fint *errorcode, MPI_Fint *errorclass, MPI_Fint *ierr) { MPI_Error_class_fortran_wrapper(errorcode, errorclass, ierr); } /* ================= End Wrappers for MPI_Error_class ================= */ /* ================== C Wrappers for MPI_Error_string ================== */ _EXTERN_C_ int PMPI_Error_string(int errorcode, char *string, int *resultlen); _EXTERN_C_ int MPI_Error_string(int errorcode, char *string, int *resultlen) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Error_string(errorcode, string, resultlen); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Error_string =============== */ static void MPI_Error_string_fortran_wrapper(MPI_Fint *errorcode, MPI_Fint *string, MPI_Fint *resultlen, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Error_string(*errorcode, (char*)string, (int*)resultlen); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ERROR_STRING(MPI_Fint *errorcode, MPI_Fint *string, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Error_string_fortran_wrapper(errorcode, string, resultlen, ierr); } _EXTERN_C_ void mpi_error_string(MPI_Fint *errorcode, MPI_Fint *string, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Error_string_fortran_wrapper(errorcode, string, resultlen, ierr); } _EXTERN_C_ void mpi_error_string_(MPI_Fint *errorcode, MPI_Fint *string, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Error_string_fortran_wrapper(errorcode, string, resultlen, ierr); } _EXTERN_C_ void mpi_error_string__(MPI_Fint *errorcode, MPI_Fint *string, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Error_string_fortran_wrapper(errorcode, string, resultlen, ierr); } /* ================= End Wrappers for MPI_Error_string ================= */ /* ================== C Wrappers for MPI_Exscan ================== */ _EXTERN_C_ int PMPI_Exscan(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm); _EXTERN_C_ int MPI_Exscan(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Exscan(sendbuf, recvbuf, count, datatype, op, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Exscan =============== */ static void MPI_Exscan_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Exscan((const void*)sendbuf, (void*)recvbuf, *count, (MPI_Datatype)(*datatype), (MPI_Op)(*op), (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Exscan((const void*)sendbuf, (void*)recvbuf, *count, MPI_Type_f2c(*datatype), MPI_Op_f2c(*op), MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_EXSCAN(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Exscan_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, ierr); } _EXTERN_C_ void mpi_exscan(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Exscan_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, ierr); } _EXTERN_C_ void mpi_exscan_(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Exscan_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, ierr); } _EXTERN_C_ void mpi_exscan__(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Exscan_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, ierr); } /* ================= End Wrappers for MPI_Exscan ================= */ /* ================== C Wrappers for MPI_Fetch_and_op ================== */ _EXTERN_C_ int PMPI_Fetch_and_op(const void *origin_addr, void *result_addr, MPI_Datatype datatype, int target_rank, MPI_Aint target_disp, MPI_Op op, MPI_Win win); _EXTERN_C_ int MPI_Fetch_and_op(const void *origin_addr, void *result_addr, MPI_Datatype datatype, int target_rank, MPI_Aint target_disp, MPI_Op op, MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Fetch_and_op(origin_addr, result_addr, datatype, target_rank, target_disp, op, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Fetch_and_op =============== */ static void MPI_Fetch_and_op_fortran_wrapper(MPI_Fint *origin_addr, MPI_Fint *result_addr, MPI_Fint *datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *op, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Fetch_and_op((const void*)origin_addr, (void*)result_addr, (MPI_Datatype)(*datatype), *target_rank, *target_disp, (MPI_Op)(*op), (MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Fetch_and_op((const void*)origin_addr, (void*)result_addr, MPI_Type_f2c(*datatype), *target_rank, *target_disp, MPI_Op_f2c(*op), MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FETCH_AND_OP(MPI_Fint *origin_addr, MPI_Fint *result_addr, MPI_Fint *datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *op, MPI_Fint *win, MPI_Fint *ierr) { MPI_Fetch_and_op_fortran_wrapper(origin_addr, result_addr, datatype, target_rank, target_disp, op, win, ierr); } _EXTERN_C_ void mpi_fetch_and_op(MPI_Fint *origin_addr, MPI_Fint *result_addr, MPI_Fint *datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *op, MPI_Fint *win, MPI_Fint *ierr) { MPI_Fetch_and_op_fortran_wrapper(origin_addr, result_addr, datatype, target_rank, target_disp, op, win, ierr); } _EXTERN_C_ void mpi_fetch_and_op_(MPI_Fint *origin_addr, MPI_Fint *result_addr, MPI_Fint *datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *op, MPI_Fint *win, MPI_Fint *ierr) { MPI_Fetch_and_op_fortran_wrapper(origin_addr, result_addr, datatype, target_rank, target_disp, op, win, ierr); } _EXTERN_C_ void mpi_fetch_and_op__(MPI_Fint *origin_addr, MPI_Fint *result_addr, MPI_Fint *datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *op, MPI_Fint *win, MPI_Fint *ierr) { MPI_Fetch_and_op_fortran_wrapper(origin_addr, result_addr, datatype, target_rank, target_disp, op, win, ierr); } /* ================= End Wrappers for MPI_Fetch_and_op ================= */ /* ================== C Wrappers for MPI_File_call_errhandler ================== */ _EXTERN_C_ int PMPI_File_call_errhandler(MPI_File fh, int errorcode); _EXTERN_C_ int MPI_File_call_errhandler(MPI_File fh, int errorcode) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_call_errhandler(fh, errorcode); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_call_errhandler =============== */ static void MPI_File_call_errhandler_fortran_wrapper(MPI_Fint *fh, MPI_Fint *errorcode, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_call_errhandler((MPI_File)(*fh), *errorcode); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_call_errhandler(MPI_File_f2c(*fh), *errorcode); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_CALL_ERRHANDLER(MPI_Fint *fh, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_File_call_errhandler_fortran_wrapper(fh, errorcode, ierr); } _EXTERN_C_ void mpi_file_call_errhandler(MPI_Fint *fh, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_File_call_errhandler_fortran_wrapper(fh, errorcode, ierr); } _EXTERN_C_ void mpi_file_call_errhandler_(MPI_Fint *fh, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_File_call_errhandler_fortran_wrapper(fh, errorcode, ierr); } _EXTERN_C_ void mpi_file_call_errhandler__(MPI_Fint *fh, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_File_call_errhandler_fortran_wrapper(fh, errorcode, ierr); } /* ================= End Wrappers for MPI_File_call_errhandler ================= */ /* ================== C Wrappers for MPI_File_close ================== */ _EXTERN_C_ int PMPI_File_close(MPI_File *fh); _EXTERN_C_ int MPI_File_close(MPI_File *fh) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_close(fh); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_close =============== */ static void MPI_File_close_fortran_wrapper(MPI_Fint *fh, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_close((MPI_File*)fh); #else /* MPI-2 safe call */ MPI_File temp_fh; temp_fh = MPI_File_f2c(*fh); _wrap_py_return_val = MPI_File_close(&temp_fh); *fh = MPI_File_c2f(temp_fh); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_CLOSE(MPI_Fint *fh, MPI_Fint *ierr) { MPI_File_close_fortran_wrapper(fh, ierr); } _EXTERN_C_ void mpi_file_close(MPI_Fint *fh, MPI_Fint *ierr) { MPI_File_close_fortran_wrapper(fh, ierr); } _EXTERN_C_ void mpi_file_close_(MPI_Fint *fh, MPI_Fint *ierr) { MPI_File_close_fortran_wrapper(fh, ierr); } _EXTERN_C_ void mpi_file_close__(MPI_Fint *fh, MPI_Fint *ierr) { MPI_File_close_fortran_wrapper(fh, ierr); } /* ================= End Wrappers for MPI_File_close ================= */ /* ================== C Wrappers for MPI_File_create_errhandler ================== */ _EXTERN_C_ int PMPI_File_create_errhandler(MPI_File_errhandler_function *function, MPI_Errhandler *errhandler); _EXTERN_C_ int MPI_File_create_errhandler(MPI_File_errhandler_function *function, MPI_Errhandler *errhandler) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_create_errhandler(function, errhandler); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_create_errhandler =============== */ static void MPI_File_create_errhandler_fortran_wrapper(MPI_File_errhandler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_create_errhandler((MPI_File_errhandler_function*)function, (MPI_Errhandler*)errhandler); #else /* MPI-2 safe call */ MPI_Errhandler temp_errhandler; temp_errhandler = MPI_Errhandler_f2c(*errhandler); _wrap_py_return_val = MPI_File_create_errhandler((MPI_File_errhandler_function*)function, &temp_errhandler); *errhandler = MPI_Errhandler_c2f(temp_errhandler); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_CREATE_ERRHANDLER(MPI_File_errhandler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_File_create_errhandler_fortran_wrapper(function, errhandler, ierr); } _EXTERN_C_ void mpi_file_create_errhandler(MPI_File_errhandler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_File_create_errhandler_fortran_wrapper(function, errhandler, ierr); } _EXTERN_C_ void mpi_file_create_errhandler_(MPI_File_errhandler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_File_create_errhandler_fortran_wrapper(function, errhandler, ierr); } _EXTERN_C_ void mpi_file_create_errhandler__(MPI_File_errhandler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_File_create_errhandler_fortran_wrapper(function, errhandler, ierr); } /* ================= End Wrappers for MPI_File_create_errhandler ================= */ /* ================== C Wrappers for MPI_File_delete ================== */ _EXTERN_C_ int PMPI_File_delete(const char *filename, MPI_Info info); _EXTERN_C_ int MPI_File_delete(const char *filename, MPI_Info info) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_delete(filename, info); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_delete =============== */ static void MPI_File_delete_fortran_wrapper(MPI_Fint *filename, MPI_Fint *info, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_delete((const char*)filename, (MPI_Info)(*info)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_delete((const char*)filename, MPI_Info_f2c(*info)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_DELETE(MPI_Fint *filename, MPI_Fint *info, MPI_Fint *ierr) { MPI_File_delete_fortran_wrapper(filename, info, ierr); } _EXTERN_C_ void mpi_file_delete(MPI_Fint *filename, MPI_Fint *info, MPI_Fint *ierr) { MPI_File_delete_fortran_wrapper(filename, info, ierr); } _EXTERN_C_ void mpi_file_delete_(MPI_Fint *filename, MPI_Fint *info, MPI_Fint *ierr) { MPI_File_delete_fortran_wrapper(filename, info, ierr); } _EXTERN_C_ void mpi_file_delete__(MPI_Fint *filename, MPI_Fint *info, MPI_Fint *ierr) { MPI_File_delete_fortran_wrapper(filename, info, ierr); } /* ================= End Wrappers for MPI_File_delete ================= */ /* ================== C Wrappers for MPI_File_get_amode ================== */ _EXTERN_C_ int PMPI_File_get_amode(MPI_File fh, int *amode); _EXTERN_C_ int MPI_File_get_amode(MPI_File fh, int *amode) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_get_amode(fh, amode); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_get_amode =============== */ static void MPI_File_get_amode_fortran_wrapper(MPI_Fint *fh, MPI_Fint *amode, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_get_amode((MPI_File)(*fh), (int*)amode); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_get_amode(MPI_File_f2c(*fh), (int*)amode); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_GET_AMODE(MPI_Fint *fh, MPI_Fint *amode, MPI_Fint *ierr) { MPI_File_get_amode_fortran_wrapper(fh, amode, ierr); } _EXTERN_C_ void mpi_file_get_amode(MPI_Fint *fh, MPI_Fint *amode, MPI_Fint *ierr) { MPI_File_get_amode_fortran_wrapper(fh, amode, ierr); } _EXTERN_C_ void mpi_file_get_amode_(MPI_Fint *fh, MPI_Fint *amode, MPI_Fint *ierr) { MPI_File_get_amode_fortran_wrapper(fh, amode, ierr); } _EXTERN_C_ void mpi_file_get_amode__(MPI_Fint *fh, MPI_Fint *amode, MPI_Fint *ierr) { MPI_File_get_amode_fortran_wrapper(fh, amode, ierr); } /* ================= End Wrappers for MPI_File_get_amode ================= */ /* ================== C Wrappers for MPI_File_get_atomicity ================== */ _EXTERN_C_ int PMPI_File_get_atomicity(MPI_File fh, int *flag); _EXTERN_C_ int MPI_File_get_atomicity(MPI_File fh, int *flag) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_get_atomicity(fh, flag); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_get_atomicity =============== */ static void MPI_File_get_atomicity_fortran_wrapper(MPI_Fint *fh, MPI_Fint *flag, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_get_atomicity((MPI_File)(*fh), (int*)flag); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_get_atomicity(MPI_File_f2c(*fh), (int*)flag); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_GET_ATOMICITY(MPI_Fint *fh, MPI_Fint *flag, MPI_Fint *ierr) { MPI_File_get_atomicity_fortran_wrapper(fh, flag, ierr); } _EXTERN_C_ void mpi_file_get_atomicity(MPI_Fint *fh, MPI_Fint *flag, MPI_Fint *ierr) { MPI_File_get_atomicity_fortran_wrapper(fh, flag, ierr); } _EXTERN_C_ void mpi_file_get_atomicity_(MPI_Fint *fh, MPI_Fint *flag, MPI_Fint *ierr) { MPI_File_get_atomicity_fortran_wrapper(fh, flag, ierr); } _EXTERN_C_ void mpi_file_get_atomicity__(MPI_Fint *fh, MPI_Fint *flag, MPI_Fint *ierr) { MPI_File_get_atomicity_fortran_wrapper(fh, flag, ierr); } /* ================= End Wrappers for MPI_File_get_atomicity ================= */ /* ================== C Wrappers for MPI_File_get_byte_offset ================== */ _EXTERN_C_ int PMPI_File_get_byte_offset(MPI_File fh, MPI_Offset offset, MPI_Offset *disp); _EXTERN_C_ int MPI_File_get_byte_offset(MPI_File fh, MPI_Offset offset, MPI_Offset *disp) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_get_byte_offset(fh, offset, disp); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_get_byte_offset =============== */ static void MPI_File_get_byte_offset_fortran_wrapper(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *disp, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_get_byte_offset((MPI_File)(*fh), *offset, (MPI_Offset*)disp); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_get_byte_offset(MPI_File_f2c(*fh), *offset, (MPI_Offset*)disp); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_GET_BYTE_OFFSET(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *disp, MPI_Fint *ierr) { MPI_File_get_byte_offset_fortran_wrapper(fh, offset, disp, ierr); } _EXTERN_C_ void mpi_file_get_byte_offset(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *disp, MPI_Fint *ierr) { MPI_File_get_byte_offset_fortran_wrapper(fh, offset, disp, ierr); } _EXTERN_C_ void mpi_file_get_byte_offset_(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *disp, MPI_Fint *ierr) { MPI_File_get_byte_offset_fortran_wrapper(fh, offset, disp, ierr); } _EXTERN_C_ void mpi_file_get_byte_offset__(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *disp, MPI_Fint *ierr) { MPI_File_get_byte_offset_fortran_wrapper(fh, offset, disp, ierr); } /* ================= End Wrappers for MPI_File_get_byte_offset ================= */ /* ================== C Wrappers for MPI_File_get_errhandler ================== */ _EXTERN_C_ int PMPI_File_get_errhandler(MPI_File file, MPI_Errhandler *errhandler); _EXTERN_C_ int MPI_File_get_errhandler(MPI_File file, MPI_Errhandler *errhandler) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_get_errhandler(file, errhandler); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_get_errhandler =============== */ static void MPI_File_get_errhandler_fortran_wrapper(MPI_Fint *file, MPI_Fint *errhandler, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_get_errhandler((MPI_File)(*file), (MPI_Errhandler*)errhandler); #else /* MPI-2 safe call */ MPI_Errhandler temp_errhandler; temp_errhandler = MPI_Errhandler_f2c(*errhandler); _wrap_py_return_val = MPI_File_get_errhandler(MPI_File_f2c(*file), &temp_errhandler); *errhandler = MPI_Errhandler_c2f(temp_errhandler); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_GET_ERRHANDLER(MPI_Fint *file, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_File_get_errhandler_fortran_wrapper(file, errhandler, ierr); } _EXTERN_C_ void mpi_file_get_errhandler(MPI_Fint *file, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_File_get_errhandler_fortran_wrapper(file, errhandler, ierr); } _EXTERN_C_ void mpi_file_get_errhandler_(MPI_Fint *file, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_File_get_errhandler_fortran_wrapper(file, errhandler, ierr); } _EXTERN_C_ void mpi_file_get_errhandler__(MPI_Fint *file, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_File_get_errhandler_fortran_wrapper(file, errhandler, ierr); } /* ================= End Wrappers for MPI_File_get_errhandler ================= */ /* ================== C Wrappers for MPI_File_get_group ================== */ _EXTERN_C_ int PMPI_File_get_group(MPI_File fh, MPI_Group *group); _EXTERN_C_ int MPI_File_get_group(MPI_File fh, MPI_Group *group) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_get_group(fh, group); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_get_group =============== */ static void MPI_File_get_group_fortran_wrapper(MPI_Fint *fh, MPI_Fint *group, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_get_group((MPI_File)(*fh), (MPI_Group*)group); #else /* MPI-2 safe call */ MPI_Group temp_group; temp_group = MPI_Group_f2c(*group); _wrap_py_return_val = MPI_File_get_group(MPI_File_f2c(*fh), &temp_group); *group = MPI_Group_c2f(temp_group); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_GET_GROUP(MPI_Fint *fh, MPI_Fint *group, MPI_Fint *ierr) { MPI_File_get_group_fortran_wrapper(fh, group, ierr); } _EXTERN_C_ void mpi_file_get_group(MPI_Fint *fh, MPI_Fint *group, MPI_Fint *ierr) { MPI_File_get_group_fortran_wrapper(fh, group, ierr); } _EXTERN_C_ void mpi_file_get_group_(MPI_Fint *fh, MPI_Fint *group, MPI_Fint *ierr) { MPI_File_get_group_fortran_wrapper(fh, group, ierr); } _EXTERN_C_ void mpi_file_get_group__(MPI_Fint *fh, MPI_Fint *group, MPI_Fint *ierr) { MPI_File_get_group_fortran_wrapper(fh, group, ierr); } /* ================= End Wrappers for MPI_File_get_group ================= */ /* ================== C Wrappers for MPI_File_get_info ================== */ _EXTERN_C_ int PMPI_File_get_info(MPI_File fh, MPI_Info *info_used); _EXTERN_C_ int MPI_File_get_info(MPI_File fh, MPI_Info *info_used) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_get_info(fh, info_used); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_get_info =============== */ static void MPI_File_get_info_fortran_wrapper(MPI_Fint *fh, MPI_Fint *info_used, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_get_info((MPI_File)(*fh), (MPI_Info*)info_used); #else /* MPI-2 safe call */ MPI_Info temp_info_used; temp_info_used = MPI_Info_f2c(*info_used); _wrap_py_return_val = MPI_File_get_info(MPI_File_f2c(*fh), &temp_info_used); *info_used = MPI_Info_c2f(temp_info_used); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_GET_INFO(MPI_Fint *fh, MPI_Fint *info_used, MPI_Fint *ierr) { MPI_File_get_info_fortran_wrapper(fh, info_used, ierr); } _EXTERN_C_ void mpi_file_get_info(MPI_Fint *fh, MPI_Fint *info_used, MPI_Fint *ierr) { MPI_File_get_info_fortran_wrapper(fh, info_used, ierr); } _EXTERN_C_ void mpi_file_get_info_(MPI_Fint *fh, MPI_Fint *info_used, MPI_Fint *ierr) { MPI_File_get_info_fortran_wrapper(fh, info_used, ierr); } _EXTERN_C_ void mpi_file_get_info__(MPI_Fint *fh, MPI_Fint *info_used, MPI_Fint *ierr) { MPI_File_get_info_fortran_wrapper(fh, info_used, ierr); } /* ================= End Wrappers for MPI_File_get_info ================= */ /* ================== C Wrappers for MPI_File_get_position ================== */ _EXTERN_C_ int PMPI_File_get_position(MPI_File fh, MPI_Offset *offset); _EXTERN_C_ int MPI_File_get_position(MPI_File fh, MPI_Offset *offset) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_get_position(fh, offset); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_get_position =============== */ static void MPI_File_get_position_fortran_wrapper(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_get_position((MPI_File)(*fh), (MPI_Offset*)offset); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_get_position(MPI_File_f2c(*fh), (MPI_Offset*)offset); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_GET_POSITION(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *ierr) { MPI_File_get_position_fortran_wrapper(fh, offset, ierr); } _EXTERN_C_ void mpi_file_get_position(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *ierr) { MPI_File_get_position_fortran_wrapper(fh, offset, ierr); } _EXTERN_C_ void mpi_file_get_position_(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *ierr) { MPI_File_get_position_fortran_wrapper(fh, offset, ierr); } _EXTERN_C_ void mpi_file_get_position__(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *ierr) { MPI_File_get_position_fortran_wrapper(fh, offset, ierr); } /* ================= End Wrappers for MPI_File_get_position ================= */ /* ================== C Wrappers for MPI_File_get_position_shared ================== */ _EXTERN_C_ int PMPI_File_get_position_shared(MPI_File fh, MPI_Offset *offset); _EXTERN_C_ int MPI_File_get_position_shared(MPI_File fh, MPI_Offset *offset) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_get_position_shared(fh, offset); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_get_position_shared =============== */ static void MPI_File_get_position_shared_fortran_wrapper(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_get_position_shared((MPI_File)(*fh), (MPI_Offset*)offset); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_get_position_shared(MPI_File_f2c(*fh), (MPI_Offset*)offset); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_GET_POSITION_SHARED(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *ierr) { MPI_File_get_position_shared_fortran_wrapper(fh, offset, ierr); } _EXTERN_C_ void mpi_file_get_position_shared(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *ierr) { MPI_File_get_position_shared_fortran_wrapper(fh, offset, ierr); } _EXTERN_C_ void mpi_file_get_position_shared_(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *ierr) { MPI_File_get_position_shared_fortran_wrapper(fh, offset, ierr); } _EXTERN_C_ void mpi_file_get_position_shared__(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *ierr) { MPI_File_get_position_shared_fortran_wrapper(fh, offset, ierr); } /* ================= End Wrappers for MPI_File_get_position_shared ================= */ /* ================== C Wrappers for MPI_File_get_size ================== */ _EXTERN_C_ int PMPI_File_get_size(MPI_File fh, MPI_Offset *size); _EXTERN_C_ int MPI_File_get_size(MPI_File fh, MPI_Offset *size) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_get_size(fh, size); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_get_size =============== */ static void MPI_File_get_size_fortran_wrapper(MPI_Fint *fh, MPI_Fint *size, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_get_size((MPI_File)(*fh), (MPI_Offset*)size); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_get_size(MPI_File_f2c(*fh), (MPI_Offset*)size); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_GET_SIZE(MPI_Fint *fh, MPI_Fint *size, MPI_Fint *ierr) { MPI_File_get_size_fortran_wrapper(fh, size, ierr); } _EXTERN_C_ void mpi_file_get_size(MPI_Fint *fh, MPI_Fint *size, MPI_Fint *ierr) { MPI_File_get_size_fortran_wrapper(fh, size, ierr); } _EXTERN_C_ void mpi_file_get_size_(MPI_Fint *fh, MPI_Fint *size, MPI_Fint *ierr) { MPI_File_get_size_fortran_wrapper(fh, size, ierr); } _EXTERN_C_ void mpi_file_get_size__(MPI_Fint *fh, MPI_Fint *size, MPI_Fint *ierr) { MPI_File_get_size_fortran_wrapper(fh, size, ierr); } /* ================= End Wrappers for MPI_File_get_size ================= */ /* ================== C Wrappers for MPI_File_get_type_extent ================== */ _EXTERN_C_ int PMPI_File_get_type_extent(MPI_File fh, MPI_Datatype datatype, MPI_Aint *extent); _EXTERN_C_ int MPI_File_get_type_extent(MPI_File fh, MPI_Datatype datatype, MPI_Aint *extent) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_get_type_extent(fh, datatype, extent); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_get_type_extent =============== */ static void MPI_File_get_type_extent_fortran_wrapper(MPI_Fint *fh, MPI_Fint *datatype, MPI_Aint *extent, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_get_type_extent((MPI_File)(*fh), (MPI_Datatype)(*datatype), (MPI_Aint*)extent); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_get_type_extent(MPI_File_f2c(*fh), MPI_Type_f2c(*datatype), (MPI_Aint*)extent); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_GET_TYPE_EXTENT(MPI_Fint *fh, MPI_Fint *datatype, MPI_Aint *extent, MPI_Fint *ierr) { MPI_File_get_type_extent_fortran_wrapper(fh, datatype, extent, ierr); } _EXTERN_C_ void mpi_file_get_type_extent(MPI_Fint *fh, MPI_Fint *datatype, MPI_Aint *extent, MPI_Fint *ierr) { MPI_File_get_type_extent_fortran_wrapper(fh, datatype, extent, ierr); } _EXTERN_C_ void mpi_file_get_type_extent_(MPI_Fint *fh, MPI_Fint *datatype, MPI_Aint *extent, MPI_Fint *ierr) { MPI_File_get_type_extent_fortran_wrapper(fh, datatype, extent, ierr); } _EXTERN_C_ void mpi_file_get_type_extent__(MPI_Fint *fh, MPI_Fint *datatype, MPI_Aint *extent, MPI_Fint *ierr) { MPI_File_get_type_extent_fortran_wrapper(fh, datatype, extent, ierr); } /* ================= End Wrappers for MPI_File_get_type_extent ================= */ /* ================== C Wrappers for MPI_File_get_view ================== */ _EXTERN_C_ int PMPI_File_get_view(MPI_File fh, MPI_Offset *disp, MPI_Datatype *etype, MPI_Datatype *filetype, char *datarep); _EXTERN_C_ int MPI_File_get_view(MPI_File fh, MPI_Offset *disp, MPI_Datatype *etype, MPI_Datatype *filetype, char *datarep) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_get_view(fh, disp, etype, filetype, datarep); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_get_view =============== */ static void MPI_File_get_view_fortran_wrapper(MPI_Fint *fh, MPI_Fint *disp, MPI_Fint *etype, MPI_Fint *filetype, MPI_Fint *datarep, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_get_view((MPI_File)(*fh), (MPI_Offset*)disp, (MPI_Datatype*)etype, (MPI_Datatype*)filetype, (char*)datarep); #else /* MPI-2 safe call */ MPI_Datatype temp_filetype; MPI_Datatype temp_etype; temp_etype = MPI_Type_f2c(*etype); temp_filetype = MPI_Type_f2c(*filetype); _wrap_py_return_val = MPI_File_get_view(MPI_File_f2c(*fh), (MPI_Offset*)disp, &temp_etype, &temp_filetype, (char*)datarep); *etype = MPI_Type_c2f(temp_etype); *filetype = MPI_Type_c2f(temp_filetype); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_GET_VIEW(MPI_Fint *fh, MPI_Fint *disp, MPI_Fint *etype, MPI_Fint *filetype, MPI_Fint *datarep, MPI_Fint *ierr) { MPI_File_get_view_fortran_wrapper(fh, disp, etype, filetype, datarep, ierr); } _EXTERN_C_ void mpi_file_get_view(MPI_Fint *fh, MPI_Fint *disp, MPI_Fint *etype, MPI_Fint *filetype, MPI_Fint *datarep, MPI_Fint *ierr) { MPI_File_get_view_fortran_wrapper(fh, disp, etype, filetype, datarep, ierr); } _EXTERN_C_ void mpi_file_get_view_(MPI_Fint *fh, MPI_Fint *disp, MPI_Fint *etype, MPI_Fint *filetype, MPI_Fint *datarep, MPI_Fint *ierr) { MPI_File_get_view_fortran_wrapper(fh, disp, etype, filetype, datarep, ierr); } _EXTERN_C_ void mpi_file_get_view__(MPI_Fint *fh, MPI_Fint *disp, MPI_Fint *etype, MPI_Fint *filetype, MPI_Fint *datarep, MPI_Fint *ierr) { MPI_File_get_view_fortran_wrapper(fh, disp, etype, filetype, datarep, ierr); } /* ================= End Wrappers for MPI_File_get_view ================= */ /* ================== C Wrappers for MPI_File_iread ================== */ _EXTERN_C_ int PMPI_File_iread(MPI_File fh, void *buf, int count, MPI_Datatype datatype, MPI_Request *request); _EXTERN_C_ int MPI_File_iread(MPI_File fh, void *buf, int count, MPI_Datatype datatype, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_iread(fh, buf, count, datatype, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_iread =============== */ static void MPI_File_iread_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_iread((MPI_File)(*fh), (void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_File_iread(MPI_File_f2c(*fh), (void*)buf, *count, MPI_Type_f2c(*datatype), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_IREAD(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iread(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iread_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iread__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_fortran_wrapper(fh, buf, count, datatype, request, ierr); } /* ================= End Wrappers for MPI_File_iread ================= */ /* ================== C Wrappers for MPI_File_iread_all ================== */ _EXTERN_C_ int PMPI_File_iread_all(MPI_File fh, void *buf, int count, MPI_Datatype datatype, MPI_Request *request); _EXTERN_C_ int MPI_File_iread_all(MPI_File fh, void *buf, int count, MPI_Datatype datatype, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_iread_all(fh, buf, count, datatype, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_iread_all =============== */ static void MPI_File_iread_all_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_iread_all((MPI_File)(*fh), (void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_File_iread_all(MPI_File_f2c(*fh), (void*)buf, *count, MPI_Type_f2c(*datatype), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_IREAD_ALL(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_all_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iread_all(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_all_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iread_all_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_all_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iread_all__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_all_fortran_wrapper(fh, buf, count, datatype, request, ierr); } /* ================= End Wrappers for MPI_File_iread_all ================= */ /* ================== C Wrappers for MPI_File_iread_at ================== */ _EXTERN_C_ int PMPI_File_iread_at(MPI_File fh, MPI_Offset offset, void *buf, int count, MPI_Datatype datatype, MPI_Request *request); _EXTERN_C_ int MPI_File_iread_at(MPI_File fh, MPI_Offset offset, void *buf, int count, MPI_Datatype datatype, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_iread_at(fh, offset, buf, count, datatype, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_iread_at =============== */ static void MPI_File_iread_at_fortran_wrapper(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_iread_at((MPI_File)(*fh), *offset, (void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_File_iread_at(MPI_File_f2c(*fh), *offset, (void*)buf, *count, MPI_Type_f2c(*datatype), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_IREAD_AT(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_at_fortran_wrapper(fh, offset, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iread_at(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_at_fortran_wrapper(fh, offset, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iread_at_(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_at_fortran_wrapper(fh, offset, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iread_at__(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_at_fortran_wrapper(fh, offset, buf, count, datatype, request, ierr); } /* ================= End Wrappers for MPI_File_iread_at ================= */ /* ================== C Wrappers for MPI_File_iread_at_all ================== */ _EXTERN_C_ int PMPI_File_iread_at_all(MPI_File fh, MPI_Offset offset, void *buf, int count, MPI_Datatype datatype, MPI_Request *request); _EXTERN_C_ int MPI_File_iread_at_all(MPI_File fh, MPI_Offset offset, void *buf, int count, MPI_Datatype datatype, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_iread_at_all(fh, offset, buf, count, datatype, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_iread_at_all =============== */ static void MPI_File_iread_at_all_fortran_wrapper(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_iread_at_all((MPI_File)(*fh), *offset, (void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_File_iread_at_all(MPI_File_f2c(*fh), *offset, (void*)buf, *count, MPI_Type_f2c(*datatype), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_IREAD_AT_ALL(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_at_all_fortran_wrapper(fh, offset, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iread_at_all(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_at_all_fortran_wrapper(fh, offset, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iread_at_all_(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_at_all_fortran_wrapper(fh, offset, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iread_at_all__(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_at_all_fortran_wrapper(fh, offset, buf, count, datatype, request, ierr); } /* ================= End Wrappers for MPI_File_iread_at_all ================= */ /* ================== C Wrappers for MPI_File_iread_shared ================== */ _EXTERN_C_ int PMPI_File_iread_shared(MPI_File fh, void *buf, int count, MPI_Datatype datatype, MPI_Request *request); _EXTERN_C_ int MPI_File_iread_shared(MPI_File fh, void *buf, int count, MPI_Datatype datatype, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_iread_shared(fh, buf, count, datatype, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_iread_shared =============== */ static void MPI_File_iread_shared_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_iread_shared((MPI_File)(*fh), (void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_File_iread_shared(MPI_File_f2c(*fh), (void*)buf, *count, MPI_Type_f2c(*datatype), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_IREAD_SHARED(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_shared_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iread_shared(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_shared_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iread_shared_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_shared_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iread_shared__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iread_shared_fortran_wrapper(fh, buf, count, datatype, request, ierr); } /* ================= End Wrappers for MPI_File_iread_shared ================= */ /* ================== C Wrappers for MPI_File_iwrite ================== */ _EXTERN_C_ int PMPI_File_iwrite(MPI_File fh, const void *buf, int count, MPI_Datatype datatype, MPI_Request *request); _EXTERN_C_ int MPI_File_iwrite(MPI_File fh, const void *buf, int count, MPI_Datatype datatype, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_iwrite(fh, buf, count, datatype, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_iwrite =============== */ static void MPI_File_iwrite_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_iwrite((MPI_File)(*fh), (const void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_File_iwrite(MPI_File_f2c(*fh), (const void*)buf, *count, MPI_Type_f2c(*datatype), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_IWRITE(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iwrite(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iwrite_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iwrite__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_fortran_wrapper(fh, buf, count, datatype, request, ierr); } /* ================= End Wrappers for MPI_File_iwrite ================= */ /* ================== C Wrappers for MPI_File_iwrite_all ================== */ _EXTERN_C_ int PMPI_File_iwrite_all(MPI_File fh, const void *buf, int count, MPI_Datatype datatype, MPI_Request *request); _EXTERN_C_ int MPI_File_iwrite_all(MPI_File fh, const void *buf, int count, MPI_Datatype datatype, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_iwrite_all(fh, buf, count, datatype, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_iwrite_all =============== */ static void MPI_File_iwrite_all_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_iwrite_all((MPI_File)(*fh), (const void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_File_iwrite_all(MPI_File_f2c(*fh), (const void*)buf, *count, MPI_Type_f2c(*datatype), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_IWRITE_ALL(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_all_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iwrite_all(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_all_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iwrite_all_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_all_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iwrite_all__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_all_fortran_wrapper(fh, buf, count, datatype, request, ierr); } /* ================= End Wrappers for MPI_File_iwrite_all ================= */ /* ================== C Wrappers for MPI_File_iwrite_at ================== */ _EXTERN_C_ int PMPI_File_iwrite_at(MPI_File fh, MPI_Offset offset, const void *buf, int count, MPI_Datatype datatype, MPI_Request *request); _EXTERN_C_ int MPI_File_iwrite_at(MPI_File fh, MPI_Offset offset, const void *buf, int count, MPI_Datatype datatype, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_iwrite_at(fh, offset, buf, count, datatype, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_iwrite_at =============== */ static void MPI_File_iwrite_at_fortran_wrapper(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_iwrite_at((MPI_File)(*fh), *offset, (const void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_File_iwrite_at(MPI_File_f2c(*fh), *offset, (const void*)buf, *count, MPI_Type_f2c(*datatype), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_IWRITE_AT(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_at_fortran_wrapper(fh, offset, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iwrite_at(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_at_fortran_wrapper(fh, offset, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iwrite_at_(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_at_fortran_wrapper(fh, offset, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iwrite_at__(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_at_fortran_wrapper(fh, offset, buf, count, datatype, request, ierr); } /* ================= End Wrappers for MPI_File_iwrite_at ================= */ /* ================== C Wrappers for MPI_File_iwrite_at_all ================== */ _EXTERN_C_ int PMPI_File_iwrite_at_all(MPI_File fh, MPI_Offset offset, const void *buf, int count, MPI_Datatype datatype, MPI_Request *request); _EXTERN_C_ int MPI_File_iwrite_at_all(MPI_File fh, MPI_Offset offset, const void *buf, int count, MPI_Datatype datatype, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_iwrite_at_all(fh, offset, buf, count, datatype, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_iwrite_at_all =============== */ static void MPI_File_iwrite_at_all_fortran_wrapper(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_iwrite_at_all((MPI_File)(*fh), *offset, (const void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_File_iwrite_at_all(MPI_File_f2c(*fh), *offset, (const void*)buf, *count, MPI_Type_f2c(*datatype), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_IWRITE_AT_ALL(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_at_all_fortran_wrapper(fh, offset, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iwrite_at_all(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_at_all_fortran_wrapper(fh, offset, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iwrite_at_all_(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_at_all_fortran_wrapper(fh, offset, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iwrite_at_all__(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_at_all_fortran_wrapper(fh, offset, buf, count, datatype, request, ierr); } /* ================= End Wrappers for MPI_File_iwrite_at_all ================= */ /* ================== C Wrappers for MPI_File_iwrite_shared ================== */ _EXTERN_C_ int PMPI_File_iwrite_shared(MPI_File fh, const void *buf, int count, MPI_Datatype datatype, MPI_Request *request); _EXTERN_C_ int MPI_File_iwrite_shared(MPI_File fh, const void *buf, int count, MPI_Datatype datatype, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_iwrite_shared(fh, buf, count, datatype, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_iwrite_shared =============== */ static void MPI_File_iwrite_shared_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_iwrite_shared((MPI_File)(*fh), (const void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_File_iwrite_shared(MPI_File_f2c(*fh), (const void*)buf, *count, MPI_Type_f2c(*datatype), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_IWRITE_SHARED(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_shared_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iwrite_shared(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_shared_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iwrite_shared_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_shared_fortran_wrapper(fh, buf, count, datatype, request, ierr); } _EXTERN_C_ void mpi_file_iwrite_shared__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *request, MPI_Fint *ierr) { MPI_File_iwrite_shared_fortran_wrapper(fh, buf, count, datatype, request, ierr); } /* ================= End Wrappers for MPI_File_iwrite_shared ================= */ /* ================== C Wrappers for MPI_File_open ================== */ _EXTERN_C_ int PMPI_File_open(MPI_Comm comm, const char *filename, int amode, MPI_Info info, MPI_File *fh); _EXTERN_C_ int MPI_File_open(MPI_Comm comm, const char *filename, int amode, MPI_Info info, MPI_File *fh) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_open(comm, filename, amode, info, fh); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_open =============== */ static void MPI_File_open_fortran_wrapper(MPI_Fint *comm, MPI_Fint *filename, MPI_Fint *amode, MPI_Fint *info, MPI_Fint *fh, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_open((MPI_Comm)(*comm), (const char*)filename, *amode, (MPI_Info)(*info), (MPI_File*)fh); #else /* MPI-2 safe call */ MPI_File temp_fh; temp_fh = MPI_File_f2c(*fh); _wrap_py_return_val = MPI_File_open(MPI_Comm_f2c(*comm), (const char*)filename, *amode, MPI_Info_f2c(*info), &temp_fh); *fh = MPI_File_c2f(temp_fh); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_OPEN(MPI_Fint *comm, MPI_Fint *filename, MPI_Fint *amode, MPI_Fint *info, MPI_Fint *fh, MPI_Fint *ierr) { MPI_File_open_fortran_wrapper(comm, filename, amode, info, fh, ierr); } _EXTERN_C_ void mpi_file_open(MPI_Fint *comm, MPI_Fint *filename, MPI_Fint *amode, MPI_Fint *info, MPI_Fint *fh, MPI_Fint *ierr) { MPI_File_open_fortran_wrapper(comm, filename, amode, info, fh, ierr); } _EXTERN_C_ void mpi_file_open_(MPI_Fint *comm, MPI_Fint *filename, MPI_Fint *amode, MPI_Fint *info, MPI_Fint *fh, MPI_Fint *ierr) { MPI_File_open_fortran_wrapper(comm, filename, amode, info, fh, ierr); } _EXTERN_C_ void mpi_file_open__(MPI_Fint *comm, MPI_Fint *filename, MPI_Fint *amode, MPI_Fint *info, MPI_Fint *fh, MPI_Fint *ierr) { MPI_File_open_fortran_wrapper(comm, filename, amode, info, fh, ierr); } /* ================= End Wrappers for MPI_File_open ================= */ /* ================== C Wrappers for MPI_File_preallocate ================== */ _EXTERN_C_ int PMPI_File_preallocate(MPI_File fh, MPI_Offset size); _EXTERN_C_ int MPI_File_preallocate(MPI_File fh, MPI_Offset size) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_preallocate(fh, size); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_preallocate =============== */ static void MPI_File_preallocate_fortran_wrapper(MPI_Fint *fh, MPI_Fint *size, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_preallocate((MPI_File)(*fh), *size); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_preallocate(MPI_File_f2c(*fh), *size); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_PREALLOCATE(MPI_Fint *fh, MPI_Fint *size, MPI_Fint *ierr) { MPI_File_preallocate_fortran_wrapper(fh, size, ierr); } _EXTERN_C_ void mpi_file_preallocate(MPI_Fint *fh, MPI_Fint *size, MPI_Fint *ierr) { MPI_File_preallocate_fortran_wrapper(fh, size, ierr); } _EXTERN_C_ void mpi_file_preallocate_(MPI_Fint *fh, MPI_Fint *size, MPI_Fint *ierr) { MPI_File_preallocate_fortran_wrapper(fh, size, ierr); } _EXTERN_C_ void mpi_file_preallocate__(MPI_Fint *fh, MPI_Fint *size, MPI_Fint *ierr) { MPI_File_preallocate_fortran_wrapper(fh, size, ierr); } /* ================= End Wrappers for MPI_File_preallocate ================= */ /* ================== C Wrappers for MPI_File_read ================== */ _EXTERN_C_ int PMPI_File_read(MPI_File fh, void *buf, int count, MPI_Datatype datatype, MPI_Status *status); _EXTERN_C_ int MPI_File_read(MPI_File fh, void *buf, int count, MPI_Datatype datatype, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_read(fh, buf, count, datatype, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_read =============== */ static void MPI_File_read_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_read((MPI_File)(*fh), (void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_read(MPI_File_f2c(*fh), (void*)buf, *count, MPI_Type_f2c(*datatype), &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_READ(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_fortran_wrapper(fh, buf, count, datatype, status, ierr); } /* ================= End Wrappers for MPI_File_read ================= */ /* ================== C Wrappers for MPI_File_read_all ================== */ _EXTERN_C_ int PMPI_File_read_all(MPI_File fh, void *buf, int count, MPI_Datatype datatype, MPI_Status *status); _EXTERN_C_ int MPI_File_read_all(MPI_File fh, void *buf, int count, MPI_Datatype datatype, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_read_all(fh, buf, count, datatype, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_read_all =============== */ static void MPI_File_read_all_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_read_all((MPI_File)(*fh), (void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_read_all(MPI_File_f2c(*fh), (void*)buf, *count, MPI_Type_f2c(*datatype), &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_READ_ALL(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_all_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read_all(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_all_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read_all_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_all_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read_all__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_all_fortran_wrapper(fh, buf, count, datatype, status, ierr); } /* ================= End Wrappers for MPI_File_read_all ================= */ /* ================== C Wrappers for MPI_File_read_all_begin ================== */ _EXTERN_C_ int PMPI_File_read_all_begin(MPI_File fh, void *buf, int count, MPI_Datatype datatype); _EXTERN_C_ int MPI_File_read_all_begin(MPI_File fh, void *buf, int count, MPI_Datatype datatype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_read_all_begin(fh, buf, count, datatype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_read_all_begin =============== */ static void MPI_File_read_all_begin_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_read_all_begin((MPI_File)(*fh), (void*)buf, *count, (MPI_Datatype)(*datatype)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_read_all_begin(MPI_File_f2c(*fh), (void*)buf, *count, MPI_Type_f2c(*datatype)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_READ_ALL_BEGIN(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_read_all_begin_fortran_wrapper(fh, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_read_all_begin(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_read_all_begin_fortran_wrapper(fh, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_read_all_begin_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_read_all_begin_fortran_wrapper(fh, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_read_all_begin__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_read_all_begin_fortran_wrapper(fh, buf, count, datatype, ierr); } /* ================= End Wrappers for MPI_File_read_all_begin ================= */ /* ================== C Wrappers for MPI_File_read_all_end ================== */ _EXTERN_C_ int PMPI_File_read_all_end(MPI_File fh, void *buf, MPI_Status *status); _EXTERN_C_ int MPI_File_read_all_end(MPI_File fh, void *buf, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_read_all_end(fh, buf, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_read_all_end =============== */ static void MPI_File_read_all_end_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_read_all_end((MPI_File)(*fh), (void*)buf, (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_read_all_end(MPI_File_f2c(*fh), (void*)buf, &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_READ_ALL_END(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_all_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_read_all_end(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_all_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_read_all_end_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_all_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_read_all_end__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_all_end_fortran_wrapper(fh, buf, status, ierr); } /* ================= End Wrappers for MPI_File_read_all_end ================= */ /* ================== C Wrappers for MPI_File_read_at ================== */ _EXTERN_C_ int PMPI_File_read_at(MPI_File fh, MPI_Offset offset, void *buf, int count, MPI_Datatype datatype, MPI_Status *status); _EXTERN_C_ int MPI_File_read_at(MPI_File fh, MPI_Offset offset, void *buf, int count, MPI_Datatype datatype, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_read_at(fh, offset, buf, count, datatype, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_read_at =============== */ static void MPI_File_read_at_fortran_wrapper(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_read_at((MPI_File)(*fh), *offset, (void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_read_at(MPI_File_f2c(*fh), *offset, (void*)buf, *count, MPI_Type_f2c(*datatype), &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_READ_AT(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_at_fortran_wrapper(fh, offset, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read_at(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_at_fortran_wrapper(fh, offset, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read_at_(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_at_fortran_wrapper(fh, offset, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read_at__(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_at_fortran_wrapper(fh, offset, buf, count, datatype, status, ierr); } /* ================= End Wrappers for MPI_File_read_at ================= */ /* ================== C Wrappers for MPI_File_read_at_all ================== */ _EXTERN_C_ int PMPI_File_read_at_all(MPI_File fh, MPI_Offset offset, void *buf, int count, MPI_Datatype datatype, MPI_Status *status); _EXTERN_C_ int MPI_File_read_at_all(MPI_File fh, MPI_Offset offset, void *buf, int count, MPI_Datatype datatype, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_read_at_all(fh, offset, buf, count, datatype, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_read_at_all =============== */ static void MPI_File_read_at_all_fortran_wrapper(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_read_at_all((MPI_File)(*fh), *offset, (void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_read_at_all(MPI_File_f2c(*fh), *offset, (void*)buf, *count, MPI_Type_f2c(*datatype), &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_READ_AT_ALL(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_at_all_fortran_wrapper(fh, offset, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read_at_all(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_at_all_fortran_wrapper(fh, offset, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read_at_all_(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_at_all_fortran_wrapper(fh, offset, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read_at_all__(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_at_all_fortran_wrapper(fh, offset, buf, count, datatype, status, ierr); } /* ================= End Wrappers for MPI_File_read_at_all ================= */ /* ================== C Wrappers for MPI_File_read_at_all_begin ================== */ _EXTERN_C_ int PMPI_File_read_at_all_begin(MPI_File fh, MPI_Offset offset, void *buf, int count, MPI_Datatype datatype); _EXTERN_C_ int MPI_File_read_at_all_begin(MPI_File fh, MPI_Offset offset, void *buf, int count, MPI_Datatype datatype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_read_at_all_begin(fh, offset, buf, count, datatype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_read_at_all_begin =============== */ static void MPI_File_read_at_all_begin_fortran_wrapper(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_read_at_all_begin((MPI_File)(*fh), *offset, (void*)buf, *count, (MPI_Datatype)(*datatype)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_read_at_all_begin(MPI_File_f2c(*fh), *offset, (void*)buf, *count, MPI_Type_f2c(*datatype)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_READ_AT_ALL_BEGIN(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_read_at_all_begin_fortran_wrapper(fh, offset, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_read_at_all_begin(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_read_at_all_begin_fortran_wrapper(fh, offset, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_read_at_all_begin_(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_read_at_all_begin_fortran_wrapper(fh, offset, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_read_at_all_begin__(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_read_at_all_begin_fortran_wrapper(fh, offset, buf, count, datatype, ierr); } /* ================= End Wrappers for MPI_File_read_at_all_begin ================= */ /* ================== C Wrappers for MPI_File_read_at_all_end ================== */ _EXTERN_C_ int PMPI_File_read_at_all_end(MPI_File fh, void *buf, MPI_Status *status); _EXTERN_C_ int MPI_File_read_at_all_end(MPI_File fh, void *buf, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_read_at_all_end(fh, buf, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_read_at_all_end =============== */ static void MPI_File_read_at_all_end_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_read_at_all_end((MPI_File)(*fh), (void*)buf, (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_read_at_all_end(MPI_File_f2c(*fh), (void*)buf, &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_READ_AT_ALL_END(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_at_all_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_read_at_all_end(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_at_all_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_read_at_all_end_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_at_all_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_read_at_all_end__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_at_all_end_fortran_wrapper(fh, buf, status, ierr); } /* ================= End Wrappers for MPI_File_read_at_all_end ================= */ /* ================== C Wrappers for MPI_File_read_ordered ================== */ _EXTERN_C_ int PMPI_File_read_ordered(MPI_File fh, void *buf, int count, MPI_Datatype datatype, MPI_Status *status); _EXTERN_C_ int MPI_File_read_ordered(MPI_File fh, void *buf, int count, MPI_Datatype datatype, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_read_ordered(fh, buf, count, datatype, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_read_ordered =============== */ static void MPI_File_read_ordered_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_read_ordered((MPI_File)(*fh), (void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_read_ordered(MPI_File_f2c(*fh), (void*)buf, *count, MPI_Type_f2c(*datatype), &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_READ_ORDERED(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_ordered_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read_ordered(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_ordered_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read_ordered_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_ordered_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read_ordered__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_ordered_fortran_wrapper(fh, buf, count, datatype, status, ierr); } /* ================= End Wrappers for MPI_File_read_ordered ================= */ /* ================== C Wrappers for MPI_File_read_ordered_begin ================== */ _EXTERN_C_ int PMPI_File_read_ordered_begin(MPI_File fh, void *buf, int count, MPI_Datatype datatype); _EXTERN_C_ int MPI_File_read_ordered_begin(MPI_File fh, void *buf, int count, MPI_Datatype datatype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_read_ordered_begin(fh, buf, count, datatype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_read_ordered_begin =============== */ static void MPI_File_read_ordered_begin_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_read_ordered_begin((MPI_File)(*fh), (void*)buf, *count, (MPI_Datatype)(*datatype)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_read_ordered_begin(MPI_File_f2c(*fh), (void*)buf, *count, MPI_Type_f2c(*datatype)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_READ_ORDERED_BEGIN(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_read_ordered_begin_fortran_wrapper(fh, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_read_ordered_begin(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_read_ordered_begin_fortran_wrapper(fh, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_read_ordered_begin_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_read_ordered_begin_fortran_wrapper(fh, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_read_ordered_begin__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_read_ordered_begin_fortran_wrapper(fh, buf, count, datatype, ierr); } /* ================= End Wrappers for MPI_File_read_ordered_begin ================= */ /* ================== C Wrappers for MPI_File_read_ordered_end ================== */ _EXTERN_C_ int PMPI_File_read_ordered_end(MPI_File fh, void *buf, MPI_Status *status); _EXTERN_C_ int MPI_File_read_ordered_end(MPI_File fh, void *buf, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_read_ordered_end(fh, buf, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_read_ordered_end =============== */ static void MPI_File_read_ordered_end_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_read_ordered_end((MPI_File)(*fh), (void*)buf, (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_read_ordered_end(MPI_File_f2c(*fh), (void*)buf, &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_READ_ORDERED_END(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_ordered_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_read_ordered_end(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_ordered_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_read_ordered_end_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_ordered_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_read_ordered_end__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_ordered_end_fortran_wrapper(fh, buf, status, ierr); } /* ================= End Wrappers for MPI_File_read_ordered_end ================= */ /* ================== C Wrappers for MPI_File_read_shared ================== */ _EXTERN_C_ int PMPI_File_read_shared(MPI_File fh, void *buf, int count, MPI_Datatype datatype, MPI_Status *status); _EXTERN_C_ int MPI_File_read_shared(MPI_File fh, void *buf, int count, MPI_Datatype datatype, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_read_shared(fh, buf, count, datatype, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_read_shared =============== */ static void MPI_File_read_shared_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_read_shared((MPI_File)(*fh), (void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_read_shared(MPI_File_f2c(*fh), (void*)buf, *count, MPI_Type_f2c(*datatype), &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_READ_SHARED(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_shared_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read_shared(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_shared_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read_shared_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_shared_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_read_shared__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_read_shared_fortran_wrapper(fh, buf, count, datatype, status, ierr); } /* ================= End Wrappers for MPI_File_read_shared ================= */ /* ================== C Wrappers for MPI_File_seek ================== */ _EXTERN_C_ int PMPI_File_seek(MPI_File fh, MPI_Offset offset, int whence); _EXTERN_C_ int MPI_File_seek(MPI_File fh, MPI_Offset offset, int whence) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_seek(fh, offset, whence); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_seek =============== */ static void MPI_File_seek_fortran_wrapper(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *whence, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_seek((MPI_File)(*fh), *offset, *whence); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_seek(MPI_File_f2c(*fh), *offset, *whence); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_SEEK(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *whence, MPI_Fint *ierr) { MPI_File_seek_fortran_wrapper(fh, offset, whence, ierr); } _EXTERN_C_ void mpi_file_seek(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *whence, MPI_Fint *ierr) { MPI_File_seek_fortran_wrapper(fh, offset, whence, ierr); } _EXTERN_C_ void mpi_file_seek_(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *whence, MPI_Fint *ierr) { MPI_File_seek_fortran_wrapper(fh, offset, whence, ierr); } _EXTERN_C_ void mpi_file_seek__(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *whence, MPI_Fint *ierr) { MPI_File_seek_fortran_wrapper(fh, offset, whence, ierr); } /* ================= End Wrappers for MPI_File_seek ================= */ /* ================== C Wrappers for MPI_File_seek_shared ================== */ _EXTERN_C_ int PMPI_File_seek_shared(MPI_File fh, MPI_Offset offset, int whence); _EXTERN_C_ int MPI_File_seek_shared(MPI_File fh, MPI_Offset offset, int whence) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_seek_shared(fh, offset, whence); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_seek_shared =============== */ static void MPI_File_seek_shared_fortran_wrapper(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *whence, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_seek_shared((MPI_File)(*fh), *offset, *whence); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_seek_shared(MPI_File_f2c(*fh), *offset, *whence); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_SEEK_SHARED(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *whence, MPI_Fint *ierr) { MPI_File_seek_shared_fortran_wrapper(fh, offset, whence, ierr); } _EXTERN_C_ void mpi_file_seek_shared(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *whence, MPI_Fint *ierr) { MPI_File_seek_shared_fortran_wrapper(fh, offset, whence, ierr); } _EXTERN_C_ void mpi_file_seek_shared_(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *whence, MPI_Fint *ierr) { MPI_File_seek_shared_fortran_wrapper(fh, offset, whence, ierr); } _EXTERN_C_ void mpi_file_seek_shared__(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *whence, MPI_Fint *ierr) { MPI_File_seek_shared_fortran_wrapper(fh, offset, whence, ierr); } /* ================= End Wrappers for MPI_File_seek_shared ================= */ /* ================== C Wrappers for MPI_File_set_atomicity ================== */ _EXTERN_C_ int PMPI_File_set_atomicity(MPI_File fh, int flag); _EXTERN_C_ int MPI_File_set_atomicity(MPI_File fh, int flag) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_set_atomicity(fh, flag); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_set_atomicity =============== */ static void MPI_File_set_atomicity_fortran_wrapper(MPI_Fint *fh, MPI_Fint *flag, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_set_atomicity((MPI_File)(*fh), *flag); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_set_atomicity(MPI_File_f2c(*fh), *flag); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_SET_ATOMICITY(MPI_Fint *fh, MPI_Fint *flag, MPI_Fint *ierr) { MPI_File_set_atomicity_fortran_wrapper(fh, flag, ierr); } _EXTERN_C_ void mpi_file_set_atomicity(MPI_Fint *fh, MPI_Fint *flag, MPI_Fint *ierr) { MPI_File_set_atomicity_fortran_wrapper(fh, flag, ierr); } _EXTERN_C_ void mpi_file_set_atomicity_(MPI_Fint *fh, MPI_Fint *flag, MPI_Fint *ierr) { MPI_File_set_atomicity_fortran_wrapper(fh, flag, ierr); } _EXTERN_C_ void mpi_file_set_atomicity__(MPI_Fint *fh, MPI_Fint *flag, MPI_Fint *ierr) { MPI_File_set_atomicity_fortran_wrapper(fh, flag, ierr); } /* ================= End Wrappers for MPI_File_set_atomicity ================= */ /* ================== C Wrappers for MPI_File_set_errhandler ================== */ _EXTERN_C_ int PMPI_File_set_errhandler(MPI_File file, MPI_Errhandler errhandler); _EXTERN_C_ int MPI_File_set_errhandler(MPI_File file, MPI_Errhandler errhandler) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_set_errhandler(file, errhandler); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_set_errhandler =============== */ static void MPI_File_set_errhandler_fortran_wrapper(MPI_Fint *file, MPI_Fint *errhandler, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_set_errhandler((MPI_File)(*file), (MPI_Errhandler)(*errhandler)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_set_errhandler(MPI_File_f2c(*file), MPI_Errhandler_f2c(*errhandler)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_SET_ERRHANDLER(MPI_Fint *file, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_File_set_errhandler_fortran_wrapper(file, errhandler, ierr); } _EXTERN_C_ void mpi_file_set_errhandler(MPI_Fint *file, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_File_set_errhandler_fortran_wrapper(file, errhandler, ierr); } _EXTERN_C_ void mpi_file_set_errhandler_(MPI_Fint *file, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_File_set_errhandler_fortran_wrapper(file, errhandler, ierr); } _EXTERN_C_ void mpi_file_set_errhandler__(MPI_Fint *file, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_File_set_errhandler_fortran_wrapper(file, errhandler, ierr); } /* ================= End Wrappers for MPI_File_set_errhandler ================= */ /* ================== C Wrappers for MPI_File_set_info ================== */ _EXTERN_C_ int PMPI_File_set_info(MPI_File fh, MPI_Info info); _EXTERN_C_ int MPI_File_set_info(MPI_File fh, MPI_Info info) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_set_info(fh, info); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_set_info =============== */ static void MPI_File_set_info_fortran_wrapper(MPI_Fint *fh, MPI_Fint *info, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_set_info((MPI_File)(*fh), (MPI_Info)(*info)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_set_info(MPI_File_f2c(*fh), MPI_Info_f2c(*info)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_SET_INFO(MPI_Fint *fh, MPI_Fint *info, MPI_Fint *ierr) { MPI_File_set_info_fortran_wrapper(fh, info, ierr); } _EXTERN_C_ void mpi_file_set_info(MPI_Fint *fh, MPI_Fint *info, MPI_Fint *ierr) { MPI_File_set_info_fortran_wrapper(fh, info, ierr); } _EXTERN_C_ void mpi_file_set_info_(MPI_Fint *fh, MPI_Fint *info, MPI_Fint *ierr) { MPI_File_set_info_fortran_wrapper(fh, info, ierr); } _EXTERN_C_ void mpi_file_set_info__(MPI_Fint *fh, MPI_Fint *info, MPI_Fint *ierr) { MPI_File_set_info_fortran_wrapper(fh, info, ierr); } /* ================= End Wrappers for MPI_File_set_info ================= */ /* ================== C Wrappers for MPI_File_set_size ================== */ _EXTERN_C_ int PMPI_File_set_size(MPI_File fh, MPI_Offset size); _EXTERN_C_ int MPI_File_set_size(MPI_File fh, MPI_Offset size) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_set_size(fh, size); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_set_size =============== */ static void MPI_File_set_size_fortran_wrapper(MPI_Fint *fh, MPI_Fint *size, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_set_size((MPI_File)(*fh), *size); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_set_size(MPI_File_f2c(*fh), *size); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_SET_SIZE(MPI_Fint *fh, MPI_Fint *size, MPI_Fint *ierr) { MPI_File_set_size_fortran_wrapper(fh, size, ierr); } _EXTERN_C_ void mpi_file_set_size(MPI_Fint *fh, MPI_Fint *size, MPI_Fint *ierr) { MPI_File_set_size_fortran_wrapper(fh, size, ierr); } _EXTERN_C_ void mpi_file_set_size_(MPI_Fint *fh, MPI_Fint *size, MPI_Fint *ierr) { MPI_File_set_size_fortran_wrapper(fh, size, ierr); } _EXTERN_C_ void mpi_file_set_size__(MPI_Fint *fh, MPI_Fint *size, MPI_Fint *ierr) { MPI_File_set_size_fortran_wrapper(fh, size, ierr); } /* ================= End Wrappers for MPI_File_set_size ================= */ /* ================== C Wrappers for MPI_File_set_view ================== */ _EXTERN_C_ int PMPI_File_set_view(MPI_File fh, MPI_Offset disp, MPI_Datatype etype, MPI_Datatype filetype, const char *datarep, MPI_Info info); _EXTERN_C_ int MPI_File_set_view(MPI_File fh, MPI_Offset disp, MPI_Datatype etype, MPI_Datatype filetype, const char *datarep, MPI_Info info) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_set_view(fh, disp, etype, filetype, datarep, info); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_set_view =============== */ static void MPI_File_set_view_fortran_wrapper(MPI_Fint *fh, MPI_Fint *disp, MPI_Fint *etype, MPI_Fint *filetype, MPI_Fint *datarep, MPI_Fint *info, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_set_view((MPI_File)(*fh), *disp, (MPI_Datatype)(*etype), (MPI_Datatype)(*filetype), (const char*)datarep, (MPI_Info)(*info)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_set_view(MPI_File_f2c(*fh), *disp, MPI_Type_f2c(*etype), MPI_Type_f2c(*filetype), (const char*)datarep, MPI_Info_f2c(*info)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_SET_VIEW(MPI_Fint *fh, MPI_Fint *disp, MPI_Fint *etype, MPI_Fint *filetype, MPI_Fint *datarep, MPI_Fint *info, MPI_Fint *ierr) { MPI_File_set_view_fortran_wrapper(fh, disp, etype, filetype, datarep, info, ierr); } _EXTERN_C_ void mpi_file_set_view(MPI_Fint *fh, MPI_Fint *disp, MPI_Fint *etype, MPI_Fint *filetype, MPI_Fint *datarep, MPI_Fint *info, MPI_Fint *ierr) { MPI_File_set_view_fortran_wrapper(fh, disp, etype, filetype, datarep, info, ierr); } _EXTERN_C_ void mpi_file_set_view_(MPI_Fint *fh, MPI_Fint *disp, MPI_Fint *etype, MPI_Fint *filetype, MPI_Fint *datarep, MPI_Fint *info, MPI_Fint *ierr) { MPI_File_set_view_fortran_wrapper(fh, disp, etype, filetype, datarep, info, ierr); } _EXTERN_C_ void mpi_file_set_view__(MPI_Fint *fh, MPI_Fint *disp, MPI_Fint *etype, MPI_Fint *filetype, MPI_Fint *datarep, MPI_Fint *info, MPI_Fint *ierr) { MPI_File_set_view_fortran_wrapper(fh, disp, etype, filetype, datarep, info, ierr); } /* ================= End Wrappers for MPI_File_set_view ================= */ /* ================== C Wrappers for MPI_File_sync ================== */ _EXTERN_C_ int PMPI_File_sync(MPI_File fh); _EXTERN_C_ int MPI_File_sync(MPI_File fh) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_sync(fh); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_sync =============== */ static void MPI_File_sync_fortran_wrapper(MPI_Fint *fh, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_sync((MPI_File)(*fh)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_sync(MPI_File_f2c(*fh)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_SYNC(MPI_Fint *fh, MPI_Fint *ierr) { MPI_File_sync_fortran_wrapper(fh, ierr); } _EXTERN_C_ void mpi_file_sync(MPI_Fint *fh, MPI_Fint *ierr) { MPI_File_sync_fortran_wrapper(fh, ierr); } _EXTERN_C_ void mpi_file_sync_(MPI_Fint *fh, MPI_Fint *ierr) { MPI_File_sync_fortran_wrapper(fh, ierr); } _EXTERN_C_ void mpi_file_sync__(MPI_Fint *fh, MPI_Fint *ierr) { MPI_File_sync_fortran_wrapper(fh, ierr); } /* ================= End Wrappers for MPI_File_sync ================= */ /* ================== C Wrappers for MPI_File_write ================== */ _EXTERN_C_ int PMPI_File_write(MPI_File fh, const void *buf, int count, MPI_Datatype datatype, MPI_Status *status); _EXTERN_C_ int MPI_File_write(MPI_File fh, const void *buf, int count, MPI_Datatype datatype, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_write(fh, buf, count, datatype, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_write =============== */ static void MPI_File_write_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_write((MPI_File)(*fh), (const void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_write(MPI_File_f2c(*fh), (const void*)buf, *count, MPI_Type_f2c(*datatype), &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_WRITE(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_fortran_wrapper(fh, buf, count, datatype, status, ierr); } /* ================= End Wrappers for MPI_File_write ================= */ /* ================== C Wrappers for MPI_File_write_all ================== */ _EXTERN_C_ int PMPI_File_write_all(MPI_File fh, const void *buf, int count, MPI_Datatype datatype, MPI_Status *status); _EXTERN_C_ int MPI_File_write_all(MPI_File fh, const void *buf, int count, MPI_Datatype datatype, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_write_all(fh, buf, count, datatype, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_write_all =============== */ static void MPI_File_write_all_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_write_all((MPI_File)(*fh), (const void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_write_all(MPI_File_f2c(*fh), (const void*)buf, *count, MPI_Type_f2c(*datatype), &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_WRITE_ALL(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_all_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write_all(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_all_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write_all_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_all_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write_all__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_all_fortran_wrapper(fh, buf, count, datatype, status, ierr); } /* ================= End Wrappers for MPI_File_write_all ================= */ /* ================== C Wrappers for MPI_File_write_all_begin ================== */ _EXTERN_C_ int PMPI_File_write_all_begin(MPI_File fh, const void *buf, int count, MPI_Datatype datatype); _EXTERN_C_ int MPI_File_write_all_begin(MPI_File fh, const void *buf, int count, MPI_Datatype datatype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_write_all_begin(fh, buf, count, datatype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_write_all_begin =============== */ static void MPI_File_write_all_begin_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_write_all_begin((MPI_File)(*fh), (const void*)buf, *count, (MPI_Datatype)(*datatype)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_write_all_begin(MPI_File_f2c(*fh), (const void*)buf, *count, MPI_Type_f2c(*datatype)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_WRITE_ALL_BEGIN(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_write_all_begin_fortran_wrapper(fh, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_write_all_begin(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_write_all_begin_fortran_wrapper(fh, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_write_all_begin_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_write_all_begin_fortran_wrapper(fh, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_write_all_begin__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_write_all_begin_fortran_wrapper(fh, buf, count, datatype, ierr); } /* ================= End Wrappers for MPI_File_write_all_begin ================= */ /* ================== C Wrappers for MPI_File_write_all_end ================== */ _EXTERN_C_ int PMPI_File_write_all_end(MPI_File fh, const void *buf, MPI_Status *status); _EXTERN_C_ int MPI_File_write_all_end(MPI_File fh, const void *buf, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_write_all_end(fh, buf, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_write_all_end =============== */ static void MPI_File_write_all_end_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_write_all_end((MPI_File)(*fh), (const void*)buf, (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_write_all_end(MPI_File_f2c(*fh), (const void*)buf, &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_WRITE_ALL_END(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_all_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_write_all_end(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_all_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_write_all_end_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_all_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_write_all_end__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_all_end_fortran_wrapper(fh, buf, status, ierr); } /* ================= End Wrappers for MPI_File_write_all_end ================= */ /* ================== C Wrappers for MPI_File_write_at ================== */ _EXTERN_C_ int PMPI_File_write_at(MPI_File fh, MPI_Offset offset, const void *buf, int count, MPI_Datatype datatype, MPI_Status *status); _EXTERN_C_ int MPI_File_write_at(MPI_File fh, MPI_Offset offset, const void *buf, int count, MPI_Datatype datatype, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_write_at(fh, offset, buf, count, datatype, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_write_at =============== */ static void MPI_File_write_at_fortran_wrapper(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_write_at((MPI_File)(*fh), *offset, (const void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_write_at(MPI_File_f2c(*fh), *offset, (const void*)buf, *count, MPI_Type_f2c(*datatype), &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_WRITE_AT(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_at_fortran_wrapper(fh, offset, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write_at(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_at_fortran_wrapper(fh, offset, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write_at_(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_at_fortran_wrapper(fh, offset, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write_at__(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_at_fortran_wrapper(fh, offset, buf, count, datatype, status, ierr); } /* ================= End Wrappers for MPI_File_write_at ================= */ /* ================== C Wrappers for MPI_File_write_at_all ================== */ _EXTERN_C_ int PMPI_File_write_at_all(MPI_File fh, MPI_Offset offset, const void *buf, int count, MPI_Datatype datatype, MPI_Status *status); _EXTERN_C_ int MPI_File_write_at_all(MPI_File fh, MPI_Offset offset, const void *buf, int count, MPI_Datatype datatype, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_write_at_all(fh, offset, buf, count, datatype, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_write_at_all =============== */ static void MPI_File_write_at_all_fortran_wrapper(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_write_at_all((MPI_File)(*fh), *offset, (const void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_write_at_all(MPI_File_f2c(*fh), *offset, (const void*)buf, *count, MPI_Type_f2c(*datatype), &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_WRITE_AT_ALL(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_at_all_fortran_wrapper(fh, offset, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write_at_all(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_at_all_fortran_wrapper(fh, offset, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write_at_all_(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_at_all_fortran_wrapper(fh, offset, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write_at_all__(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_at_all_fortran_wrapper(fh, offset, buf, count, datatype, status, ierr); } /* ================= End Wrappers for MPI_File_write_at_all ================= */ /* ================== C Wrappers for MPI_File_write_at_all_begin ================== */ _EXTERN_C_ int PMPI_File_write_at_all_begin(MPI_File fh, MPI_Offset offset, const void *buf, int count, MPI_Datatype datatype); _EXTERN_C_ int MPI_File_write_at_all_begin(MPI_File fh, MPI_Offset offset, const void *buf, int count, MPI_Datatype datatype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_write_at_all_begin(fh, offset, buf, count, datatype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_write_at_all_begin =============== */ static void MPI_File_write_at_all_begin_fortran_wrapper(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_write_at_all_begin((MPI_File)(*fh), *offset, (const void*)buf, *count, (MPI_Datatype)(*datatype)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_write_at_all_begin(MPI_File_f2c(*fh), *offset, (const void*)buf, *count, MPI_Type_f2c(*datatype)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_WRITE_AT_ALL_BEGIN(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_write_at_all_begin_fortran_wrapper(fh, offset, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_write_at_all_begin(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_write_at_all_begin_fortran_wrapper(fh, offset, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_write_at_all_begin_(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_write_at_all_begin_fortran_wrapper(fh, offset, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_write_at_all_begin__(MPI_Fint *fh, MPI_Fint *offset, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_write_at_all_begin_fortran_wrapper(fh, offset, buf, count, datatype, ierr); } /* ================= End Wrappers for MPI_File_write_at_all_begin ================= */ /* ================== C Wrappers for MPI_File_write_at_all_end ================== */ _EXTERN_C_ int PMPI_File_write_at_all_end(MPI_File fh, const void *buf, MPI_Status *status); _EXTERN_C_ int MPI_File_write_at_all_end(MPI_File fh, const void *buf, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_write_at_all_end(fh, buf, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_write_at_all_end =============== */ static void MPI_File_write_at_all_end_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_write_at_all_end((MPI_File)(*fh), (const void*)buf, (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_write_at_all_end(MPI_File_f2c(*fh), (const void*)buf, &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_WRITE_AT_ALL_END(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_at_all_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_write_at_all_end(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_at_all_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_write_at_all_end_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_at_all_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_write_at_all_end__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_at_all_end_fortran_wrapper(fh, buf, status, ierr); } /* ================= End Wrappers for MPI_File_write_at_all_end ================= */ /* ================== C Wrappers for MPI_File_write_ordered ================== */ _EXTERN_C_ int PMPI_File_write_ordered(MPI_File fh, const void *buf, int count, MPI_Datatype datatype, MPI_Status *status); _EXTERN_C_ int MPI_File_write_ordered(MPI_File fh, const void *buf, int count, MPI_Datatype datatype, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_write_ordered(fh, buf, count, datatype, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_write_ordered =============== */ static void MPI_File_write_ordered_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_write_ordered((MPI_File)(*fh), (const void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_write_ordered(MPI_File_f2c(*fh), (const void*)buf, *count, MPI_Type_f2c(*datatype), &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_WRITE_ORDERED(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_ordered_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write_ordered(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_ordered_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write_ordered_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_ordered_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write_ordered__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_ordered_fortran_wrapper(fh, buf, count, datatype, status, ierr); } /* ================= End Wrappers for MPI_File_write_ordered ================= */ /* ================== C Wrappers for MPI_File_write_ordered_begin ================== */ _EXTERN_C_ int PMPI_File_write_ordered_begin(MPI_File fh, const void *buf, int count, MPI_Datatype datatype); _EXTERN_C_ int MPI_File_write_ordered_begin(MPI_File fh, const void *buf, int count, MPI_Datatype datatype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_write_ordered_begin(fh, buf, count, datatype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_write_ordered_begin =============== */ static void MPI_File_write_ordered_begin_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_write_ordered_begin((MPI_File)(*fh), (const void*)buf, *count, (MPI_Datatype)(*datatype)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_File_write_ordered_begin(MPI_File_f2c(*fh), (const void*)buf, *count, MPI_Type_f2c(*datatype)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_WRITE_ORDERED_BEGIN(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_write_ordered_begin_fortran_wrapper(fh, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_write_ordered_begin(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_write_ordered_begin_fortran_wrapper(fh, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_write_ordered_begin_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_write_ordered_begin_fortran_wrapper(fh, buf, count, datatype, ierr); } _EXTERN_C_ void mpi_file_write_ordered_begin__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_File_write_ordered_begin_fortran_wrapper(fh, buf, count, datatype, ierr); } /* ================= End Wrappers for MPI_File_write_ordered_begin ================= */ /* ================== C Wrappers for MPI_File_write_ordered_end ================== */ _EXTERN_C_ int PMPI_File_write_ordered_end(MPI_File fh, const void *buf, MPI_Status *status); _EXTERN_C_ int MPI_File_write_ordered_end(MPI_File fh, const void *buf, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_write_ordered_end(fh, buf, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_write_ordered_end =============== */ static void MPI_File_write_ordered_end_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_write_ordered_end((MPI_File)(*fh), (const void*)buf, (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_write_ordered_end(MPI_File_f2c(*fh), (const void*)buf, &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_WRITE_ORDERED_END(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_ordered_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_write_ordered_end(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_ordered_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_write_ordered_end_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_ordered_end_fortran_wrapper(fh, buf, status, ierr); } _EXTERN_C_ void mpi_file_write_ordered_end__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_ordered_end_fortran_wrapper(fh, buf, status, ierr); } /* ================= End Wrappers for MPI_File_write_ordered_end ================= */ /* ================== C Wrappers for MPI_File_write_shared ================== */ _EXTERN_C_ int PMPI_File_write_shared(MPI_File fh, const void *buf, int count, MPI_Datatype datatype, MPI_Status *status); _EXTERN_C_ int MPI_File_write_shared(MPI_File fh, const void *buf, int count, MPI_Datatype datatype, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_File_write_shared(fh, buf, count, datatype, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_File_write_shared =============== */ static void MPI_File_write_shared_fortran_wrapper(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_File_write_shared((MPI_File)(*fh), (const void*)buf, *count, (MPI_Datatype)(*datatype), (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_File_write_shared(MPI_File_f2c(*fh), (const void*)buf, *count, MPI_Type_f2c(*datatype), &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FILE_WRITE_SHARED(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_shared_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write_shared(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_shared_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write_shared_(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_shared_fortran_wrapper(fh, buf, count, datatype, status, ierr); } _EXTERN_C_ void mpi_file_write_shared__(MPI_Fint *fh, MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *status, MPI_Fint *ierr) { MPI_File_write_shared_fortran_wrapper(fh, buf, count, datatype, status, ierr); } /* ================= End Wrappers for MPI_File_write_shared ================= */ /* ================== C Wrappers for MPI_Finalize ================== */ _EXTERN_C_ int PMPI_Finalize(); _EXTERN_C_ int MPI_Finalize() { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX rw_tape_free(); if (NULL != backend_finalize) { backend_finalize(); } if (NULL != wrapper_backend_handle) { dlclose(wrapper_backend_handle); wrapper_backend_handle = NULL; } _wrap_py_return_val = PMPI_Finalize(); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Finalize =============== */ static void MPI_Finalize_fortran_wrapper(MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Finalize(); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FINALIZE(MPI_Fint *ierr) { MPI_Finalize_fortran_wrapper(ierr); } _EXTERN_C_ void mpi_finalize(MPI_Fint *ierr) { MPI_Finalize_fortran_wrapper(ierr); } _EXTERN_C_ void mpi_finalize_(MPI_Fint *ierr) { MPI_Finalize_fortran_wrapper(ierr); } _EXTERN_C_ void mpi_finalize__(MPI_Fint *ierr) { MPI_Finalize_fortran_wrapper(ierr); } /* ================= End Wrappers for MPI_Finalize ================= */ /* ================== C Wrappers for MPI_Finalized ================== */ _EXTERN_C_ int PMPI_Finalized(int *flag); _EXTERN_C_ int MPI_Finalized(int *flag) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Finalized(flag); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Finalized =============== */ static void MPI_Finalized_fortran_wrapper(MPI_Fint *flag, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Finalized((int*)flag); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FINALIZED(MPI_Fint *flag, MPI_Fint *ierr) { MPI_Finalized_fortran_wrapper(flag, ierr); } _EXTERN_C_ void mpi_finalized(MPI_Fint *flag, MPI_Fint *ierr) { MPI_Finalized_fortran_wrapper(flag, ierr); } _EXTERN_C_ void mpi_finalized_(MPI_Fint *flag, MPI_Fint *ierr) { MPI_Finalized_fortran_wrapper(flag, ierr); } _EXTERN_C_ void mpi_finalized__(MPI_Fint *flag, MPI_Fint *ierr) { MPI_Finalized_fortran_wrapper(flag, ierr); } /* ================= End Wrappers for MPI_Finalized ================= */ /* ================== C Wrappers for MPI_Free_mem ================== */ _EXTERN_C_ int PMPI_Free_mem(void *base); _EXTERN_C_ int MPI_Free_mem(void *base) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Free_mem(base); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Free_mem =============== */ static void MPI_Free_mem_fortran_wrapper(MPI_Fint *base, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Free_mem((void*)base); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_FREE_MEM(MPI_Fint *base, MPI_Fint *ierr) { MPI_Free_mem_fortran_wrapper(base, ierr); } _EXTERN_C_ void mpi_free_mem(MPI_Fint *base, MPI_Fint *ierr) { MPI_Free_mem_fortran_wrapper(base, ierr); } _EXTERN_C_ void mpi_free_mem_(MPI_Fint *base, MPI_Fint *ierr) { MPI_Free_mem_fortran_wrapper(base, ierr); } _EXTERN_C_ void mpi_free_mem__(MPI_Fint *base, MPI_Fint *ierr) { MPI_Free_mem_fortran_wrapper(base, ierr); } /* ================= End Wrappers for MPI_Free_mem ================= */ /* ================== C Wrappers for MPI_Gather ================== */ _EXTERN_C_ int PMPI_Gather(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm); _EXTERN_C_ int MPI_Gather(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Gather(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Gather =============== */ static void MPI_Gather_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Gather((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, *recvcount, (MPI_Datatype)(*recvtype), *root, (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Gather((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, *recvcount, MPI_Type_f2c(*recvtype), *root, MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GATHER(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Gather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, ierr); } _EXTERN_C_ void mpi_gather(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Gather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, ierr); } _EXTERN_C_ void mpi_gather_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Gather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, ierr); } _EXTERN_C_ void mpi_gather__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Gather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, ierr); } /* ================= End Wrappers for MPI_Gather ================= */ /* ================== C Wrappers for MPI_Gatherv ================== */ _EXTERN_C_ int PMPI_Gatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int displs[], MPI_Datatype recvtype, int root, MPI_Comm comm); _EXTERN_C_ int MPI_Gatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int displs[], MPI_Datatype recvtype, int root, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Gatherv(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, root, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Gatherv =============== */ static void MPI_Gatherv_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Gatherv((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)displs, (MPI_Datatype)(*recvtype), *root, (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Gatherv((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)displs, MPI_Type_f2c(*recvtype), *root, MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GATHERV(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Gatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, root, comm, ierr); } _EXTERN_C_ void mpi_gatherv(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Gatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, root, comm, ierr); } _EXTERN_C_ void mpi_gatherv_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Gatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, root, comm, ierr); } _EXTERN_C_ void mpi_gatherv__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Gatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, root, comm, ierr); } /* ================= End Wrappers for MPI_Gatherv ================= */ /* ================== C Wrappers for MPI_Get ================== */ _EXTERN_C_ int PMPI_Get(void *origin_addr, int origin_count, MPI_Datatype origin_datatype, int target_rank, MPI_Aint target_disp, int target_count, MPI_Datatype target_datatype, MPI_Win win); _EXTERN_C_ int MPI_Get(void *origin_addr, int origin_count, MPI_Datatype origin_datatype, int target_rank, MPI_Aint target_disp, int target_count, MPI_Datatype target_datatype, MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Get(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Get =============== */ static void MPI_Get_fortran_wrapper(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Get((void*)origin_addr, *origin_count, (MPI_Datatype)(*origin_datatype), *target_rank, *target_disp, *target_count, (MPI_Datatype)(*target_datatype), (MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Get((void*)origin_addr, *origin_count, MPI_Type_f2c(*origin_datatype), *target_rank, *target_disp, *target_count, MPI_Type_f2c(*target_datatype), MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GET(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *ierr) { MPI_Get_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, win, ierr); } _EXTERN_C_ void mpi_get(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *ierr) { MPI_Get_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, win, ierr); } _EXTERN_C_ void mpi_get_(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *ierr) { MPI_Get_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, win, ierr); } _EXTERN_C_ void mpi_get__(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *ierr) { MPI_Get_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, win, ierr); } /* ================= End Wrappers for MPI_Get ================= */ /* ================== C Wrappers for MPI_Get_accumulate ================== */ _EXTERN_C_ int PMPI_Get_accumulate(const void *origin_addr, int origin_count, MPI_Datatype origin_datatype, void *result_addr, int result_count, MPI_Datatype result_datatype, int target_rank, MPI_Aint target_disp, int target_count, MPI_Datatype target_datatype, MPI_Op op, MPI_Win win); _EXTERN_C_ int MPI_Get_accumulate(const void *origin_addr, int origin_count, MPI_Datatype origin_datatype, void *result_addr, int result_count, MPI_Datatype result_datatype, int target_rank, MPI_Aint target_disp, int target_count, MPI_Datatype target_datatype, MPI_Op op, MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Get_accumulate(origin_addr, origin_count, origin_datatype, result_addr, result_count, result_datatype, target_rank, target_disp, target_count, target_datatype, op, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Get_accumulate =============== */ static void MPI_Get_accumulate_fortran_wrapper(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *result_addr, MPI_Fint *result_count, MPI_Fint *result_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Get_accumulate((const void*)origin_addr, *origin_count, (MPI_Datatype)(*origin_datatype), (void*)result_addr, *result_count, (MPI_Datatype)(*result_datatype), *target_rank, *target_disp, *target_count, (MPI_Datatype)(*target_datatype), (MPI_Op)(*op), (MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Get_accumulate((const void*)origin_addr, *origin_count, MPI_Type_f2c(*origin_datatype), (void*)result_addr, *result_count, MPI_Type_f2c(*result_datatype), *target_rank, *target_disp, *target_count, MPI_Type_f2c(*target_datatype), MPI_Op_f2c(*op), MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GET_ACCUMULATE(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *result_addr, MPI_Fint *result_count, MPI_Fint *result_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *ierr) { MPI_Get_accumulate_fortran_wrapper(origin_addr, origin_count, origin_datatype, result_addr, result_count, result_datatype, target_rank, target_disp, target_count, target_datatype, op, win, ierr); } _EXTERN_C_ void mpi_get_accumulate(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *result_addr, MPI_Fint *result_count, MPI_Fint *result_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *ierr) { MPI_Get_accumulate_fortran_wrapper(origin_addr, origin_count, origin_datatype, result_addr, result_count, result_datatype, target_rank, target_disp, target_count, target_datatype, op, win, ierr); } _EXTERN_C_ void mpi_get_accumulate_(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *result_addr, MPI_Fint *result_count, MPI_Fint *result_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *ierr) { MPI_Get_accumulate_fortran_wrapper(origin_addr, origin_count, origin_datatype, result_addr, result_count, result_datatype, target_rank, target_disp, target_count, target_datatype, op, win, ierr); } _EXTERN_C_ void mpi_get_accumulate__(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *result_addr, MPI_Fint *result_count, MPI_Fint *result_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *ierr) { MPI_Get_accumulate_fortran_wrapper(origin_addr, origin_count, origin_datatype, result_addr, result_count, result_datatype, target_rank, target_disp, target_count, target_datatype, op, win, ierr); } /* ================= End Wrappers for MPI_Get_accumulate ================= */ /* ================== C Wrappers for MPI_Get_address ================== */ _EXTERN_C_ int PMPI_Get_address(const void *location, MPI_Aint *address); _EXTERN_C_ int MPI_Get_address(const void *location, MPI_Aint *address) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Get_address(location, address); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Get_address =============== */ static void MPI_Get_address_fortran_wrapper(MPI_Fint *location, MPI_Aint *address, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Get_address((const void*)location, (MPI_Aint*)address); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GET_ADDRESS(MPI_Fint *location, MPI_Aint *address, MPI_Fint *ierr) { MPI_Get_address_fortran_wrapper(location, address, ierr); } _EXTERN_C_ void mpi_get_address(MPI_Fint *location, MPI_Aint *address, MPI_Fint *ierr) { MPI_Get_address_fortran_wrapper(location, address, ierr); } _EXTERN_C_ void mpi_get_address_(MPI_Fint *location, MPI_Aint *address, MPI_Fint *ierr) { MPI_Get_address_fortran_wrapper(location, address, ierr); } _EXTERN_C_ void mpi_get_address__(MPI_Fint *location, MPI_Aint *address, MPI_Fint *ierr) { MPI_Get_address_fortran_wrapper(location, address, ierr); } /* ================= End Wrappers for MPI_Get_address ================= */ /* ================== C Wrappers for MPI_Get_count ================== */ _EXTERN_C_ int PMPI_Get_count(const MPI_Status *status, MPI_Datatype datatype, int *count); _EXTERN_C_ int MPI_Get_count(const MPI_Status *status, MPI_Datatype datatype, int *count) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Get_count(status, datatype, count); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Get_count =============== */ static void MPI_Get_count_fortran_wrapper(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Get_count((const MPI_Status*)status, (MPI_Datatype)(*datatype), (int*)count); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Get_count((const MPI_Status*)status, MPI_Type_f2c(*datatype), (int*)count); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GET_COUNT(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Get_count_fortran_wrapper(status, datatype, count, ierr); } _EXTERN_C_ void mpi_get_count(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Get_count_fortran_wrapper(status, datatype, count, ierr); } _EXTERN_C_ void mpi_get_count_(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Get_count_fortran_wrapper(status, datatype, count, ierr); } _EXTERN_C_ void mpi_get_count__(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Get_count_fortran_wrapper(status, datatype, count, ierr); } /* ================= End Wrappers for MPI_Get_count ================= */ /* ================== C Wrappers for MPI_Get_elements ================== */ _EXTERN_C_ int PMPI_Get_elements(const MPI_Status *status, MPI_Datatype datatype, int *count); _EXTERN_C_ int MPI_Get_elements(const MPI_Status *status, MPI_Datatype datatype, int *count) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Get_elements(status, datatype, count); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Get_elements =============== */ static void MPI_Get_elements_fortran_wrapper(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Get_elements((const MPI_Status*)status, (MPI_Datatype)(*datatype), (int*)count); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Get_elements((const MPI_Status*)status, MPI_Type_f2c(*datatype), (int*)count); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GET_ELEMENTS(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Get_elements_fortran_wrapper(status, datatype, count, ierr); } _EXTERN_C_ void mpi_get_elements(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Get_elements_fortran_wrapper(status, datatype, count, ierr); } _EXTERN_C_ void mpi_get_elements_(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Get_elements_fortran_wrapper(status, datatype, count, ierr); } _EXTERN_C_ void mpi_get_elements__(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Get_elements_fortran_wrapper(status, datatype, count, ierr); } /* ================= End Wrappers for MPI_Get_elements ================= */ /* ================== C Wrappers for MPI_Get_elements_x ================== */ _EXTERN_C_ int PMPI_Get_elements_x(const MPI_Status *status, MPI_Datatype datatype, MPI_Count *count); _EXTERN_C_ int MPI_Get_elements_x(const MPI_Status *status, MPI_Datatype datatype, MPI_Count *count) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Get_elements_x(status, datatype, count); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Get_elements_x =============== */ static void MPI_Get_elements_x_fortran_wrapper(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Get_elements_x((const MPI_Status*)status, (MPI_Datatype)(*datatype), (MPI_Count*)count); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Get_elements_x((const MPI_Status*)status, MPI_Type_f2c(*datatype), (MPI_Count*)count); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GET_ELEMENTS_X(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Get_elements_x_fortran_wrapper(status, datatype, count, ierr); } _EXTERN_C_ void mpi_get_elements_x(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Get_elements_x_fortran_wrapper(status, datatype, count, ierr); } _EXTERN_C_ void mpi_get_elements_x_(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Get_elements_x_fortran_wrapper(status, datatype, count, ierr); } _EXTERN_C_ void mpi_get_elements_x__(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Get_elements_x_fortran_wrapper(status, datatype, count, ierr); } /* ================= End Wrappers for MPI_Get_elements_x ================= */ /* ================== C Wrappers for MPI_Get_library_version ================== */ _EXTERN_C_ int PMPI_Get_library_version(char *version, int *resultlen); _EXTERN_C_ int MPI_Get_library_version(char *version, int *resultlen) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Get_library_version(version, resultlen); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Get_library_version =============== */ static void MPI_Get_library_version_fortran_wrapper(MPI_Fint *version, MPI_Fint *resultlen, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Get_library_version((char*)version, (int*)resultlen); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GET_LIBRARY_VERSION(MPI_Fint *version, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Get_library_version_fortran_wrapper(version, resultlen, ierr); } _EXTERN_C_ void mpi_get_library_version(MPI_Fint *version, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Get_library_version_fortran_wrapper(version, resultlen, ierr); } _EXTERN_C_ void mpi_get_library_version_(MPI_Fint *version, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Get_library_version_fortran_wrapper(version, resultlen, ierr); } _EXTERN_C_ void mpi_get_library_version__(MPI_Fint *version, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Get_library_version_fortran_wrapper(version, resultlen, ierr); } /* ================= End Wrappers for MPI_Get_library_version ================= */ /* ================== C Wrappers for MPI_Get_processor_name ================== */ _EXTERN_C_ int PMPI_Get_processor_name(char *name, int *resultlen); _EXTERN_C_ int MPI_Get_processor_name(char *name, int *resultlen) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Get_processor_name(name, resultlen); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Get_processor_name =============== */ static void MPI_Get_processor_name_fortran_wrapper(MPI_Fint *name, MPI_Fint *resultlen, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Get_processor_name((char*)name, (int*)resultlen); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GET_PROCESSOR_NAME(MPI_Fint *name, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Get_processor_name_fortran_wrapper(name, resultlen, ierr); } _EXTERN_C_ void mpi_get_processor_name(MPI_Fint *name, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Get_processor_name_fortran_wrapper(name, resultlen, ierr); } _EXTERN_C_ void mpi_get_processor_name_(MPI_Fint *name, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Get_processor_name_fortran_wrapper(name, resultlen, ierr); } _EXTERN_C_ void mpi_get_processor_name__(MPI_Fint *name, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Get_processor_name_fortran_wrapper(name, resultlen, ierr); } /* ================= End Wrappers for MPI_Get_processor_name ================= */ /* ================== C Wrappers for MPI_Get_version ================== */ _EXTERN_C_ int PMPI_Get_version(int *version, int *subversion); _EXTERN_C_ int MPI_Get_version(int *version, int *subversion) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Get_version(version, subversion); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Get_version =============== */ static void MPI_Get_version_fortran_wrapper(MPI_Fint *version, MPI_Fint *subversion, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Get_version((int*)version, (int*)subversion); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GET_VERSION(MPI_Fint *version, MPI_Fint *subversion, MPI_Fint *ierr) { MPI_Get_version_fortran_wrapper(version, subversion, ierr); } _EXTERN_C_ void mpi_get_version(MPI_Fint *version, MPI_Fint *subversion, MPI_Fint *ierr) { MPI_Get_version_fortran_wrapper(version, subversion, ierr); } _EXTERN_C_ void mpi_get_version_(MPI_Fint *version, MPI_Fint *subversion, MPI_Fint *ierr) { MPI_Get_version_fortran_wrapper(version, subversion, ierr); } _EXTERN_C_ void mpi_get_version__(MPI_Fint *version, MPI_Fint *subversion, MPI_Fint *ierr) { MPI_Get_version_fortran_wrapper(version, subversion, ierr); } /* ================= End Wrappers for MPI_Get_version ================= */ /* ================== C Wrappers for MPI_Graph_create ================== */ _EXTERN_C_ int PMPI_Graph_create(MPI_Comm comm_old, int nnodes, const int index[], const int edges[], int reorder, MPI_Comm *comm_graph); _EXTERN_C_ int MPI_Graph_create(MPI_Comm comm_old, int nnodes, const int index[], const int edges[], int reorder, MPI_Comm *comm_graph) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Graph_create(comm_old, nnodes, index, edges, reorder, comm_graph); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Graph_create =============== */ static void MPI_Graph_create_fortran_wrapper(MPI_Fint *comm_old, MPI_Fint *nnodes, MPI_Fint index[], MPI_Fint edges[], MPI_Fint *reorder, MPI_Fint *comm_graph, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Graph_create((MPI_Comm)(*comm_old), *nnodes, (const int*)index, (const int*)edges, *reorder, (MPI_Comm*)comm_graph); #else /* MPI-2 safe call */ MPI_Comm temp_comm_graph; temp_comm_graph = MPI_Comm_f2c(*comm_graph); _wrap_py_return_val = MPI_Graph_create(MPI_Comm_f2c(*comm_old), *nnodes, (const int*)index, (const int*)edges, *reorder, &temp_comm_graph); *comm_graph = MPI_Comm_c2f(temp_comm_graph); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GRAPH_CREATE(MPI_Fint *comm_old, MPI_Fint *nnodes, MPI_Fint index[], MPI_Fint edges[], MPI_Fint *reorder, MPI_Fint *comm_graph, MPI_Fint *ierr) { MPI_Graph_create_fortran_wrapper(comm_old, nnodes, index, edges, reorder, comm_graph, ierr); } _EXTERN_C_ void mpi_graph_create(MPI_Fint *comm_old, MPI_Fint *nnodes, MPI_Fint index[], MPI_Fint edges[], MPI_Fint *reorder, MPI_Fint *comm_graph, MPI_Fint *ierr) { MPI_Graph_create_fortran_wrapper(comm_old, nnodes, index, edges, reorder, comm_graph, ierr); } _EXTERN_C_ void mpi_graph_create_(MPI_Fint *comm_old, MPI_Fint *nnodes, MPI_Fint index[], MPI_Fint edges[], MPI_Fint *reorder, MPI_Fint *comm_graph, MPI_Fint *ierr) { MPI_Graph_create_fortran_wrapper(comm_old, nnodes, index, edges, reorder, comm_graph, ierr); } _EXTERN_C_ void mpi_graph_create__(MPI_Fint *comm_old, MPI_Fint *nnodes, MPI_Fint index[], MPI_Fint edges[], MPI_Fint *reorder, MPI_Fint *comm_graph, MPI_Fint *ierr) { MPI_Graph_create_fortran_wrapper(comm_old, nnodes, index, edges, reorder, comm_graph, ierr); } /* ================= End Wrappers for MPI_Graph_create ================= */ /* ================== C Wrappers for MPI_Graph_get ================== */ _EXTERN_C_ int PMPI_Graph_get(MPI_Comm comm, int maxindex, int maxedges, int index[], int edges[]); _EXTERN_C_ int MPI_Graph_get(MPI_Comm comm, int maxindex, int maxedges, int index[], int edges[]) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Graph_get(comm, maxindex, maxedges, index, edges); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Graph_get =============== */ static void MPI_Graph_get_fortran_wrapper(MPI_Fint *comm, MPI_Fint *maxindex, MPI_Fint *maxedges, MPI_Fint index[], MPI_Fint edges[], MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Graph_get((MPI_Comm)(*comm), *maxindex, *maxedges, (int*)index, (int*)edges); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Graph_get(MPI_Comm_f2c(*comm), *maxindex, *maxedges, (int*)index, (int*)edges); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GRAPH_GET(MPI_Fint *comm, MPI_Fint *maxindex, MPI_Fint *maxedges, MPI_Fint index[], MPI_Fint edges[], MPI_Fint *ierr) { MPI_Graph_get_fortran_wrapper(comm, maxindex, maxedges, index, edges, ierr); } _EXTERN_C_ void mpi_graph_get(MPI_Fint *comm, MPI_Fint *maxindex, MPI_Fint *maxedges, MPI_Fint index[], MPI_Fint edges[], MPI_Fint *ierr) { MPI_Graph_get_fortran_wrapper(comm, maxindex, maxedges, index, edges, ierr); } _EXTERN_C_ void mpi_graph_get_(MPI_Fint *comm, MPI_Fint *maxindex, MPI_Fint *maxedges, MPI_Fint index[], MPI_Fint edges[], MPI_Fint *ierr) { MPI_Graph_get_fortran_wrapper(comm, maxindex, maxedges, index, edges, ierr); } _EXTERN_C_ void mpi_graph_get__(MPI_Fint *comm, MPI_Fint *maxindex, MPI_Fint *maxedges, MPI_Fint index[], MPI_Fint edges[], MPI_Fint *ierr) { MPI_Graph_get_fortran_wrapper(comm, maxindex, maxedges, index, edges, ierr); } /* ================= End Wrappers for MPI_Graph_get ================= */ /* ================== C Wrappers for MPI_Graph_map ================== */ _EXTERN_C_ int PMPI_Graph_map(MPI_Comm comm, int nnodes, const int index[], const int edges[], int *newrank); _EXTERN_C_ int MPI_Graph_map(MPI_Comm comm, int nnodes, const int index[], const int edges[], int *newrank) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Graph_map(comm, nnodes, index, edges, newrank); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Graph_map =============== */ static void MPI_Graph_map_fortran_wrapper(MPI_Fint *comm, MPI_Fint *nnodes, MPI_Fint index[], MPI_Fint edges[], MPI_Fint *newrank, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Graph_map((MPI_Comm)(*comm), *nnodes, (const int*)index, (const int*)edges, (int*)newrank); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Graph_map(MPI_Comm_f2c(*comm), *nnodes, (const int*)index, (const int*)edges, (int*)newrank); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GRAPH_MAP(MPI_Fint *comm, MPI_Fint *nnodes, MPI_Fint index[], MPI_Fint edges[], MPI_Fint *newrank, MPI_Fint *ierr) { MPI_Graph_map_fortran_wrapper(comm, nnodes, index, edges, newrank, ierr); } _EXTERN_C_ void mpi_graph_map(MPI_Fint *comm, MPI_Fint *nnodes, MPI_Fint index[], MPI_Fint edges[], MPI_Fint *newrank, MPI_Fint *ierr) { MPI_Graph_map_fortran_wrapper(comm, nnodes, index, edges, newrank, ierr); } _EXTERN_C_ void mpi_graph_map_(MPI_Fint *comm, MPI_Fint *nnodes, MPI_Fint index[], MPI_Fint edges[], MPI_Fint *newrank, MPI_Fint *ierr) { MPI_Graph_map_fortran_wrapper(comm, nnodes, index, edges, newrank, ierr); } _EXTERN_C_ void mpi_graph_map__(MPI_Fint *comm, MPI_Fint *nnodes, MPI_Fint index[], MPI_Fint edges[], MPI_Fint *newrank, MPI_Fint *ierr) { MPI_Graph_map_fortran_wrapper(comm, nnodes, index, edges, newrank, ierr); } /* ================= End Wrappers for MPI_Graph_map ================= */ /* ================== C Wrappers for MPI_Graph_neighbors ================== */ _EXTERN_C_ int PMPI_Graph_neighbors(MPI_Comm comm, int rank, int maxneighbors, int neighbors[]); _EXTERN_C_ int MPI_Graph_neighbors(MPI_Comm comm, int rank, int maxneighbors, int neighbors[]) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Graph_neighbors(comm, rank, maxneighbors, neighbors); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Graph_neighbors =============== */ static void MPI_Graph_neighbors_fortran_wrapper(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *maxneighbors, MPI_Fint neighbors[], MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Graph_neighbors((MPI_Comm)(*comm), *rank, *maxneighbors, (int*)neighbors); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Graph_neighbors(MPI_Comm_f2c(*comm), *rank, *maxneighbors, (int*)neighbors); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GRAPH_NEIGHBORS(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *maxneighbors, MPI_Fint neighbors[], MPI_Fint *ierr) { MPI_Graph_neighbors_fortran_wrapper(comm, rank, maxneighbors, neighbors, ierr); } _EXTERN_C_ void mpi_graph_neighbors(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *maxneighbors, MPI_Fint neighbors[], MPI_Fint *ierr) { MPI_Graph_neighbors_fortran_wrapper(comm, rank, maxneighbors, neighbors, ierr); } _EXTERN_C_ void mpi_graph_neighbors_(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *maxneighbors, MPI_Fint neighbors[], MPI_Fint *ierr) { MPI_Graph_neighbors_fortran_wrapper(comm, rank, maxneighbors, neighbors, ierr); } _EXTERN_C_ void mpi_graph_neighbors__(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *maxneighbors, MPI_Fint neighbors[], MPI_Fint *ierr) { MPI_Graph_neighbors_fortran_wrapper(comm, rank, maxneighbors, neighbors, ierr); } /* ================= End Wrappers for MPI_Graph_neighbors ================= */ /* ================== C Wrappers for MPI_Graph_neighbors_count ================== */ _EXTERN_C_ int PMPI_Graph_neighbors_count(MPI_Comm comm, int rank, int *nneighbors); _EXTERN_C_ int MPI_Graph_neighbors_count(MPI_Comm comm, int rank, int *nneighbors) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Graph_neighbors_count(comm, rank, nneighbors); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Graph_neighbors_count =============== */ static void MPI_Graph_neighbors_count_fortran_wrapper(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *nneighbors, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Graph_neighbors_count((MPI_Comm)(*comm), *rank, (int*)nneighbors); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Graph_neighbors_count(MPI_Comm_f2c(*comm), *rank, (int*)nneighbors); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GRAPH_NEIGHBORS_COUNT(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *nneighbors, MPI_Fint *ierr) { MPI_Graph_neighbors_count_fortran_wrapper(comm, rank, nneighbors, ierr); } _EXTERN_C_ void mpi_graph_neighbors_count(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *nneighbors, MPI_Fint *ierr) { MPI_Graph_neighbors_count_fortran_wrapper(comm, rank, nneighbors, ierr); } _EXTERN_C_ void mpi_graph_neighbors_count_(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *nneighbors, MPI_Fint *ierr) { MPI_Graph_neighbors_count_fortran_wrapper(comm, rank, nneighbors, ierr); } _EXTERN_C_ void mpi_graph_neighbors_count__(MPI_Fint *comm, MPI_Fint *rank, MPI_Fint *nneighbors, MPI_Fint *ierr) { MPI_Graph_neighbors_count_fortran_wrapper(comm, rank, nneighbors, ierr); } /* ================= End Wrappers for MPI_Graph_neighbors_count ================= */ /* ================== C Wrappers for MPI_Graphdims_get ================== */ _EXTERN_C_ int PMPI_Graphdims_get(MPI_Comm comm, int *nnodes, int *nedges); _EXTERN_C_ int MPI_Graphdims_get(MPI_Comm comm, int *nnodes, int *nedges) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Graphdims_get(comm, nnodes, nedges); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Graphdims_get =============== */ static void MPI_Graphdims_get_fortran_wrapper(MPI_Fint *comm, MPI_Fint *nnodes, MPI_Fint *nedges, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Graphdims_get((MPI_Comm)(*comm), (int*)nnodes, (int*)nedges); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Graphdims_get(MPI_Comm_f2c(*comm), (int*)nnodes, (int*)nedges); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GRAPHDIMS_GET(MPI_Fint *comm, MPI_Fint *nnodes, MPI_Fint *nedges, MPI_Fint *ierr) { MPI_Graphdims_get_fortran_wrapper(comm, nnodes, nedges, ierr); } _EXTERN_C_ void mpi_graphdims_get(MPI_Fint *comm, MPI_Fint *nnodes, MPI_Fint *nedges, MPI_Fint *ierr) { MPI_Graphdims_get_fortran_wrapper(comm, nnodes, nedges, ierr); } _EXTERN_C_ void mpi_graphdims_get_(MPI_Fint *comm, MPI_Fint *nnodes, MPI_Fint *nedges, MPI_Fint *ierr) { MPI_Graphdims_get_fortran_wrapper(comm, nnodes, nedges, ierr); } _EXTERN_C_ void mpi_graphdims_get__(MPI_Fint *comm, MPI_Fint *nnodes, MPI_Fint *nedges, MPI_Fint *ierr) { MPI_Graphdims_get_fortran_wrapper(comm, nnodes, nedges, ierr); } /* ================= End Wrappers for MPI_Graphdims_get ================= */ /* ================== C Wrappers for MPI_Grequest_complete ================== */ _EXTERN_C_ int PMPI_Grequest_complete(MPI_Request request); _EXTERN_C_ int MPI_Grequest_complete(MPI_Request request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Grequest_complete(request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Grequest_complete =============== */ static void MPI_Grequest_complete_fortran_wrapper(MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Grequest_complete((MPI_Request)(*request)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Grequest_complete(MPI_Request_f2c(*request)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GREQUEST_COMPLETE(MPI_Fint *request, MPI_Fint *ierr) { MPI_Grequest_complete_fortran_wrapper(request, ierr); } _EXTERN_C_ void mpi_grequest_complete(MPI_Fint *request, MPI_Fint *ierr) { MPI_Grequest_complete_fortran_wrapper(request, ierr); } _EXTERN_C_ void mpi_grequest_complete_(MPI_Fint *request, MPI_Fint *ierr) { MPI_Grequest_complete_fortran_wrapper(request, ierr); } _EXTERN_C_ void mpi_grequest_complete__(MPI_Fint *request, MPI_Fint *ierr) { MPI_Grequest_complete_fortran_wrapper(request, ierr); } /* ================= End Wrappers for MPI_Grequest_complete ================= */ /* ================== C Wrappers for MPI_Grequest_start ================== */ _EXTERN_C_ int PMPI_Grequest_start(MPI_Grequest_query_function *query_fn, MPI_Grequest_free_function *free_fn, MPI_Grequest_cancel_function *cancel_fn, void *extra_state, MPI_Request *request); _EXTERN_C_ int MPI_Grequest_start(MPI_Grequest_query_function *query_fn, MPI_Grequest_free_function *free_fn, MPI_Grequest_cancel_function *cancel_fn, void *extra_state, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Grequest_start(query_fn, free_fn, cancel_fn, extra_state, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Grequest_start =============== */ static void MPI_Grequest_start_fortran_wrapper(MPI_Grequest_query_function *query_fn, MPI_Grequest_free_function *free_fn, MPI_Grequest_cancel_function *cancel_fn, MPI_Fint *extra_state, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Grequest_start((MPI_Grequest_query_function*)query_fn, (MPI_Grequest_free_function*)free_fn, (MPI_Grequest_cancel_function*)cancel_fn, (void*)extra_state, (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Grequest_start((MPI_Grequest_query_function*)query_fn, (MPI_Grequest_free_function*)free_fn, (MPI_Grequest_cancel_function*)cancel_fn, (void*)extra_state, &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GREQUEST_START(MPI_Grequest_query_function *query_fn, MPI_Grequest_free_function *free_fn, MPI_Grequest_cancel_function *cancel_fn, MPI_Fint *extra_state, MPI_Fint *request, MPI_Fint *ierr) { MPI_Grequest_start_fortran_wrapper(query_fn, free_fn, cancel_fn, extra_state, request, ierr); } _EXTERN_C_ void mpi_grequest_start(MPI_Grequest_query_function *query_fn, MPI_Grequest_free_function *free_fn, MPI_Grequest_cancel_function *cancel_fn, MPI_Fint *extra_state, MPI_Fint *request, MPI_Fint *ierr) { MPI_Grequest_start_fortran_wrapper(query_fn, free_fn, cancel_fn, extra_state, request, ierr); } _EXTERN_C_ void mpi_grequest_start_(MPI_Grequest_query_function *query_fn, MPI_Grequest_free_function *free_fn, MPI_Grequest_cancel_function *cancel_fn, MPI_Fint *extra_state, MPI_Fint *request, MPI_Fint *ierr) { MPI_Grequest_start_fortran_wrapper(query_fn, free_fn, cancel_fn, extra_state, request, ierr); } _EXTERN_C_ void mpi_grequest_start__(MPI_Grequest_query_function *query_fn, MPI_Grequest_free_function *free_fn, MPI_Grequest_cancel_function *cancel_fn, MPI_Fint *extra_state, MPI_Fint *request, MPI_Fint *ierr) { MPI_Grequest_start_fortran_wrapper(query_fn, free_fn, cancel_fn, extra_state, request, ierr); } /* ================= End Wrappers for MPI_Grequest_start ================= */ /* ================== C Wrappers for MPI_Group_compare ================== */ _EXTERN_C_ int PMPI_Group_compare(MPI_Group group1, MPI_Group group2, int *result); _EXTERN_C_ int MPI_Group_compare(MPI_Group group1, MPI_Group group2, int *result) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Group_compare(group1, group2, result); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Group_compare =============== */ static void MPI_Group_compare_fortran_wrapper(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *result, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Group_compare((MPI_Group)(*group1), (MPI_Group)(*group2), (int*)result); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Group_compare(MPI_Group_f2c(*group1), MPI_Group_f2c(*group2), (int*)result); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GROUP_COMPARE(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *result, MPI_Fint *ierr) { MPI_Group_compare_fortran_wrapper(group1, group2, result, ierr); } _EXTERN_C_ void mpi_group_compare(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *result, MPI_Fint *ierr) { MPI_Group_compare_fortran_wrapper(group1, group2, result, ierr); } _EXTERN_C_ void mpi_group_compare_(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *result, MPI_Fint *ierr) { MPI_Group_compare_fortran_wrapper(group1, group2, result, ierr); } _EXTERN_C_ void mpi_group_compare__(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *result, MPI_Fint *ierr) { MPI_Group_compare_fortran_wrapper(group1, group2, result, ierr); } /* ================= End Wrappers for MPI_Group_compare ================= */ /* ================== C Wrappers for MPI_Group_difference ================== */ _EXTERN_C_ int PMPI_Group_difference(MPI_Group group1, MPI_Group group2, MPI_Group *newgroup); _EXTERN_C_ int MPI_Group_difference(MPI_Group group1, MPI_Group group2, MPI_Group *newgroup) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Group_difference(group1, group2, newgroup); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Group_difference =============== */ static void MPI_Group_difference_fortran_wrapper(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *newgroup, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Group_difference((MPI_Group)(*group1), (MPI_Group)(*group2), (MPI_Group*)newgroup); #else /* MPI-2 safe call */ MPI_Group temp_newgroup; temp_newgroup = MPI_Group_f2c(*newgroup); _wrap_py_return_val = MPI_Group_difference(MPI_Group_f2c(*group1), MPI_Group_f2c(*group2), &temp_newgroup); *newgroup = MPI_Group_c2f(temp_newgroup); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GROUP_DIFFERENCE(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_difference_fortran_wrapper(group1, group2, newgroup, ierr); } _EXTERN_C_ void mpi_group_difference(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_difference_fortran_wrapper(group1, group2, newgroup, ierr); } _EXTERN_C_ void mpi_group_difference_(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_difference_fortran_wrapper(group1, group2, newgroup, ierr); } _EXTERN_C_ void mpi_group_difference__(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_difference_fortran_wrapper(group1, group2, newgroup, ierr); } /* ================= End Wrappers for MPI_Group_difference ================= */ /* ================== C Wrappers for MPI_Group_excl ================== */ _EXTERN_C_ int PMPI_Group_excl(MPI_Group group, int n, const int ranks[], MPI_Group *newgroup); _EXTERN_C_ int MPI_Group_excl(MPI_Group group, int n, const int ranks[], MPI_Group *newgroup) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Group_excl(group, n, ranks, newgroup); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Group_excl =============== */ static void MPI_Group_excl_fortran_wrapper(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranks[], MPI_Fint *newgroup, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Group_excl((MPI_Group)(*group), *n, (const int*)ranks, (MPI_Group*)newgroup); #else /* MPI-2 safe call */ MPI_Group temp_newgroup; temp_newgroup = MPI_Group_f2c(*newgroup); _wrap_py_return_val = MPI_Group_excl(MPI_Group_f2c(*group), *n, (const int*)ranks, &temp_newgroup); *newgroup = MPI_Group_c2f(temp_newgroup); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GROUP_EXCL(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranks[], MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_excl_fortran_wrapper(group, n, ranks, newgroup, ierr); } _EXTERN_C_ void mpi_group_excl(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranks[], MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_excl_fortran_wrapper(group, n, ranks, newgroup, ierr); } _EXTERN_C_ void mpi_group_excl_(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranks[], MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_excl_fortran_wrapper(group, n, ranks, newgroup, ierr); } _EXTERN_C_ void mpi_group_excl__(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranks[], MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_excl_fortran_wrapper(group, n, ranks, newgroup, ierr); } /* ================= End Wrappers for MPI_Group_excl ================= */ /* ================== C Wrappers for MPI_Group_free ================== */ _EXTERN_C_ int PMPI_Group_free(MPI_Group *group); _EXTERN_C_ int MPI_Group_free(MPI_Group *group) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Group_free(group); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Group_free =============== */ static void MPI_Group_free_fortran_wrapper(MPI_Fint *group, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Group_free((MPI_Group*)group); #else /* MPI-2 safe call */ MPI_Group temp_group; temp_group = MPI_Group_f2c(*group); _wrap_py_return_val = MPI_Group_free(&temp_group); *group = MPI_Group_c2f(temp_group); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GROUP_FREE(MPI_Fint *group, MPI_Fint *ierr) { MPI_Group_free_fortran_wrapper(group, ierr); } _EXTERN_C_ void mpi_group_free(MPI_Fint *group, MPI_Fint *ierr) { MPI_Group_free_fortran_wrapper(group, ierr); } _EXTERN_C_ void mpi_group_free_(MPI_Fint *group, MPI_Fint *ierr) { MPI_Group_free_fortran_wrapper(group, ierr); } _EXTERN_C_ void mpi_group_free__(MPI_Fint *group, MPI_Fint *ierr) { MPI_Group_free_fortran_wrapper(group, ierr); } /* ================= End Wrappers for MPI_Group_free ================= */ /* ================== C Wrappers for MPI_Group_incl ================== */ _EXTERN_C_ int PMPI_Group_incl(MPI_Group group, int n, const int ranks[], MPI_Group *newgroup); _EXTERN_C_ int MPI_Group_incl(MPI_Group group, int n, const int ranks[], MPI_Group *newgroup) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Group_incl(group, n, ranks, newgroup); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Group_incl =============== */ static void MPI_Group_incl_fortran_wrapper(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranks[], MPI_Fint *newgroup, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Group_incl((MPI_Group)(*group), *n, (const int*)ranks, (MPI_Group*)newgroup); #else /* MPI-2 safe call */ MPI_Group temp_newgroup; temp_newgroup = MPI_Group_f2c(*newgroup); _wrap_py_return_val = MPI_Group_incl(MPI_Group_f2c(*group), *n, (const int*)ranks, &temp_newgroup); *newgroup = MPI_Group_c2f(temp_newgroup); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GROUP_INCL(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranks[], MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_incl_fortran_wrapper(group, n, ranks, newgroup, ierr); } _EXTERN_C_ void mpi_group_incl(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranks[], MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_incl_fortran_wrapper(group, n, ranks, newgroup, ierr); } _EXTERN_C_ void mpi_group_incl_(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranks[], MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_incl_fortran_wrapper(group, n, ranks, newgroup, ierr); } _EXTERN_C_ void mpi_group_incl__(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranks[], MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_incl_fortran_wrapper(group, n, ranks, newgroup, ierr); } /* ================= End Wrappers for MPI_Group_incl ================= */ /* ================== C Wrappers for MPI_Group_intersection ================== */ _EXTERN_C_ int PMPI_Group_intersection(MPI_Group group1, MPI_Group group2, MPI_Group *newgroup); _EXTERN_C_ int MPI_Group_intersection(MPI_Group group1, MPI_Group group2, MPI_Group *newgroup) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Group_intersection(group1, group2, newgroup); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Group_intersection =============== */ static void MPI_Group_intersection_fortran_wrapper(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *newgroup, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Group_intersection((MPI_Group)(*group1), (MPI_Group)(*group2), (MPI_Group*)newgroup); #else /* MPI-2 safe call */ MPI_Group temp_newgroup; temp_newgroup = MPI_Group_f2c(*newgroup); _wrap_py_return_val = MPI_Group_intersection(MPI_Group_f2c(*group1), MPI_Group_f2c(*group2), &temp_newgroup); *newgroup = MPI_Group_c2f(temp_newgroup); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GROUP_INTERSECTION(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_intersection_fortran_wrapper(group1, group2, newgroup, ierr); } _EXTERN_C_ void mpi_group_intersection(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_intersection_fortran_wrapper(group1, group2, newgroup, ierr); } _EXTERN_C_ void mpi_group_intersection_(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_intersection_fortran_wrapper(group1, group2, newgroup, ierr); } _EXTERN_C_ void mpi_group_intersection__(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_intersection_fortran_wrapper(group1, group2, newgroup, ierr); } /* ================= End Wrappers for MPI_Group_intersection ================= */ /* ================== C Wrappers for MPI_Group_range_excl ================== */ _EXTERN_C_ int PMPI_Group_range_excl(MPI_Group group, int n, int ranges[][3], MPI_Group *newgroup); _EXTERN_C_ int MPI_Group_range_excl(MPI_Group group, int n, int ranges[][3], MPI_Group *newgroup) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Group_range_excl(group, n, ranges, newgroup); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Group_range_excl =============== */ static void MPI_Group_range_excl_fortran_wrapper(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranges[][3], MPI_Fint *newgroup, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Group_range_excl((MPI_Group)(*group), *n, (int(*)[3])ranges, (MPI_Group*)newgroup); #else /* MPI-2 safe call */ MPI_Group temp_newgroup; temp_newgroup = MPI_Group_f2c(*newgroup); _wrap_py_return_val = MPI_Group_range_excl(MPI_Group_f2c(*group), *n, (int(*)[3])ranges, &temp_newgroup); *newgroup = MPI_Group_c2f(temp_newgroup); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GROUP_RANGE_EXCL(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranges[][3], MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_range_excl_fortran_wrapper(group, n, ranges, newgroup, ierr); } _EXTERN_C_ void mpi_group_range_excl(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranges[][3], MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_range_excl_fortran_wrapper(group, n, ranges, newgroup, ierr); } _EXTERN_C_ void mpi_group_range_excl_(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranges[][3], MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_range_excl_fortran_wrapper(group, n, ranges, newgroup, ierr); } _EXTERN_C_ void mpi_group_range_excl__(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranges[][3], MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_range_excl_fortran_wrapper(group, n, ranges, newgroup, ierr); } /* ================= End Wrappers for MPI_Group_range_excl ================= */ /* ================== C Wrappers for MPI_Group_range_incl ================== */ _EXTERN_C_ int PMPI_Group_range_incl(MPI_Group group, int n, int ranges[][3], MPI_Group *newgroup); _EXTERN_C_ int MPI_Group_range_incl(MPI_Group group, int n, int ranges[][3], MPI_Group *newgroup) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Group_range_incl(group, n, ranges, newgroup); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Group_range_incl =============== */ static void MPI_Group_range_incl_fortran_wrapper(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranges[][3], MPI_Fint *newgroup, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Group_range_incl((MPI_Group)(*group), *n, (int(*)[3])ranges, (MPI_Group*)newgroup); #else /* MPI-2 safe call */ MPI_Group temp_newgroup; temp_newgroup = MPI_Group_f2c(*newgroup); _wrap_py_return_val = MPI_Group_range_incl(MPI_Group_f2c(*group), *n, (int(*)[3])ranges, &temp_newgroup); *newgroup = MPI_Group_c2f(temp_newgroup); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GROUP_RANGE_INCL(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranges[][3], MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_range_incl_fortran_wrapper(group, n, ranges, newgroup, ierr); } _EXTERN_C_ void mpi_group_range_incl(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranges[][3], MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_range_incl_fortran_wrapper(group, n, ranges, newgroup, ierr); } _EXTERN_C_ void mpi_group_range_incl_(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranges[][3], MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_range_incl_fortran_wrapper(group, n, ranges, newgroup, ierr); } _EXTERN_C_ void mpi_group_range_incl__(MPI_Fint *group, MPI_Fint *n, MPI_Fint ranges[][3], MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_range_incl_fortran_wrapper(group, n, ranges, newgroup, ierr); } /* ================= End Wrappers for MPI_Group_range_incl ================= */ /* ================== C Wrappers for MPI_Group_rank ================== */ _EXTERN_C_ int PMPI_Group_rank(MPI_Group group, int *rank); _EXTERN_C_ int MPI_Group_rank(MPI_Group group, int *rank) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Group_rank(group, rank); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Group_rank =============== */ static void MPI_Group_rank_fortran_wrapper(MPI_Fint *group, MPI_Fint *rank, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Group_rank((MPI_Group)(*group), (int*)rank); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Group_rank(MPI_Group_f2c(*group), (int*)rank); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GROUP_RANK(MPI_Fint *group, MPI_Fint *rank, MPI_Fint *ierr) { MPI_Group_rank_fortran_wrapper(group, rank, ierr); } _EXTERN_C_ void mpi_group_rank(MPI_Fint *group, MPI_Fint *rank, MPI_Fint *ierr) { MPI_Group_rank_fortran_wrapper(group, rank, ierr); } _EXTERN_C_ void mpi_group_rank_(MPI_Fint *group, MPI_Fint *rank, MPI_Fint *ierr) { MPI_Group_rank_fortran_wrapper(group, rank, ierr); } _EXTERN_C_ void mpi_group_rank__(MPI_Fint *group, MPI_Fint *rank, MPI_Fint *ierr) { MPI_Group_rank_fortran_wrapper(group, rank, ierr); } /* ================= End Wrappers for MPI_Group_rank ================= */ /* ================== C Wrappers for MPI_Group_size ================== */ _EXTERN_C_ int PMPI_Group_size(MPI_Group group, int *size); _EXTERN_C_ int MPI_Group_size(MPI_Group group, int *size) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Group_size(group, size); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Group_size =============== */ static void MPI_Group_size_fortran_wrapper(MPI_Fint *group, MPI_Fint *size, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Group_size((MPI_Group)(*group), (int*)size); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Group_size(MPI_Group_f2c(*group), (int*)size); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GROUP_SIZE(MPI_Fint *group, MPI_Fint *size, MPI_Fint *ierr) { MPI_Group_size_fortran_wrapper(group, size, ierr); } _EXTERN_C_ void mpi_group_size(MPI_Fint *group, MPI_Fint *size, MPI_Fint *ierr) { MPI_Group_size_fortran_wrapper(group, size, ierr); } _EXTERN_C_ void mpi_group_size_(MPI_Fint *group, MPI_Fint *size, MPI_Fint *ierr) { MPI_Group_size_fortran_wrapper(group, size, ierr); } _EXTERN_C_ void mpi_group_size__(MPI_Fint *group, MPI_Fint *size, MPI_Fint *ierr) { MPI_Group_size_fortran_wrapper(group, size, ierr); } /* ================= End Wrappers for MPI_Group_size ================= */ /* ================== C Wrappers for MPI_Group_translate_ranks ================== */ _EXTERN_C_ int PMPI_Group_translate_ranks(MPI_Group group1, int n, const int ranks1[], MPI_Group group2, int ranks2[]); _EXTERN_C_ int MPI_Group_translate_ranks(MPI_Group group1, int n, const int ranks1[], MPI_Group group2, int ranks2[]) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Group_translate_ranks(group1, n, ranks1, group2, ranks2); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Group_translate_ranks =============== */ static void MPI_Group_translate_ranks_fortran_wrapper(MPI_Fint *group1, MPI_Fint *n, MPI_Fint ranks1[], MPI_Fint *group2, MPI_Fint ranks2[], MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Group_translate_ranks((MPI_Group)(*group1), *n, (const int*)ranks1, (MPI_Group)(*group2), (int*)ranks2); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Group_translate_ranks(MPI_Group_f2c(*group1), *n, (const int*)ranks1, MPI_Group_f2c(*group2), (int*)ranks2); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GROUP_TRANSLATE_RANKS(MPI_Fint *group1, MPI_Fint *n, MPI_Fint ranks1[], MPI_Fint *group2, MPI_Fint ranks2[], MPI_Fint *ierr) { MPI_Group_translate_ranks_fortran_wrapper(group1, n, ranks1, group2, ranks2, ierr); } _EXTERN_C_ void mpi_group_translate_ranks(MPI_Fint *group1, MPI_Fint *n, MPI_Fint ranks1[], MPI_Fint *group2, MPI_Fint ranks2[], MPI_Fint *ierr) { MPI_Group_translate_ranks_fortran_wrapper(group1, n, ranks1, group2, ranks2, ierr); } _EXTERN_C_ void mpi_group_translate_ranks_(MPI_Fint *group1, MPI_Fint *n, MPI_Fint ranks1[], MPI_Fint *group2, MPI_Fint ranks2[], MPI_Fint *ierr) { MPI_Group_translate_ranks_fortran_wrapper(group1, n, ranks1, group2, ranks2, ierr); } _EXTERN_C_ void mpi_group_translate_ranks__(MPI_Fint *group1, MPI_Fint *n, MPI_Fint ranks1[], MPI_Fint *group2, MPI_Fint ranks2[], MPI_Fint *ierr) { MPI_Group_translate_ranks_fortran_wrapper(group1, n, ranks1, group2, ranks2, ierr); } /* ================= End Wrappers for MPI_Group_translate_ranks ================= */ /* ================== C Wrappers for MPI_Group_union ================== */ _EXTERN_C_ int PMPI_Group_union(MPI_Group group1, MPI_Group group2, MPI_Group *newgroup); _EXTERN_C_ int MPI_Group_union(MPI_Group group1, MPI_Group group2, MPI_Group *newgroup) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Group_union(group1, group2, newgroup); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Group_union =============== */ static void MPI_Group_union_fortran_wrapper(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *newgroup, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Group_union((MPI_Group)(*group1), (MPI_Group)(*group2), (MPI_Group*)newgroup); #else /* MPI-2 safe call */ MPI_Group temp_newgroup; temp_newgroup = MPI_Group_f2c(*newgroup); _wrap_py_return_val = MPI_Group_union(MPI_Group_f2c(*group1), MPI_Group_f2c(*group2), &temp_newgroup); *newgroup = MPI_Group_c2f(temp_newgroup); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_GROUP_UNION(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_union_fortran_wrapper(group1, group2, newgroup, ierr); } _EXTERN_C_ void mpi_group_union(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_union_fortran_wrapper(group1, group2, newgroup, ierr); } _EXTERN_C_ void mpi_group_union_(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_union_fortran_wrapper(group1, group2, newgroup, ierr); } _EXTERN_C_ void mpi_group_union__(MPI_Fint *group1, MPI_Fint *group2, MPI_Fint *newgroup, MPI_Fint *ierr) { MPI_Group_union_fortran_wrapper(group1, group2, newgroup, ierr); } /* ================= End Wrappers for MPI_Group_union ================= */ /* ================== C Wrappers for MPI_Iallgather ================== */ _EXTERN_C_ int PMPI_Iallgather(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Iallgather(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Iallgather(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Iallgather =============== */ static void MPI_Iallgather_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Iallgather((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, *recvcount, (MPI_Datatype)(*recvtype), (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Iallgather((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, *recvcount, MPI_Type_f2c(*recvtype), MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IALLGATHER(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iallgather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_iallgather(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iallgather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_iallgather_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iallgather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_iallgather__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iallgather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, ierr); } /* ================= End Wrappers for MPI_Iallgather ================= */ /* ================== C Wrappers for MPI_Iallgatherv ================== */ _EXTERN_C_ int PMPI_Iallgatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int displs[], MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Iallgatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int displs[], MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Iallgatherv(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Iallgatherv =============== */ static void MPI_Iallgatherv_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Iallgatherv((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)displs, (MPI_Datatype)(*recvtype), (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Iallgatherv((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)displs, MPI_Type_f2c(*recvtype), MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IALLGATHERV(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iallgatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_iallgatherv(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iallgatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_iallgatherv_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iallgatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_iallgatherv__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iallgatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, request, ierr); } /* ================= End Wrappers for MPI_Iallgatherv ================= */ /* ================== C Wrappers for MPI_Iallreduce ================== */ _EXTERN_C_ int PMPI_Iallreduce(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Iallreduce(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Iallreduce(sendbuf, recvbuf, count, datatype, op, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Iallreduce =============== */ static void MPI_Iallreduce_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Iallreduce((const void*)sendbuf, (void*)recvbuf, *count, (MPI_Datatype)(*datatype), (MPI_Op)(*op), (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Iallreduce((const void*)sendbuf, (void*)recvbuf, *count, MPI_Type_f2c(*datatype), MPI_Op_f2c(*op), MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IALLREDUCE(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iallreduce_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, request, ierr); } _EXTERN_C_ void mpi_iallreduce(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iallreduce_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, request, ierr); } _EXTERN_C_ void mpi_iallreduce_(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iallreduce_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, request, ierr); } _EXTERN_C_ void mpi_iallreduce__(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iallreduce_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, request, ierr); } /* ================= End Wrappers for MPI_Iallreduce ================= */ /* ================== C Wrappers for MPI_Ialltoall ================== */ _EXTERN_C_ int PMPI_Ialltoall(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Ialltoall(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Ialltoall(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Ialltoall =============== */ static void MPI_Ialltoall_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Ialltoall((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, *recvcount, (MPI_Datatype)(*recvtype), (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Ialltoall((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, *recvcount, MPI_Type_f2c(*recvtype), MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IALLTOALL(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ialltoall_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ialltoall(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ialltoall_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ialltoall_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ialltoall_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ialltoall__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ialltoall_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, ierr); } /* ================= End Wrappers for MPI_Ialltoall ================= */ /* ================== C Wrappers for MPI_Ialltoallv ================== */ _EXTERN_C_ int PMPI_Ialltoallv(const void *sendbuf, const int sendcounts[], const int sdispls[], MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int rdispls[], MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Ialltoallv(const void *sendbuf, const int sendcounts[], const int sdispls[], MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int rdispls[], MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Ialltoallv(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Ialltoallv =============== */ static void MPI_Ialltoallv_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Ialltoallv((const void*)sendbuf, (const int*)sendcounts, (const int*)sdispls, (MPI_Datatype)(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)rdispls, (MPI_Datatype)(*recvtype), (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Ialltoallv((const void*)sendbuf, (const int*)sendcounts, (const int*)sdispls, MPI_Type_f2c(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)rdispls, MPI_Type_f2c(*recvtype), MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IALLTOALLV(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ialltoallv_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ialltoallv(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ialltoallv_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ialltoallv_(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ialltoallv_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ialltoallv__(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ialltoallv_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, request, ierr); } /* ================= End Wrappers for MPI_Ialltoallv ================= */ /* ================== C Wrappers for MPI_Ialltoallw ================== */ _EXTERN_C_ int PMPI_Ialltoallw(const void *sendbuf, const int sendcounts[], const int sdispls[], const MPI_Datatype sendtypes[], void *recvbuf, const int recvcounts[], const int rdispls[], const MPI_Datatype recvtypes[], MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Ialltoallw(const void *sendbuf, const int sendcounts[], const int sdispls[], const MPI_Datatype sendtypes[], void *recvbuf, const int recvcounts[], const int rdispls[], const MPI_Datatype recvtypes[], MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Ialltoallw(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Ialltoallw =============== */ static void MPI_Ialltoallw_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Ialltoallw((const void*)sendbuf, (const int*)sendcounts, (const int*)sdispls, (const MPI_Datatype*)sendtypes, (void*)recvbuf, (const int*)recvcounts, (const int*)rdispls, (const MPI_Datatype*)recvtypes, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Ialltoallw((const void*)sendbuf, (const int*)sendcounts, (const int*)sdispls, (const MPI_Datatype*)sendtypes, (void*)recvbuf, (const int*)recvcounts, (const int*)rdispls, (const MPI_Datatype*)recvtypes, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IALLTOALLW(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ialltoallw_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, request, ierr); } _EXTERN_C_ void mpi_ialltoallw(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ialltoallw_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, request, ierr); } _EXTERN_C_ void mpi_ialltoallw_(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ialltoallw_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, request, ierr); } _EXTERN_C_ void mpi_ialltoallw__(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ialltoallw_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, request, ierr); } /* ================= End Wrappers for MPI_Ialltoallw ================= */ /* ================== C Wrappers for MPI_Ibarrier ================== */ _EXTERN_C_ int PMPI_Ibarrier(MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Ibarrier(MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Ibarrier(comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Ibarrier =============== */ static void MPI_Ibarrier_fortran_wrapper(MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Ibarrier((MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Ibarrier(MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IBARRIER(MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ibarrier_fortran_wrapper(comm, request, ierr); } _EXTERN_C_ void mpi_ibarrier(MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ibarrier_fortran_wrapper(comm, request, ierr); } _EXTERN_C_ void mpi_ibarrier_(MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ibarrier_fortran_wrapper(comm, request, ierr); } _EXTERN_C_ void mpi_ibarrier__(MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ibarrier_fortran_wrapper(comm, request, ierr); } /* ================= End Wrappers for MPI_Ibarrier ================= */ /* ================== C Wrappers for MPI_Ibcast ================== */ _EXTERN_C_ int PMPI_Ibcast(void *buffer, int count, MPI_Datatype datatype, int root, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Ibcast(void *buffer, int count, MPI_Datatype datatype, int root, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Ibcast(buffer, count, datatype, root, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Ibcast =============== */ static void MPI_Ibcast_fortran_wrapper(MPI_Fint *buffer, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Ibcast((void*)buffer, *count, (MPI_Datatype)(*datatype), *root, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Ibcast((void*)buffer, *count, MPI_Type_f2c(*datatype), *root, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IBCAST(MPI_Fint *buffer, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ibcast_fortran_wrapper(buffer, count, datatype, root, comm, request, ierr); } _EXTERN_C_ void mpi_ibcast(MPI_Fint *buffer, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ibcast_fortran_wrapper(buffer, count, datatype, root, comm, request, ierr); } _EXTERN_C_ void mpi_ibcast_(MPI_Fint *buffer, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ibcast_fortran_wrapper(buffer, count, datatype, root, comm, request, ierr); } _EXTERN_C_ void mpi_ibcast__(MPI_Fint *buffer, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ibcast_fortran_wrapper(buffer, count, datatype, root, comm, request, ierr); } /* ================= End Wrappers for MPI_Ibcast ================= */ /* ================== C Wrappers for MPI_Ibsend ================== */ _EXTERN_C_ int PMPI_Ibsend(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Ibsend(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Ibsend(buf, count, datatype, dest, tag, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Ibsend =============== */ static void MPI_Ibsend_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Ibsend((const void*)buf, *count, (MPI_Datatype)(*datatype), *dest, *tag, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Ibsend((const void*)buf, *count, MPI_Type_f2c(*datatype), *dest, *tag, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IBSEND(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ibsend_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_ibsend(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ibsend_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_ibsend_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ibsend_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_ibsend__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ibsend_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } /* ================= End Wrappers for MPI_Ibsend ================= */ /* ================== C Wrappers for MPI_Iexscan ================== */ _EXTERN_C_ int PMPI_Iexscan(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Iexscan(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Iexscan(sendbuf, recvbuf, count, datatype, op, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Iexscan =============== */ static void MPI_Iexscan_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Iexscan((const void*)sendbuf, (void*)recvbuf, *count, (MPI_Datatype)(*datatype), (MPI_Op)(*op), (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Iexscan((const void*)sendbuf, (void*)recvbuf, *count, MPI_Type_f2c(*datatype), MPI_Op_f2c(*op), MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IEXSCAN(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iexscan_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, request, ierr); } _EXTERN_C_ void mpi_iexscan(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iexscan_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, request, ierr); } _EXTERN_C_ void mpi_iexscan_(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iexscan_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, request, ierr); } _EXTERN_C_ void mpi_iexscan__(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iexscan_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, request, ierr); } /* ================= End Wrappers for MPI_Iexscan ================= */ /* ================== C Wrappers for MPI_Igather ================== */ _EXTERN_C_ int PMPI_Igather(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Igather(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Igather(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Igather =============== */ static void MPI_Igather_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Igather((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, *recvcount, (MPI_Datatype)(*recvtype), *root, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Igather((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, *recvcount, MPI_Type_f2c(*recvtype), *root, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IGATHER(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Igather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, request, ierr); } _EXTERN_C_ void mpi_igather(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Igather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, request, ierr); } _EXTERN_C_ void mpi_igather_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Igather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, request, ierr); } _EXTERN_C_ void mpi_igather__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Igather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, request, ierr); } /* ================= End Wrappers for MPI_Igather ================= */ /* ================== C Wrappers for MPI_Igatherv ================== */ _EXTERN_C_ int PMPI_Igatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int displs[], MPI_Datatype recvtype, int root, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Igatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int displs[], MPI_Datatype recvtype, int root, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Igatherv(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, root, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Igatherv =============== */ static void MPI_Igatherv_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Igatherv((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)displs, (MPI_Datatype)(*recvtype), *root, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Igatherv((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)displs, MPI_Type_f2c(*recvtype), *root, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IGATHERV(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Igatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, root, comm, request, ierr); } _EXTERN_C_ void mpi_igatherv(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Igatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, root, comm, request, ierr); } _EXTERN_C_ void mpi_igatherv_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Igatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, root, comm, request, ierr); } _EXTERN_C_ void mpi_igatherv__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Igatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, root, comm, request, ierr); } /* ================= End Wrappers for MPI_Igatherv ================= */ /* ================== C Wrappers for MPI_Improbe ================== */ _EXTERN_C_ int PMPI_Improbe(int source, int tag, MPI_Comm comm, int *flag, MPI_Message *message, MPI_Status *status); _EXTERN_C_ int MPI_Improbe(int source, int tag, MPI_Comm comm, int *flag, MPI_Message *message, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Improbe(source, tag, comm, flag, message, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Improbe =============== */ static void MPI_Improbe_fortran_wrapper(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *flag, MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Improbe(*source, *tag, (MPI_Comm)(*comm), (int*)flag, (MPI_Message*)message, (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_Improbe(*source, *tag, MPI_Comm_f2c(*comm), (int*)flag, (MPI_Message*)message, &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IMPROBE(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *flag, MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr) { MPI_Improbe_fortran_wrapper(source, tag, comm, flag, message, status, ierr); } _EXTERN_C_ void mpi_improbe(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *flag, MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr) { MPI_Improbe_fortran_wrapper(source, tag, comm, flag, message, status, ierr); } _EXTERN_C_ void mpi_improbe_(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *flag, MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr) { MPI_Improbe_fortran_wrapper(source, tag, comm, flag, message, status, ierr); } _EXTERN_C_ void mpi_improbe__(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *flag, MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr) { MPI_Improbe_fortran_wrapper(source, tag, comm, flag, message, status, ierr); } /* ================= End Wrappers for MPI_Improbe ================= */ /* ================== C Wrappers for MPI_Imrecv ================== */ _EXTERN_C_ int PMPI_Imrecv(void *buf, int count, MPI_Datatype type, MPI_Message *message, MPI_Request *request); _EXTERN_C_ int MPI_Imrecv(void *buf, int count, MPI_Datatype type, MPI_Message *message, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Imrecv(buf, count, type, message, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Imrecv =============== */ static void MPI_Imrecv_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *type, MPI_Fint *message, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Imrecv((void*)buf, *count, (MPI_Datatype)(*type), (MPI_Message*)message, (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Imrecv((void*)buf, *count, MPI_Type_f2c(*type), (MPI_Message*)message, &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IMRECV(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *type, MPI_Fint *message, MPI_Fint *request, MPI_Fint *ierr) { MPI_Imrecv_fortran_wrapper(buf, count, type, message, request, ierr); } _EXTERN_C_ void mpi_imrecv(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *type, MPI_Fint *message, MPI_Fint *request, MPI_Fint *ierr) { MPI_Imrecv_fortran_wrapper(buf, count, type, message, request, ierr); } _EXTERN_C_ void mpi_imrecv_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *type, MPI_Fint *message, MPI_Fint *request, MPI_Fint *ierr) { MPI_Imrecv_fortran_wrapper(buf, count, type, message, request, ierr); } _EXTERN_C_ void mpi_imrecv__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *type, MPI_Fint *message, MPI_Fint *request, MPI_Fint *ierr) { MPI_Imrecv_fortran_wrapper(buf, count, type, message, request, ierr); } /* ================= End Wrappers for MPI_Imrecv ================= */ /* ================== C Wrappers for MPI_Ineighbor_allgather ================== */ _EXTERN_C_ int PMPI_Ineighbor_allgather(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Ineighbor_allgather(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Ineighbor_allgather(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Ineighbor_allgather =============== */ static void MPI_Ineighbor_allgather_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Ineighbor_allgather((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, *recvcount, (MPI_Datatype)(*recvtype), (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Ineighbor_allgather((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, *recvcount, MPI_Type_f2c(*recvtype), MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INEIGHBOR_ALLGATHER(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_allgather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ineighbor_allgather(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_allgather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ineighbor_allgather_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_allgather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ineighbor_allgather__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_allgather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, ierr); } /* ================= End Wrappers for MPI_Ineighbor_allgather ================= */ /* ================== C Wrappers for MPI_Ineighbor_allgatherv ================== */ _EXTERN_C_ int PMPI_Ineighbor_allgatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int displs[], MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Ineighbor_allgatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int displs[], MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Ineighbor_allgatherv(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Ineighbor_allgatherv =============== */ static void MPI_Ineighbor_allgatherv_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Ineighbor_allgatherv((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)displs, (MPI_Datatype)(*recvtype), (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Ineighbor_allgatherv((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)displs, MPI_Type_f2c(*recvtype), MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INEIGHBOR_ALLGATHERV(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_allgatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ineighbor_allgatherv(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_allgatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ineighbor_allgatherv_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_allgatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ineighbor_allgatherv__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_allgatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, request, ierr); } /* ================= End Wrappers for MPI_Ineighbor_allgatherv ================= */ /* ================== C Wrappers for MPI_Ineighbor_alltoall ================== */ _EXTERN_C_ int PMPI_Ineighbor_alltoall(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Ineighbor_alltoall(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Ineighbor_alltoall(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Ineighbor_alltoall =============== */ static void MPI_Ineighbor_alltoall_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Ineighbor_alltoall((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, *recvcount, (MPI_Datatype)(*recvtype), (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Ineighbor_alltoall((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, *recvcount, MPI_Type_f2c(*recvtype), MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INEIGHBOR_ALLTOALL(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_alltoall_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ineighbor_alltoall(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_alltoall_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ineighbor_alltoall_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_alltoall_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ineighbor_alltoall__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_alltoall_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, ierr); } /* ================= End Wrappers for MPI_Ineighbor_alltoall ================= */ /* ================== C Wrappers for MPI_Ineighbor_alltoallv ================== */ _EXTERN_C_ int PMPI_Ineighbor_alltoallv(const void *sendbuf, const int sendcounts[], const int sdispls[], MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int rdispls[], MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Ineighbor_alltoallv(const void *sendbuf, const int sendcounts[], const int sdispls[], MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int rdispls[], MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Ineighbor_alltoallv(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Ineighbor_alltoallv =============== */ static void MPI_Ineighbor_alltoallv_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Ineighbor_alltoallv((const void*)sendbuf, (const int*)sendcounts, (const int*)sdispls, (MPI_Datatype)(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)rdispls, (MPI_Datatype)(*recvtype), (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Ineighbor_alltoallv((const void*)sendbuf, (const int*)sendcounts, (const int*)sdispls, MPI_Type_f2c(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)rdispls, MPI_Type_f2c(*recvtype), MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INEIGHBOR_ALLTOALLV(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_alltoallv_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ineighbor_alltoallv(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_alltoallv_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ineighbor_alltoallv_(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_alltoallv_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, request, ierr); } _EXTERN_C_ void mpi_ineighbor_alltoallv__(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_alltoallv_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, request, ierr); } /* ================= End Wrappers for MPI_Ineighbor_alltoallv ================= */ /* ================== C Wrappers for MPI_Ineighbor_alltoallw ================== */ _EXTERN_C_ int PMPI_Ineighbor_alltoallw(const void *sendbuf, const int sendcounts[], const MPI_Aint sdispls[], const MPI_Datatype sendtypes[], void *recvbuf, const int recvcounts[], const MPI_Aint rdispls[], const MPI_Datatype recvtypes[], MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Ineighbor_alltoallw(const void *sendbuf, const int sendcounts[], const MPI_Aint sdispls[], const MPI_Datatype sendtypes[], void *recvbuf, const int recvcounts[], const MPI_Aint rdispls[], const MPI_Datatype recvtypes[], MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Ineighbor_alltoallw(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Ineighbor_alltoallw =============== */ static void MPI_Ineighbor_alltoallw_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Ineighbor_alltoallw((const void*)sendbuf, (const int*)sendcounts, (const MPI_Aint*)sdispls, (const MPI_Datatype*)sendtypes, (void*)recvbuf, (const int*)recvcounts, (const MPI_Aint*)rdispls, (const MPI_Datatype*)recvtypes, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Ineighbor_alltoallw((const void*)sendbuf, (const int*)sendcounts, (const MPI_Aint*)sdispls, (const MPI_Datatype*)sendtypes, (void*)recvbuf, (const int*)recvcounts, (const MPI_Aint*)rdispls, (const MPI_Datatype*)recvtypes, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INEIGHBOR_ALLTOALLW(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_alltoallw_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, request, ierr); } _EXTERN_C_ void mpi_ineighbor_alltoallw(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_alltoallw_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, request, ierr); } _EXTERN_C_ void mpi_ineighbor_alltoallw_(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_alltoallw_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, request, ierr); } _EXTERN_C_ void mpi_ineighbor_alltoallw__(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ineighbor_alltoallw_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, request, ierr); } /* ================= End Wrappers for MPI_Ineighbor_alltoallw ================= */ /* ================== C Wrappers for MPI_Info_create ================== */ _EXTERN_C_ int PMPI_Info_create(MPI_Info *info); _EXTERN_C_ int MPI_Info_create(MPI_Info *info) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Info_create(info); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Info_create =============== */ static void MPI_Info_create_fortran_wrapper(MPI_Fint *info, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Info_create((MPI_Info*)info); #else /* MPI-2 safe call */ MPI_Info temp_info; temp_info = MPI_Info_f2c(*info); _wrap_py_return_val = MPI_Info_create(&temp_info); *info = MPI_Info_c2f(temp_info); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INFO_CREATE(MPI_Fint *info, MPI_Fint *ierr) { MPI_Info_create_fortran_wrapper(info, ierr); } _EXTERN_C_ void mpi_info_create(MPI_Fint *info, MPI_Fint *ierr) { MPI_Info_create_fortran_wrapper(info, ierr); } _EXTERN_C_ void mpi_info_create_(MPI_Fint *info, MPI_Fint *ierr) { MPI_Info_create_fortran_wrapper(info, ierr); } _EXTERN_C_ void mpi_info_create__(MPI_Fint *info, MPI_Fint *ierr) { MPI_Info_create_fortran_wrapper(info, ierr); } /* ================= End Wrappers for MPI_Info_create ================= */ /* ================== C Wrappers for MPI_Info_delete ================== */ _EXTERN_C_ int PMPI_Info_delete(MPI_Info info, const char *key); _EXTERN_C_ int MPI_Info_delete(MPI_Info info, const char *key) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Info_delete(info, key); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Info_delete =============== */ static void MPI_Info_delete_fortran_wrapper(MPI_Fint *info, MPI_Fint *key, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Info_delete((MPI_Info)(*info), (const char*)key); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Info_delete(MPI_Info_f2c(*info), (const char*)key); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INFO_DELETE(MPI_Fint *info, MPI_Fint *key, MPI_Fint *ierr) { MPI_Info_delete_fortran_wrapper(info, key, ierr); } _EXTERN_C_ void mpi_info_delete(MPI_Fint *info, MPI_Fint *key, MPI_Fint *ierr) { MPI_Info_delete_fortran_wrapper(info, key, ierr); } _EXTERN_C_ void mpi_info_delete_(MPI_Fint *info, MPI_Fint *key, MPI_Fint *ierr) { MPI_Info_delete_fortran_wrapper(info, key, ierr); } _EXTERN_C_ void mpi_info_delete__(MPI_Fint *info, MPI_Fint *key, MPI_Fint *ierr) { MPI_Info_delete_fortran_wrapper(info, key, ierr); } /* ================= End Wrappers for MPI_Info_delete ================= */ /* ================== C Wrappers for MPI_Info_dup ================== */ _EXTERN_C_ int PMPI_Info_dup(MPI_Info info, MPI_Info *newinfo); _EXTERN_C_ int MPI_Info_dup(MPI_Info info, MPI_Info *newinfo) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Info_dup(info, newinfo); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Info_dup =============== */ static void MPI_Info_dup_fortran_wrapper(MPI_Fint *info, MPI_Fint *newinfo, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Info_dup((MPI_Info)(*info), (MPI_Info*)newinfo); #else /* MPI-2 safe call */ MPI_Info temp_newinfo; temp_newinfo = MPI_Info_f2c(*newinfo); _wrap_py_return_val = MPI_Info_dup(MPI_Info_f2c(*info), &temp_newinfo); *newinfo = MPI_Info_c2f(temp_newinfo); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INFO_DUP(MPI_Fint *info, MPI_Fint *newinfo, MPI_Fint *ierr) { MPI_Info_dup_fortran_wrapper(info, newinfo, ierr); } _EXTERN_C_ void mpi_info_dup(MPI_Fint *info, MPI_Fint *newinfo, MPI_Fint *ierr) { MPI_Info_dup_fortran_wrapper(info, newinfo, ierr); } _EXTERN_C_ void mpi_info_dup_(MPI_Fint *info, MPI_Fint *newinfo, MPI_Fint *ierr) { MPI_Info_dup_fortran_wrapper(info, newinfo, ierr); } _EXTERN_C_ void mpi_info_dup__(MPI_Fint *info, MPI_Fint *newinfo, MPI_Fint *ierr) { MPI_Info_dup_fortran_wrapper(info, newinfo, ierr); } /* ================= End Wrappers for MPI_Info_dup ================= */ /* ================== C Wrappers for MPI_Info_free ================== */ _EXTERN_C_ int PMPI_Info_free(MPI_Info *info); _EXTERN_C_ int MPI_Info_free(MPI_Info *info) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Info_free(info); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Info_free =============== */ static void MPI_Info_free_fortran_wrapper(MPI_Fint *info, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Info_free((MPI_Info*)info); #else /* MPI-2 safe call */ MPI_Info temp_info; temp_info = MPI_Info_f2c(*info); _wrap_py_return_val = MPI_Info_free(&temp_info); *info = MPI_Info_c2f(temp_info); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INFO_FREE(MPI_Fint *info, MPI_Fint *ierr) { MPI_Info_free_fortran_wrapper(info, ierr); } _EXTERN_C_ void mpi_info_free(MPI_Fint *info, MPI_Fint *ierr) { MPI_Info_free_fortran_wrapper(info, ierr); } _EXTERN_C_ void mpi_info_free_(MPI_Fint *info, MPI_Fint *ierr) { MPI_Info_free_fortran_wrapper(info, ierr); } _EXTERN_C_ void mpi_info_free__(MPI_Fint *info, MPI_Fint *ierr) { MPI_Info_free_fortran_wrapper(info, ierr); } /* ================= End Wrappers for MPI_Info_free ================= */ /* ================== C Wrappers for MPI_Info_get ================== */ _EXTERN_C_ int PMPI_Info_get(MPI_Info info, const char *key, int valuelen, char *value, int *flag); _EXTERN_C_ int MPI_Info_get(MPI_Info info, const char *key, int valuelen, char *value, int *flag) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Info_get(info, key, valuelen, value, flag); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Info_get =============== */ static void MPI_Info_get_fortran_wrapper(MPI_Fint *info, MPI_Fint *key, MPI_Fint *valuelen, MPI_Fint *value, MPI_Fint *flag, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Info_get((MPI_Info)(*info), (const char*)key, *valuelen, (char*)value, (int*)flag); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Info_get(MPI_Info_f2c(*info), (const char*)key, *valuelen, (char*)value, (int*)flag); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INFO_GET(MPI_Fint *info, MPI_Fint *key, MPI_Fint *valuelen, MPI_Fint *value, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Info_get_fortran_wrapper(info, key, valuelen, value, flag, ierr); } _EXTERN_C_ void mpi_info_get(MPI_Fint *info, MPI_Fint *key, MPI_Fint *valuelen, MPI_Fint *value, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Info_get_fortran_wrapper(info, key, valuelen, value, flag, ierr); } _EXTERN_C_ void mpi_info_get_(MPI_Fint *info, MPI_Fint *key, MPI_Fint *valuelen, MPI_Fint *value, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Info_get_fortran_wrapper(info, key, valuelen, value, flag, ierr); } _EXTERN_C_ void mpi_info_get__(MPI_Fint *info, MPI_Fint *key, MPI_Fint *valuelen, MPI_Fint *value, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Info_get_fortran_wrapper(info, key, valuelen, value, flag, ierr); } /* ================= End Wrappers for MPI_Info_get ================= */ /* ================== C Wrappers for MPI_Info_get_nkeys ================== */ _EXTERN_C_ int PMPI_Info_get_nkeys(MPI_Info info, int *nkeys); _EXTERN_C_ int MPI_Info_get_nkeys(MPI_Info info, int *nkeys) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Info_get_nkeys(info, nkeys); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Info_get_nkeys =============== */ static void MPI_Info_get_nkeys_fortran_wrapper(MPI_Fint *info, MPI_Fint *nkeys, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Info_get_nkeys((MPI_Info)(*info), (int*)nkeys); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Info_get_nkeys(MPI_Info_f2c(*info), (int*)nkeys); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INFO_GET_NKEYS(MPI_Fint *info, MPI_Fint *nkeys, MPI_Fint *ierr) { MPI_Info_get_nkeys_fortran_wrapper(info, nkeys, ierr); } _EXTERN_C_ void mpi_info_get_nkeys(MPI_Fint *info, MPI_Fint *nkeys, MPI_Fint *ierr) { MPI_Info_get_nkeys_fortran_wrapper(info, nkeys, ierr); } _EXTERN_C_ void mpi_info_get_nkeys_(MPI_Fint *info, MPI_Fint *nkeys, MPI_Fint *ierr) { MPI_Info_get_nkeys_fortran_wrapper(info, nkeys, ierr); } _EXTERN_C_ void mpi_info_get_nkeys__(MPI_Fint *info, MPI_Fint *nkeys, MPI_Fint *ierr) { MPI_Info_get_nkeys_fortran_wrapper(info, nkeys, ierr); } /* ================= End Wrappers for MPI_Info_get_nkeys ================= */ /* ================== C Wrappers for MPI_Info_get_nthkey ================== */ _EXTERN_C_ int PMPI_Info_get_nthkey(MPI_Info info, int n, char *key); _EXTERN_C_ int MPI_Info_get_nthkey(MPI_Info info, int n, char *key) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Info_get_nthkey(info, n, key); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Info_get_nthkey =============== */ static void MPI_Info_get_nthkey_fortran_wrapper(MPI_Fint *info, MPI_Fint *n, MPI_Fint *key, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Info_get_nthkey((MPI_Info)(*info), *n, (char*)key); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Info_get_nthkey(MPI_Info_f2c(*info), *n, (char*)key); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INFO_GET_NTHKEY(MPI_Fint *info, MPI_Fint *n, MPI_Fint *key, MPI_Fint *ierr) { MPI_Info_get_nthkey_fortran_wrapper(info, n, key, ierr); } _EXTERN_C_ void mpi_info_get_nthkey(MPI_Fint *info, MPI_Fint *n, MPI_Fint *key, MPI_Fint *ierr) { MPI_Info_get_nthkey_fortran_wrapper(info, n, key, ierr); } _EXTERN_C_ void mpi_info_get_nthkey_(MPI_Fint *info, MPI_Fint *n, MPI_Fint *key, MPI_Fint *ierr) { MPI_Info_get_nthkey_fortran_wrapper(info, n, key, ierr); } _EXTERN_C_ void mpi_info_get_nthkey__(MPI_Fint *info, MPI_Fint *n, MPI_Fint *key, MPI_Fint *ierr) { MPI_Info_get_nthkey_fortran_wrapper(info, n, key, ierr); } /* ================= End Wrappers for MPI_Info_get_nthkey ================= */ /* ================== C Wrappers for MPI_Info_get_valuelen ================== */ _EXTERN_C_ int PMPI_Info_get_valuelen(MPI_Info info, const char *key, int *valuelen, int *flag); _EXTERN_C_ int MPI_Info_get_valuelen(MPI_Info info, const char *key, int *valuelen, int *flag) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Info_get_valuelen(info, key, valuelen, flag); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Info_get_valuelen =============== */ static void MPI_Info_get_valuelen_fortran_wrapper(MPI_Fint *info, MPI_Fint *key, MPI_Fint *valuelen, MPI_Fint *flag, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Info_get_valuelen((MPI_Info)(*info), (const char*)key, (int*)valuelen, (int*)flag); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Info_get_valuelen(MPI_Info_f2c(*info), (const char*)key, (int*)valuelen, (int*)flag); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INFO_GET_VALUELEN(MPI_Fint *info, MPI_Fint *key, MPI_Fint *valuelen, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Info_get_valuelen_fortran_wrapper(info, key, valuelen, flag, ierr); } _EXTERN_C_ void mpi_info_get_valuelen(MPI_Fint *info, MPI_Fint *key, MPI_Fint *valuelen, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Info_get_valuelen_fortran_wrapper(info, key, valuelen, flag, ierr); } _EXTERN_C_ void mpi_info_get_valuelen_(MPI_Fint *info, MPI_Fint *key, MPI_Fint *valuelen, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Info_get_valuelen_fortran_wrapper(info, key, valuelen, flag, ierr); } _EXTERN_C_ void mpi_info_get_valuelen__(MPI_Fint *info, MPI_Fint *key, MPI_Fint *valuelen, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Info_get_valuelen_fortran_wrapper(info, key, valuelen, flag, ierr); } /* ================= End Wrappers for MPI_Info_get_valuelen ================= */ /* ================== C Wrappers for MPI_Info_set ================== */ _EXTERN_C_ int PMPI_Info_set(MPI_Info info, const char *key, const char *value); _EXTERN_C_ int MPI_Info_set(MPI_Info info, const char *key, const char *value) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Info_set(info, key, value); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Info_set =============== */ static void MPI_Info_set_fortran_wrapper(MPI_Fint *info, MPI_Fint *key, MPI_Fint *value, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Info_set((MPI_Info)(*info), (const char*)key, (const char*)value); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Info_set(MPI_Info_f2c(*info), (const char*)key, (const char*)value); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INFO_SET(MPI_Fint *info, MPI_Fint *key, MPI_Fint *value, MPI_Fint *ierr) { MPI_Info_set_fortran_wrapper(info, key, value, ierr); } _EXTERN_C_ void mpi_info_set(MPI_Fint *info, MPI_Fint *key, MPI_Fint *value, MPI_Fint *ierr) { MPI_Info_set_fortran_wrapper(info, key, value, ierr); } _EXTERN_C_ void mpi_info_set_(MPI_Fint *info, MPI_Fint *key, MPI_Fint *value, MPI_Fint *ierr) { MPI_Info_set_fortran_wrapper(info, key, value, ierr); } _EXTERN_C_ void mpi_info_set__(MPI_Fint *info, MPI_Fint *key, MPI_Fint *value, MPI_Fint *ierr) { MPI_Info_set_fortran_wrapper(info, key, value, ierr); } /* ================= End Wrappers for MPI_Info_set ================= */ _EXTERN_C_ int PMPI_Comm_rank(MPI_Comm comm, int *rank); static int fortran_init = 0; /* ================== C Wrappers for MPI_Init ================== */ _EXTERN_C_ int PMPI_Init(int *argc, char ***argv); _EXTERN_C_ int MPI_Init(int *argc, char ***argv) { int _wrap_py_return_val = 0; { if (fortran_init) { #ifdef PIC if (!PMPI_INIT && !pmpi_init && !pmpi_init_ && !pmpi_init__) { fprintf(stderr, "ERROR: Couldn't find fortran pmpi_init function. Link against static library instead.\n"); exit(1); } switch (fortran_init) { case 1: PMPI_INIT(&_wrap_py_return_val); break; case 2: pmpi_init(&_wrap_py_return_val); break; case 3: pmpi_init_(&_wrap_py_return_val); break; case 4: pmpi_init__(&_wrap_py_return_val); break; default: fprintf(stderr, "NO SUITABLE FORTRAN MPI_INIT BINDING\n"); break; } #else /* !PIC */ pmpi_init_(&_wrap_py_return_val); #endif /* !PIC */ } else { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Init(argc, argv); WRAP_MPI_CALL_POSTFIX } } if (isolation_mode) { current_rank = unit_rank; } else { if (MPI_SUCCESS == _wrap_py_return_val) { /* MPI_COMM_WORLD is maybe the best solution to some unstated problems yet. */ PMPI_Comm_rank(MPI_COMM_WORLD, &current_rank); } } char *backend_spec = getenv("RAW_WRAPPER_BACKEND"); if (NULL != backend_spec) { wrapper_backend_handle = dlopen(backend_spec, RTLD_NOW); assert(NULL != wrapper_backend_handle); backend_capture_data = dlsym(wrapper_backend_handle, "rw_capture_data"); backend_create_pending_request = dlsym(wrapper_backend_handle, "rw_create_pending_request"); backend_finalize = dlsym(wrapper_backend_handle, "rw_finalize"); backend_init = dlsym(wrapper_backend_handle, "rw_init"); backend_obtain_pending_request = dlsym(wrapper_backend_handle, "rw_obtain_pending_request"); backend_replay_data = dlsym(wrapper_backend_handle, "rw_replay_data"); } else { backend_capture_data = rw_capture_data; backend_create_pending_request = rw_create_pending_request; backend_obtain_pending_request = rw_obtain_pending_request; backend_replay_data = rw_replay_data; } if (NULL != backend_init) { backend_init(argc, argv, current_rank); } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Init =============== */ static void MPI_Init_fortran_wrapper(MPI_Fint *ierr) { int argc = 0; char ** argv = NULL; int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Init(&argc, &argv); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INIT(MPI_Fint *ierr) { fortran_init = 1; MPI_Init_fortran_wrapper(ierr); } _EXTERN_C_ void mpi_init(MPI_Fint *ierr) { fortran_init = 2; MPI_Init_fortran_wrapper(ierr); } _EXTERN_C_ void mpi_init_(MPI_Fint *ierr) { fortran_init = 3; MPI_Init_fortran_wrapper(ierr); } _EXTERN_C_ void mpi_init__(MPI_Fint *ierr) { fortran_init = 4; MPI_Init_fortran_wrapper(ierr); } /* ================= End Wrappers for MPI_Init ================= */ /* ================== C Wrappers for MPI_Init_thread ================== */ _EXTERN_C_ int PMPI_Init_thread(int *argc, char ***argv, int required, int *provided); _EXTERN_C_ int MPI_Init_thread(int *argc, char ***argv, int required, int *provided) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Init_thread(argc, argv, required, provided); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Init_thread =============== */ static void MPI_Init_thread_fortran_wrapper(MPI_Fint *argc, MPI_Fint ***argv, MPI_Fint *required, MPI_Fint *provided, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Init_thread((int*)argc, (char***)argv, *required, (int*)provided); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INIT_THREAD(MPI_Fint *argc, MPI_Fint ***argv, MPI_Fint *required, MPI_Fint *provided, MPI_Fint *ierr) { MPI_Init_thread_fortran_wrapper(argc, argv, required, provided, ierr); } _EXTERN_C_ void mpi_init_thread(MPI_Fint *argc, MPI_Fint ***argv, MPI_Fint *required, MPI_Fint *provided, MPI_Fint *ierr) { MPI_Init_thread_fortran_wrapper(argc, argv, required, provided, ierr); } _EXTERN_C_ void mpi_init_thread_(MPI_Fint *argc, MPI_Fint ***argv, MPI_Fint *required, MPI_Fint *provided, MPI_Fint *ierr) { MPI_Init_thread_fortran_wrapper(argc, argv, required, provided, ierr); } _EXTERN_C_ void mpi_init_thread__(MPI_Fint *argc, MPI_Fint ***argv, MPI_Fint *required, MPI_Fint *provided, MPI_Fint *ierr) { MPI_Init_thread_fortran_wrapper(argc, argv, required, provided, ierr); } /* ================= End Wrappers for MPI_Init_thread ================= */ /* ================== C Wrappers for MPI_Initialized ================== */ _EXTERN_C_ int PMPI_Initialized(int *flag); _EXTERN_C_ int MPI_Initialized(int *flag) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Initialized(flag); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Initialized =============== */ static void MPI_Initialized_fortran_wrapper(MPI_Fint *flag, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Initialized((int*)flag); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INITIALIZED(MPI_Fint *flag, MPI_Fint *ierr) { MPI_Initialized_fortran_wrapper(flag, ierr); } _EXTERN_C_ void mpi_initialized(MPI_Fint *flag, MPI_Fint *ierr) { MPI_Initialized_fortran_wrapper(flag, ierr); } _EXTERN_C_ void mpi_initialized_(MPI_Fint *flag, MPI_Fint *ierr) { MPI_Initialized_fortran_wrapper(flag, ierr); } _EXTERN_C_ void mpi_initialized__(MPI_Fint *flag, MPI_Fint *ierr) { MPI_Initialized_fortran_wrapper(flag, ierr); } /* ================= End Wrappers for MPI_Initialized ================= */ /* ================== C Wrappers for MPI_Intercomm_create ================== */ _EXTERN_C_ int PMPI_Intercomm_create(MPI_Comm local_comm, int local_leader, MPI_Comm bridge_comm, int remote_leader, int tag, MPI_Comm *newintercomm); _EXTERN_C_ int MPI_Intercomm_create(MPI_Comm local_comm, int local_leader, MPI_Comm bridge_comm, int remote_leader, int tag, MPI_Comm *newintercomm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Intercomm_create(local_comm, local_leader, bridge_comm, remote_leader, tag, newintercomm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Intercomm_create =============== */ static void MPI_Intercomm_create_fortran_wrapper(MPI_Fint *local_comm, MPI_Fint *local_leader, MPI_Fint *bridge_comm, MPI_Fint *remote_leader, MPI_Fint *tag, MPI_Fint *newintercomm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Intercomm_create((MPI_Comm)(*local_comm), *local_leader, (MPI_Comm)(*bridge_comm), *remote_leader, *tag, (MPI_Comm*)newintercomm); #else /* MPI-2 safe call */ MPI_Comm temp_newintercomm; temp_newintercomm = MPI_Comm_f2c(*newintercomm); _wrap_py_return_val = MPI_Intercomm_create(MPI_Comm_f2c(*local_comm), *local_leader, MPI_Comm_f2c(*bridge_comm), *remote_leader, *tag, &temp_newintercomm); *newintercomm = MPI_Comm_c2f(temp_newintercomm); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INTERCOMM_CREATE(MPI_Fint *local_comm, MPI_Fint *local_leader, MPI_Fint *bridge_comm, MPI_Fint *remote_leader, MPI_Fint *tag, MPI_Fint *newintercomm, MPI_Fint *ierr) { MPI_Intercomm_create_fortran_wrapper(local_comm, local_leader, bridge_comm, remote_leader, tag, newintercomm, ierr); } _EXTERN_C_ void mpi_intercomm_create(MPI_Fint *local_comm, MPI_Fint *local_leader, MPI_Fint *bridge_comm, MPI_Fint *remote_leader, MPI_Fint *tag, MPI_Fint *newintercomm, MPI_Fint *ierr) { MPI_Intercomm_create_fortran_wrapper(local_comm, local_leader, bridge_comm, remote_leader, tag, newintercomm, ierr); } _EXTERN_C_ void mpi_intercomm_create_(MPI_Fint *local_comm, MPI_Fint *local_leader, MPI_Fint *bridge_comm, MPI_Fint *remote_leader, MPI_Fint *tag, MPI_Fint *newintercomm, MPI_Fint *ierr) { MPI_Intercomm_create_fortran_wrapper(local_comm, local_leader, bridge_comm, remote_leader, tag, newintercomm, ierr); } _EXTERN_C_ void mpi_intercomm_create__(MPI_Fint *local_comm, MPI_Fint *local_leader, MPI_Fint *bridge_comm, MPI_Fint *remote_leader, MPI_Fint *tag, MPI_Fint *newintercomm, MPI_Fint *ierr) { MPI_Intercomm_create_fortran_wrapper(local_comm, local_leader, bridge_comm, remote_leader, tag, newintercomm, ierr); } /* ================= End Wrappers for MPI_Intercomm_create ================= */ /* ================== C Wrappers for MPI_Intercomm_merge ================== */ _EXTERN_C_ int PMPI_Intercomm_merge(MPI_Comm intercomm, int high, MPI_Comm *newintercomm); _EXTERN_C_ int MPI_Intercomm_merge(MPI_Comm intercomm, int high, MPI_Comm *newintercomm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Intercomm_merge(intercomm, high, newintercomm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Intercomm_merge =============== */ static void MPI_Intercomm_merge_fortran_wrapper(MPI_Fint *intercomm, MPI_Fint *high, MPI_Fint *newintercomm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Intercomm_merge((MPI_Comm)(*intercomm), *high, (MPI_Comm*)newintercomm); #else /* MPI-2 safe call */ MPI_Comm temp_newintercomm; temp_newintercomm = MPI_Comm_f2c(*newintercomm); _wrap_py_return_val = MPI_Intercomm_merge(MPI_Comm_f2c(*intercomm), *high, &temp_newintercomm); *newintercomm = MPI_Comm_c2f(temp_newintercomm); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_INTERCOMM_MERGE(MPI_Fint *intercomm, MPI_Fint *high, MPI_Fint *newintercomm, MPI_Fint *ierr) { MPI_Intercomm_merge_fortran_wrapper(intercomm, high, newintercomm, ierr); } _EXTERN_C_ void mpi_intercomm_merge(MPI_Fint *intercomm, MPI_Fint *high, MPI_Fint *newintercomm, MPI_Fint *ierr) { MPI_Intercomm_merge_fortran_wrapper(intercomm, high, newintercomm, ierr); } _EXTERN_C_ void mpi_intercomm_merge_(MPI_Fint *intercomm, MPI_Fint *high, MPI_Fint *newintercomm, MPI_Fint *ierr) { MPI_Intercomm_merge_fortran_wrapper(intercomm, high, newintercomm, ierr); } _EXTERN_C_ void mpi_intercomm_merge__(MPI_Fint *intercomm, MPI_Fint *high, MPI_Fint *newintercomm, MPI_Fint *ierr) { MPI_Intercomm_merge_fortran_wrapper(intercomm, high, newintercomm, ierr); } /* ================= End Wrappers for MPI_Intercomm_merge ================= */ /* ================== C Wrappers for MPI_Iprobe ================== */ _EXTERN_C_ int PMPI_Iprobe(int source, int tag, MPI_Comm comm, int *flag, MPI_Status *status); _EXTERN_C_ int MPI_Iprobe(int source, int tag, MPI_Comm comm, int *flag, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Iprobe(source, tag, comm, flag, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Iprobe =============== */ static void MPI_Iprobe_fortran_wrapper(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Iprobe(*source, *tag, (MPI_Comm)(*comm), (int*)flag, (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_Iprobe(*source, *tag, MPI_Comm_f2c(*comm), (int*)flag, &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IPROBE(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { MPI_Iprobe_fortran_wrapper(source, tag, comm, flag, status, ierr); } _EXTERN_C_ void mpi_iprobe(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { MPI_Iprobe_fortran_wrapper(source, tag, comm, flag, status, ierr); } _EXTERN_C_ void mpi_iprobe_(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { MPI_Iprobe_fortran_wrapper(source, tag, comm, flag, status, ierr); } _EXTERN_C_ void mpi_iprobe__(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { MPI_Iprobe_fortran_wrapper(source, tag, comm, flag, status, ierr); } /* ================= End Wrappers for MPI_Iprobe ================= */ /* ================== C Wrappers for MPI_Irecv ================== */ _EXTERN_C_ int PMPI_Irecv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Irecv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX uint64_t local_call_counter = 0; if (!wrapper_enabled) { _wrap_py_return_val = PMPI_Irecv(buf, count, datatype, source, tag, comm, request); goto end; } #pragma omp atomic capture local_call_counter = ++receive_counter; if (isolation_mode) { MPI_Status replayed_status; backend_replay_data(current_rank, local_call_counter - 1, buf, datatype, count, &replayed_status); *request = 0; _wrap_py_return_val = MPI_SUCCESS; } else { _wrap_py_return_val = PMPI_Irecv(buf, count, datatype, source, tag, comm, request); if (MPI_SUCCESS == _wrap_py_return_val) { int8_t request_name[SHA256_HEX_CHARS] = {0}; rw_mpi_request_to_unique_string(request, request_name); RW_AsyncMarker marker; marker.call_id = RW_MPI_CALL_ID_IRECV; marker.call_number = local_call_counter - 1; marker.type_count = count; marker.type = datatype; marker.source = source; marker.tag = tag; marker.data_address = buf; backend_create_pending_request(current_rank, &marker, request_name); } } WRAP_MPI_CALL_POSTFIX } end: return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Irecv =============== */ static void MPI_Irecv_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Irecv((void*)buf, *count, (MPI_Datatype)(*datatype), *source, *tag, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Irecv((void*)buf, *count, MPI_Type_f2c(*datatype), *source, *tag, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IRECV(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Irecv_fortran_wrapper(buf, count, datatype, source, tag, comm, request, ierr); } _EXTERN_C_ void mpi_irecv(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Irecv_fortran_wrapper(buf, count, datatype, source, tag, comm, request, ierr); } _EXTERN_C_ void mpi_irecv_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Irecv_fortran_wrapper(buf, count, datatype, source, tag, comm, request, ierr); } _EXTERN_C_ void mpi_irecv__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Irecv_fortran_wrapper(buf, count, datatype, source, tag, comm, request, ierr); } /* ================= End Wrappers for MPI_Irecv ================= */ /* ================== C Wrappers for MPI_Ireduce ================== */ _EXTERN_C_ int PMPI_Ireduce(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, int root, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Ireduce(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, int root, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Ireduce(sendbuf, recvbuf, count, datatype, op, root, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Ireduce =============== */ static void MPI_Ireduce_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Ireduce((const void*)sendbuf, (void*)recvbuf, *count, (MPI_Datatype)(*datatype), (MPI_Op)(*op), *root, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Ireduce((const void*)sendbuf, (void*)recvbuf, *count, MPI_Type_f2c(*datatype), MPI_Op_f2c(*op), *root, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IREDUCE(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ireduce_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, root, comm, request, ierr); } _EXTERN_C_ void mpi_ireduce(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ireduce_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, root, comm, request, ierr); } _EXTERN_C_ void mpi_ireduce_(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ireduce_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, root, comm, request, ierr); } _EXTERN_C_ void mpi_ireduce__(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ireduce_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, root, comm, request, ierr); } /* ================= End Wrappers for MPI_Ireduce ================= */ /* ================== C Wrappers for MPI_Ireduce_scatter ================== */ _EXTERN_C_ int PMPI_Ireduce_scatter(const void *sendbuf, void *recvbuf, const int recvcounts[], MPI_Datatype datatype, MPI_Op op, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Ireduce_scatter(const void *sendbuf, void *recvbuf, const int recvcounts[], MPI_Datatype datatype, MPI_Op op, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Ireduce_scatter(sendbuf, recvbuf, recvcounts, datatype, op, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Ireduce_scatter =============== */ static void MPI_Ireduce_scatter_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Ireduce_scatter((const void*)sendbuf, (void*)recvbuf, (const int*)recvcounts, (MPI_Datatype)(*datatype), (MPI_Op)(*op), (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Ireduce_scatter((const void*)sendbuf, (void*)recvbuf, (const int*)recvcounts, MPI_Type_f2c(*datatype), MPI_Op_f2c(*op), MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IREDUCE_SCATTER(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ireduce_scatter_fortran_wrapper(sendbuf, recvbuf, recvcounts, datatype, op, comm, request, ierr); } _EXTERN_C_ void mpi_ireduce_scatter(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ireduce_scatter_fortran_wrapper(sendbuf, recvbuf, recvcounts, datatype, op, comm, request, ierr); } _EXTERN_C_ void mpi_ireduce_scatter_(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ireduce_scatter_fortran_wrapper(sendbuf, recvbuf, recvcounts, datatype, op, comm, request, ierr); } _EXTERN_C_ void mpi_ireduce_scatter__(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ireduce_scatter_fortran_wrapper(sendbuf, recvbuf, recvcounts, datatype, op, comm, request, ierr); } /* ================= End Wrappers for MPI_Ireduce_scatter ================= */ /* ================== C Wrappers for MPI_Ireduce_scatter_block ================== */ _EXTERN_C_ int PMPI_Ireduce_scatter_block(const void *sendbuf, void *recvbuf, int recvcount, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Ireduce_scatter_block(const void *sendbuf, void *recvbuf, int recvcount, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Ireduce_scatter_block(sendbuf, recvbuf, recvcount, datatype, op, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Ireduce_scatter_block =============== */ static void MPI_Ireduce_scatter_block_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Ireduce_scatter_block((const void*)sendbuf, (void*)recvbuf, *recvcount, (MPI_Datatype)(*datatype), (MPI_Op)(*op), (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Ireduce_scatter_block((const void*)sendbuf, (void*)recvbuf, *recvcount, MPI_Type_f2c(*datatype), MPI_Op_f2c(*op), MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IREDUCE_SCATTER_BLOCK(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ireduce_scatter_block_fortran_wrapper(sendbuf, recvbuf, recvcount, datatype, op, comm, request, ierr); } _EXTERN_C_ void mpi_ireduce_scatter_block(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ireduce_scatter_block_fortran_wrapper(sendbuf, recvbuf, recvcount, datatype, op, comm, request, ierr); } _EXTERN_C_ void mpi_ireduce_scatter_block_(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ireduce_scatter_block_fortran_wrapper(sendbuf, recvbuf, recvcount, datatype, op, comm, request, ierr); } _EXTERN_C_ void mpi_ireduce_scatter_block__(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ireduce_scatter_block_fortran_wrapper(sendbuf, recvbuf, recvcount, datatype, op, comm, request, ierr); } /* ================= End Wrappers for MPI_Ireduce_scatter_block ================= */ /* ================== C Wrappers for MPI_Irsend ================== */ _EXTERN_C_ int PMPI_Irsend(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Irsend(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Irsend(buf, count, datatype, dest, tag, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Irsend =============== */ static void MPI_Irsend_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Irsend((const void*)buf, *count, (MPI_Datatype)(*datatype), *dest, *tag, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Irsend((const void*)buf, *count, MPI_Type_f2c(*datatype), *dest, *tag, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IRSEND(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Irsend_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_irsend(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Irsend_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_irsend_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Irsend_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_irsend__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Irsend_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } /* ================= End Wrappers for MPI_Irsend ================= */ /* ================== C Wrappers for MPI_Is_thread_main ================== */ _EXTERN_C_ int PMPI_Is_thread_main(int *flag); _EXTERN_C_ int MPI_Is_thread_main(int *flag) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Is_thread_main(flag); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Is_thread_main =============== */ static void MPI_Is_thread_main_fortran_wrapper(MPI_Fint *flag, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Is_thread_main((int*)flag); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_IS_THREAD_MAIN(MPI_Fint *flag, MPI_Fint *ierr) { MPI_Is_thread_main_fortran_wrapper(flag, ierr); } _EXTERN_C_ void mpi_is_thread_main(MPI_Fint *flag, MPI_Fint *ierr) { MPI_Is_thread_main_fortran_wrapper(flag, ierr); } _EXTERN_C_ void mpi_is_thread_main_(MPI_Fint *flag, MPI_Fint *ierr) { MPI_Is_thread_main_fortran_wrapper(flag, ierr); } _EXTERN_C_ void mpi_is_thread_main__(MPI_Fint *flag, MPI_Fint *ierr) { MPI_Is_thread_main_fortran_wrapper(flag, ierr); } /* ================= End Wrappers for MPI_Is_thread_main ================= */ /* ================== C Wrappers for MPI_Iscan ================== */ _EXTERN_C_ int PMPI_Iscan(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Iscan(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Iscan(sendbuf, recvbuf, count, datatype, op, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Iscan =============== */ static void MPI_Iscan_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Iscan((const void*)sendbuf, (void*)recvbuf, *count, (MPI_Datatype)(*datatype), (MPI_Op)(*op), (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Iscan((const void*)sendbuf, (void*)recvbuf, *count, MPI_Type_f2c(*datatype), MPI_Op_f2c(*op), MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ISCAN(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iscan_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, request, ierr); } _EXTERN_C_ void mpi_iscan(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iscan_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, request, ierr); } _EXTERN_C_ void mpi_iscan_(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iscan_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, request, ierr); } _EXTERN_C_ void mpi_iscan__(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iscan_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, request, ierr); } /* ================= End Wrappers for MPI_Iscan ================= */ /* ================== C Wrappers for MPI_Iscatter ================== */ _EXTERN_C_ int PMPI_Iscatter(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Iscatter(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Iscatter(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Iscatter =============== */ static void MPI_Iscatter_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Iscatter((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, *recvcount, (MPI_Datatype)(*recvtype), *root, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Iscatter((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, *recvcount, MPI_Type_f2c(*recvtype), *root, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ISCATTER(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iscatter_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, request, ierr); } _EXTERN_C_ void mpi_iscatter(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iscatter_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, request, ierr); } _EXTERN_C_ void mpi_iscatter_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iscatter_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, request, ierr); } _EXTERN_C_ void mpi_iscatter__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iscatter_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, request, ierr); } /* ================= End Wrappers for MPI_Iscatter ================= */ /* ================== C Wrappers for MPI_Iscatterv ================== */ _EXTERN_C_ int PMPI_Iscatterv(const void *sendbuf, const int sendcounts[], const int displs[], MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Iscatterv(const void *sendbuf, const int sendcounts[], const int displs[], MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Iscatterv(sendbuf, sendcounts, displs, sendtype, recvbuf, recvcount, recvtype, root, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Iscatterv =============== */ static void MPI_Iscatterv_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint displs[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Iscatterv((const void*)sendbuf, (const int*)sendcounts, (const int*)displs, (MPI_Datatype)(*sendtype), (void*)recvbuf, *recvcount, (MPI_Datatype)(*recvtype), *root, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Iscatterv((const void*)sendbuf, (const int*)sendcounts, (const int*)displs, MPI_Type_f2c(*sendtype), (void*)recvbuf, *recvcount, MPI_Type_f2c(*recvtype), *root, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ISCATTERV(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint displs[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iscatterv_fortran_wrapper(sendbuf, sendcounts, displs, sendtype, recvbuf, recvcount, recvtype, root, comm, request, ierr); } _EXTERN_C_ void mpi_iscatterv(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint displs[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iscatterv_fortran_wrapper(sendbuf, sendcounts, displs, sendtype, recvbuf, recvcount, recvtype, root, comm, request, ierr); } _EXTERN_C_ void mpi_iscatterv_(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint displs[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iscatterv_fortran_wrapper(sendbuf, sendcounts, displs, sendtype, recvbuf, recvcount, recvtype, root, comm, request, ierr); } _EXTERN_C_ void mpi_iscatterv__(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint displs[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Iscatterv_fortran_wrapper(sendbuf, sendcounts, displs, sendtype, recvbuf, recvcount, recvtype, root, comm, request, ierr); } /* ================= End Wrappers for MPI_Iscatterv ================= */ /* ================== C Wrappers for MPI_Isend ================== */ _EXTERN_C_ int PMPI_Isend(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Isend(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX if (isolation_mode && wrapper_enabled) { _wrap_py_return_val = MPI_SUCCESS; } else { _wrap_py_return_val = PMPI_Isend(buf, count, datatype, dest, tag, comm, request); } WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Isend =============== */ static void MPI_Isend_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Isend((const void*)buf, *count, (MPI_Datatype)(*datatype), *dest, *tag, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Isend((const void*)buf, *count, MPI_Type_f2c(*datatype), *dest, *tag, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ISEND(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Isend_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_isend(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Isend_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_isend_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Isend_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_isend__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Isend_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } /* ================= End Wrappers for MPI_Isend ================= */ /* ================== C Wrappers for MPI_Issend ================== */ _EXTERN_C_ int PMPI_Issend(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Issend(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Issend(buf, count, datatype, dest, tag, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Issend =============== */ static void MPI_Issend_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Issend((const void*)buf, *count, (MPI_Datatype)(*datatype), *dest, *tag, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Issend((const void*)buf, *count, MPI_Type_f2c(*datatype), *dest, *tag, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_ISSEND(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Issend_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_issend(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Issend_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_issend_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Issend_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_issend__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Issend_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } /* ================= End Wrappers for MPI_Issend ================= */ /* ================== C Wrappers for MPI_Keyval_create ================== */ _EXTERN_C_ int PMPI_Keyval_create(MPI_Copy_function *copy_fn, MPI_Delete_function *delete_fn, int *keyval, void *extra_state); _EXTERN_C_ int MPI_Keyval_create(MPI_Copy_function *copy_fn, MPI_Delete_function *delete_fn, int *keyval, void *extra_state) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Keyval_create(copy_fn, delete_fn, keyval, extra_state); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Keyval_create =============== */ static void MPI_Keyval_create_fortran_wrapper(MPI_Copy_function *copy_fn, MPI_Delete_function *delete_fn, MPI_Fint *keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { int _wrap_py_return_val = 0; WRAP_MPI_CALL_PREFIX _wrap_py_return_val = MPI_Keyval_create((MPI_Copy_function*)copy_fn, (MPI_Delete_function*)delete_fn, (int*)keyval, (void*)extra_state); WRAP_MPI_CALL_POSTFIX *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_KEYVAL_CREATE(MPI_Copy_function *copy_fn, MPI_Delete_function *delete_fn, MPI_Fint *keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Keyval_create_fortran_wrapper(copy_fn, delete_fn, keyval, extra_state, ierr); } _EXTERN_C_ void mpi_keyval_create(MPI_Copy_function *copy_fn, MPI_Delete_function *delete_fn, MPI_Fint *keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Keyval_create_fortran_wrapper(copy_fn, delete_fn, keyval, extra_state, ierr); } _EXTERN_C_ void mpi_keyval_create_(MPI_Copy_function *copy_fn, MPI_Delete_function *delete_fn, MPI_Fint *keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Keyval_create_fortran_wrapper(copy_fn, delete_fn, keyval, extra_state, ierr); } _EXTERN_C_ void mpi_keyval_create__(MPI_Copy_function *copy_fn, MPI_Delete_function *delete_fn, MPI_Fint *keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Keyval_create_fortran_wrapper(copy_fn, delete_fn, keyval, extra_state, ierr); } /* ================= End Wrappers for MPI_Keyval_create ================= */ /* ================== C Wrappers for MPI_Keyval_free ================== */ _EXTERN_C_ int PMPI_Keyval_free(int *keyval); _EXTERN_C_ int MPI_Keyval_free(int *keyval) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Keyval_free(keyval); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Keyval_free =============== */ static void MPI_Keyval_free_fortran_wrapper(MPI_Fint *keyval, MPI_Fint *ierr) { int _wrap_py_return_val = 0; WRAP_MPI_CALL_PREFIX _wrap_py_return_val = MPI_Keyval_free((int*)keyval); WRAP_MPI_CALL_POSTFIX *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_KEYVAL_FREE(MPI_Fint *keyval, MPI_Fint *ierr) { MPI_Keyval_free_fortran_wrapper(keyval, ierr); } _EXTERN_C_ void mpi_keyval_free(MPI_Fint *keyval, MPI_Fint *ierr) { MPI_Keyval_free_fortran_wrapper(keyval, ierr); } _EXTERN_C_ void mpi_keyval_free_(MPI_Fint *keyval, MPI_Fint *ierr) { MPI_Keyval_free_fortran_wrapper(keyval, ierr); } _EXTERN_C_ void mpi_keyval_free__(MPI_Fint *keyval, MPI_Fint *ierr) { MPI_Keyval_free_fortran_wrapper(keyval, ierr); } /* ================= End Wrappers for MPI_Keyval_free ================= */ /* ================== C Wrappers for MPI_Lookup_name ================== */ _EXTERN_C_ int PMPI_Lookup_name(const char *service_name, MPI_Info info, char *port_name); _EXTERN_C_ int MPI_Lookup_name(const char *service_name, MPI_Info info, char *port_name) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Lookup_name(service_name, info, port_name); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Lookup_name =============== */ static void MPI_Lookup_name_fortran_wrapper(MPI_Fint *service_name, MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Lookup_name((const char*)service_name, (MPI_Info)(*info), (char*)port_name); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Lookup_name((const char*)service_name, MPI_Info_f2c(*info), (char*)port_name); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_LOOKUP_NAME(MPI_Fint *service_name, MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Lookup_name_fortran_wrapper(service_name, info, port_name, ierr); } _EXTERN_C_ void mpi_lookup_name(MPI_Fint *service_name, MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Lookup_name_fortran_wrapper(service_name, info, port_name, ierr); } _EXTERN_C_ void mpi_lookup_name_(MPI_Fint *service_name, MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Lookup_name_fortran_wrapper(service_name, info, port_name, ierr); } _EXTERN_C_ void mpi_lookup_name__(MPI_Fint *service_name, MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Lookup_name_fortran_wrapper(service_name, info, port_name, ierr); } /* ================= End Wrappers for MPI_Lookup_name ================= */ /* ================== C Wrappers for MPI_Mprobe ================== */ _EXTERN_C_ int PMPI_Mprobe(int source, int tag, MPI_Comm comm, MPI_Message *message, MPI_Status *status); _EXTERN_C_ int MPI_Mprobe(int source, int tag, MPI_Comm comm, MPI_Message *message, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Mprobe(source, tag, comm, message, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Mprobe =============== */ static void MPI_Mprobe_fortran_wrapper(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Mprobe(*source, *tag, (MPI_Comm)(*comm), (MPI_Message*)message, (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_Mprobe(*source, *tag, MPI_Comm_f2c(*comm), (MPI_Message*)message, &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_MPROBE(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr) { MPI_Mprobe_fortran_wrapper(source, tag, comm, message, status, ierr); } _EXTERN_C_ void mpi_mprobe(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr) { MPI_Mprobe_fortran_wrapper(source, tag, comm, message, status, ierr); } _EXTERN_C_ void mpi_mprobe_(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr) { MPI_Mprobe_fortran_wrapper(source, tag, comm, message, status, ierr); } _EXTERN_C_ void mpi_mprobe__(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr) { MPI_Mprobe_fortran_wrapper(source, tag, comm, message, status, ierr); } /* ================= End Wrappers for MPI_Mprobe ================= */ /* ================== C Wrappers for MPI_Mrecv ================== */ _EXTERN_C_ int PMPI_Mrecv(void *buf, int count, MPI_Datatype type, MPI_Message *message, MPI_Status *status); _EXTERN_C_ int MPI_Mrecv(void *buf, int count, MPI_Datatype type, MPI_Message *message, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Mrecv(buf, count, type, message, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Mrecv =============== */ static void MPI_Mrecv_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *type, MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Mrecv((void*)buf, *count, (MPI_Datatype)(*type), (MPI_Message*)message, (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_Mrecv((void*)buf, *count, MPI_Type_f2c(*type), (MPI_Message*)message, &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_MRECV(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *type, MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr) { MPI_Mrecv_fortran_wrapper(buf, count, type, message, status, ierr); } _EXTERN_C_ void mpi_mrecv(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *type, MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr) { MPI_Mrecv_fortran_wrapper(buf, count, type, message, status, ierr); } _EXTERN_C_ void mpi_mrecv_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *type, MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr) { MPI_Mrecv_fortran_wrapper(buf, count, type, message, status, ierr); } _EXTERN_C_ void mpi_mrecv__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *type, MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr) { MPI_Mrecv_fortran_wrapper(buf, count, type, message, status, ierr); } /* ================= End Wrappers for MPI_Mrecv ================= */ /* ================== C Wrappers for MPI_Neighbor_allgather ================== */ _EXTERN_C_ int PMPI_Neighbor_allgather(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm); _EXTERN_C_ int MPI_Neighbor_allgather(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Neighbor_allgather(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Neighbor_allgather =============== */ static void MPI_Neighbor_allgather_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Neighbor_allgather((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, *recvcount, (MPI_Datatype)(*recvtype), (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Neighbor_allgather((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, *recvcount, MPI_Type_f2c(*recvtype), MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_NEIGHBOR_ALLGATHER(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_allgather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, ierr); } _EXTERN_C_ void mpi_neighbor_allgather(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_allgather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, ierr); } _EXTERN_C_ void mpi_neighbor_allgather_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_allgather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, ierr); } _EXTERN_C_ void mpi_neighbor_allgather__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_allgather_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, ierr); } /* ================= End Wrappers for MPI_Neighbor_allgather ================= */ /* ================== C Wrappers for MPI_Neighbor_allgatherv ================== */ _EXTERN_C_ int PMPI_Neighbor_allgatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int displs[], MPI_Datatype recvtype, MPI_Comm comm); _EXTERN_C_ int MPI_Neighbor_allgatherv(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int displs[], MPI_Datatype recvtype, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Neighbor_allgatherv(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Neighbor_allgatherv =============== */ static void MPI_Neighbor_allgatherv_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Neighbor_allgatherv((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)displs, (MPI_Datatype)(*recvtype), (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Neighbor_allgatherv((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)displs, MPI_Type_f2c(*recvtype), MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_NEIGHBOR_ALLGATHERV(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_allgatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, ierr); } _EXTERN_C_ void mpi_neighbor_allgatherv(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_allgatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, ierr); } _EXTERN_C_ void mpi_neighbor_allgatherv_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_allgatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, ierr); } _EXTERN_C_ void mpi_neighbor_allgatherv__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint displs[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_allgatherv_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcounts, displs, recvtype, comm, ierr); } /* ================= End Wrappers for MPI_Neighbor_allgatherv ================= */ /* ================== C Wrappers for MPI_Neighbor_alltoall ================== */ _EXTERN_C_ int PMPI_Neighbor_alltoall(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm); _EXTERN_C_ int MPI_Neighbor_alltoall(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Neighbor_alltoall(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Neighbor_alltoall =============== */ static void MPI_Neighbor_alltoall_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Neighbor_alltoall((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, *recvcount, (MPI_Datatype)(*recvtype), (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Neighbor_alltoall((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, *recvcount, MPI_Type_f2c(*recvtype), MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_NEIGHBOR_ALLTOALL(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_alltoall_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, ierr); } _EXTERN_C_ void mpi_neighbor_alltoall(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_alltoall_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, ierr); } _EXTERN_C_ void mpi_neighbor_alltoall_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_alltoall_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, ierr); } _EXTERN_C_ void mpi_neighbor_alltoall__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_alltoall_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, ierr); } /* ================= End Wrappers for MPI_Neighbor_alltoall ================= */ /* ================== C Wrappers for MPI_Neighbor_alltoallv ================== */ _EXTERN_C_ int PMPI_Neighbor_alltoallv(const void *sendbuf, const int sendcounts[], const int sdispls[], MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int rdispls[], MPI_Datatype recvtype, MPI_Comm comm); _EXTERN_C_ int MPI_Neighbor_alltoallv(const void *sendbuf, const int sendcounts[], const int sdispls[], MPI_Datatype sendtype, void *recvbuf, const int recvcounts[], const int rdispls[], MPI_Datatype recvtype, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Neighbor_alltoallv(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Neighbor_alltoallv =============== */ static void MPI_Neighbor_alltoallv_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Neighbor_alltoallv((const void*)sendbuf, (const int*)sendcounts, (const int*)sdispls, (MPI_Datatype)(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)rdispls, (MPI_Datatype)(*recvtype), (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Neighbor_alltoallv((const void*)sendbuf, (const int*)sendcounts, (const int*)sdispls, MPI_Type_f2c(*sendtype), (void*)recvbuf, (const int*)recvcounts, (const int*)rdispls, MPI_Type_f2c(*recvtype), MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_NEIGHBOR_ALLTOALLV(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_alltoallv_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, ierr); } _EXTERN_C_ void mpi_neighbor_alltoallv(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_alltoallv_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, ierr); } _EXTERN_C_ void mpi_neighbor_alltoallv_(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_alltoallv_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, ierr); } _EXTERN_C_ void mpi_neighbor_alltoallv__(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint *recvtype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_alltoallv_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm, ierr); } /* ================= End Wrappers for MPI_Neighbor_alltoallv ================= */ /* ================== C Wrappers for MPI_Neighbor_alltoallw ================== */ _EXTERN_C_ int PMPI_Neighbor_alltoallw(const void *sendbuf, const int sendcounts[], const MPI_Aint sdispls[], const MPI_Datatype sendtypes[], void *recvbuf, const int recvcounts[], const MPI_Aint rdispls[], const MPI_Datatype recvtypes[], MPI_Comm comm); _EXTERN_C_ int MPI_Neighbor_alltoallw(const void *sendbuf, const int sendcounts[], const MPI_Aint sdispls[], const MPI_Datatype sendtypes[], void *recvbuf, const int recvcounts[], const MPI_Aint rdispls[], const MPI_Datatype recvtypes[], MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Neighbor_alltoallw(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Neighbor_alltoallw =============== */ static void MPI_Neighbor_alltoallw_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Neighbor_alltoallw((const void*)sendbuf, (const int*)sendcounts, (const MPI_Aint*)sdispls, (const MPI_Datatype*)sendtypes, (void*)recvbuf, (const int*)recvcounts, (const MPI_Aint*)rdispls, (const MPI_Datatype*)recvtypes, (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Neighbor_alltoallw((const void*)sendbuf, (const int*)sendcounts, (const MPI_Aint*)sdispls, (const MPI_Datatype*)sendtypes, (void*)recvbuf, (const int*)recvcounts, (const MPI_Aint*)rdispls, (const MPI_Datatype*)recvtypes, MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_NEIGHBOR_ALLTOALLW(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_alltoallw_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, ierr); } _EXTERN_C_ void mpi_neighbor_alltoallw(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_alltoallw_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, ierr); } _EXTERN_C_ void mpi_neighbor_alltoallw_(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_alltoallw_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, ierr); } _EXTERN_C_ void mpi_neighbor_alltoallw__(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint sdispls[], MPI_Fint sendtypes[], MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint rdispls[], MPI_Fint recvtypes[], MPI_Fint *comm, MPI_Fint *ierr) { MPI_Neighbor_alltoallw_fortran_wrapper(sendbuf, sendcounts, sdispls, sendtypes, recvbuf, recvcounts, rdispls, recvtypes, comm, ierr); } /* ================= End Wrappers for MPI_Neighbor_alltoallw ================= */ /* ================== C Wrappers for MPI_Op_commutative ================== */ _EXTERN_C_ int PMPI_Op_commutative(MPI_Op op, int *commute); _EXTERN_C_ int MPI_Op_commutative(MPI_Op op, int *commute) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Op_commutative(op, commute); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Op_commutative =============== */ static void MPI_Op_commutative_fortran_wrapper(MPI_Fint *op, MPI_Fint *commute, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Op_commutative((MPI_Op)(*op), (int*)commute); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Op_commutative(MPI_Op_f2c(*op), (int*)commute); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_OP_COMMUTATIVE(MPI_Fint *op, MPI_Fint *commute, MPI_Fint *ierr) { MPI_Op_commutative_fortran_wrapper(op, commute, ierr); } _EXTERN_C_ void mpi_op_commutative(MPI_Fint *op, MPI_Fint *commute, MPI_Fint *ierr) { MPI_Op_commutative_fortran_wrapper(op, commute, ierr); } _EXTERN_C_ void mpi_op_commutative_(MPI_Fint *op, MPI_Fint *commute, MPI_Fint *ierr) { MPI_Op_commutative_fortran_wrapper(op, commute, ierr); } _EXTERN_C_ void mpi_op_commutative__(MPI_Fint *op, MPI_Fint *commute, MPI_Fint *ierr) { MPI_Op_commutative_fortran_wrapper(op, commute, ierr); } /* ================= End Wrappers for MPI_Op_commutative ================= */ /* ================== C Wrappers for MPI_Op_create ================== */ _EXTERN_C_ int PMPI_Op_create(MPI_User_function *function, int commute, MPI_Op *op); _EXTERN_C_ int MPI_Op_create(MPI_User_function *function, int commute, MPI_Op *op) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Op_create(function, commute, op); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Op_create =============== */ static void MPI_Op_create_fortran_wrapper(MPI_User_function *function, MPI_Fint *commute, MPI_Fint *op, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Op_create((MPI_User_function*)function, *commute, (MPI_Op*)op); #else /* MPI-2 safe call */ MPI_Op temp_op; temp_op = MPI_Op_f2c(*op); _wrap_py_return_val = MPI_Op_create((MPI_User_function*)function, *commute, &temp_op); *op = MPI_Op_c2f(temp_op); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_OP_CREATE(MPI_User_function *function, MPI_Fint *commute, MPI_Fint *op, MPI_Fint *ierr) { MPI_Op_create_fortran_wrapper(function, commute, op, ierr); } _EXTERN_C_ void mpi_op_create(MPI_User_function *function, MPI_Fint *commute, MPI_Fint *op, MPI_Fint *ierr) { MPI_Op_create_fortran_wrapper(function, commute, op, ierr); } _EXTERN_C_ void mpi_op_create_(MPI_User_function *function, MPI_Fint *commute, MPI_Fint *op, MPI_Fint *ierr) { MPI_Op_create_fortran_wrapper(function, commute, op, ierr); } _EXTERN_C_ void mpi_op_create__(MPI_User_function *function, MPI_Fint *commute, MPI_Fint *op, MPI_Fint *ierr) { MPI_Op_create_fortran_wrapper(function, commute, op, ierr); } /* ================= End Wrappers for MPI_Op_create ================= */ /* ================== C Wrappers for MPI_Op_free ================== */ _EXTERN_C_ int PMPI_Op_free(MPI_Op *op); _EXTERN_C_ int MPI_Op_free(MPI_Op *op) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Op_free(op); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Op_free =============== */ static void MPI_Op_free_fortran_wrapper(MPI_Fint *op, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Op_free((MPI_Op*)op); #else /* MPI-2 safe call */ MPI_Op temp_op; temp_op = MPI_Op_f2c(*op); _wrap_py_return_val = MPI_Op_free(&temp_op); *op = MPI_Op_c2f(temp_op); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_OP_FREE(MPI_Fint *op, MPI_Fint *ierr) { MPI_Op_free_fortran_wrapper(op, ierr); } _EXTERN_C_ void mpi_op_free(MPI_Fint *op, MPI_Fint *ierr) { MPI_Op_free_fortran_wrapper(op, ierr); } _EXTERN_C_ void mpi_op_free_(MPI_Fint *op, MPI_Fint *ierr) { MPI_Op_free_fortran_wrapper(op, ierr); } _EXTERN_C_ void mpi_op_free__(MPI_Fint *op, MPI_Fint *ierr) { MPI_Op_free_fortran_wrapper(op, ierr); } /* ================= End Wrappers for MPI_Op_free ================= */ /* ================== C Wrappers for MPI_Open_port ================== */ _EXTERN_C_ int PMPI_Open_port(MPI_Info info, char *port_name); _EXTERN_C_ int MPI_Open_port(MPI_Info info, char *port_name) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Open_port(info, port_name); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Open_port =============== */ static void MPI_Open_port_fortran_wrapper(MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Open_port((MPI_Info)(*info), (char*)port_name); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Open_port(MPI_Info_f2c(*info), (char*)port_name); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_OPEN_PORT(MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Open_port_fortran_wrapper(info, port_name, ierr); } _EXTERN_C_ void mpi_open_port(MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Open_port_fortran_wrapper(info, port_name, ierr); } _EXTERN_C_ void mpi_open_port_(MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Open_port_fortran_wrapper(info, port_name, ierr); } _EXTERN_C_ void mpi_open_port__(MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Open_port_fortran_wrapper(info, port_name, ierr); } /* ================= End Wrappers for MPI_Open_port ================= */ /* ================== C Wrappers for MPI_Pack ================== */ _EXTERN_C_ int PMPI_Pack(const void *inbuf, int incount, MPI_Datatype datatype, void *outbuf, int outsize, int *position, MPI_Comm comm); _EXTERN_C_ int MPI_Pack(const void *inbuf, int incount, MPI_Datatype datatype, void *outbuf, int outsize, int *position, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Pack(inbuf, incount, datatype, outbuf, outsize, position, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Pack =============== */ static void MPI_Pack_fortran_wrapper(MPI_Fint *inbuf, MPI_Fint *incount, MPI_Fint *datatype, MPI_Fint *outbuf, MPI_Fint *outsize, MPI_Fint *position, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Pack((const void*)inbuf, *incount, (MPI_Datatype)(*datatype), (void*)outbuf, *outsize, (int*)position, (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Pack((const void*)inbuf, *incount, MPI_Type_f2c(*datatype), (void*)outbuf, *outsize, (int*)position, MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_PACK(MPI_Fint *inbuf, MPI_Fint *incount, MPI_Fint *datatype, MPI_Fint *outbuf, MPI_Fint *outsize, MPI_Fint *position, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Pack_fortran_wrapper(inbuf, incount, datatype, outbuf, outsize, position, comm, ierr); } _EXTERN_C_ void mpi_pack(MPI_Fint *inbuf, MPI_Fint *incount, MPI_Fint *datatype, MPI_Fint *outbuf, MPI_Fint *outsize, MPI_Fint *position, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Pack_fortran_wrapper(inbuf, incount, datatype, outbuf, outsize, position, comm, ierr); } _EXTERN_C_ void mpi_pack_(MPI_Fint *inbuf, MPI_Fint *incount, MPI_Fint *datatype, MPI_Fint *outbuf, MPI_Fint *outsize, MPI_Fint *position, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Pack_fortran_wrapper(inbuf, incount, datatype, outbuf, outsize, position, comm, ierr); } _EXTERN_C_ void mpi_pack__(MPI_Fint *inbuf, MPI_Fint *incount, MPI_Fint *datatype, MPI_Fint *outbuf, MPI_Fint *outsize, MPI_Fint *position, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Pack_fortran_wrapper(inbuf, incount, datatype, outbuf, outsize, position, comm, ierr); } /* ================= End Wrappers for MPI_Pack ================= */ /* ================== C Wrappers for MPI_Pack_external ================== */ _EXTERN_C_ int PMPI_Pack_external(const char datarep[], const void *inbuf, int incount, MPI_Datatype datatype, void *outbuf, MPI_Aint outsize, MPI_Aint *position); _EXTERN_C_ int MPI_Pack_external(const char datarep[], const void *inbuf, int incount, MPI_Datatype datatype, void *outbuf, MPI_Aint outsize, MPI_Aint *position) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Pack_external(datarep, inbuf, incount, datatype, outbuf, outsize, position); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Pack_external =============== */ static void MPI_Pack_external_fortran_wrapper(MPI_Fint datarep[], MPI_Fint *inbuf, MPI_Fint *incount, MPI_Fint *datatype, MPI_Fint *outbuf, MPI_Aint *outsize, MPI_Aint *position, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Pack_external((const char*)datarep, (const void*)inbuf, *incount, (MPI_Datatype)(*datatype), (void*)outbuf, *outsize, (MPI_Aint*)position); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Pack_external((const char*)datarep, (const void*)inbuf, *incount, MPI_Type_f2c(*datatype), (void*)outbuf, *outsize, (MPI_Aint*)position); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_PACK_EXTERNAL(MPI_Fint datarep[], MPI_Fint *inbuf, MPI_Fint *incount, MPI_Fint *datatype, MPI_Fint *outbuf, MPI_Aint *outsize, MPI_Aint *position, MPI_Fint *ierr) { MPI_Pack_external_fortran_wrapper(datarep, inbuf, incount, datatype, outbuf, outsize, position, ierr); } _EXTERN_C_ void mpi_pack_external(MPI_Fint datarep[], MPI_Fint *inbuf, MPI_Fint *incount, MPI_Fint *datatype, MPI_Fint *outbuf, MPI_Aint *outsize, MPI_Aint *position, MPI_Fint *ierr) { MPI_Pack_external_fortran_wrapper(datarep, inbuf, incount, datatype, outbuf, outsize, position, ierr); } _EXTERN_C_ void mpi_pack_external_(MPI_Fint datarep[], MPI_Fint *inbuf, MPI_Fint *incount, MPI_Fint *datatype, MPI_Fint *outbuf, MPI_Aint *outsize, MPI_Aint *position, MPI_Fint *ierr) { MPI_Pack_external_fortran_wrapper(datarep, inbuf, incount, datatype, outbuf, outsize, position, ierr); } _EXTERN_C_ void mpi_pack_external__(MPI_Fint datarep[], MPI_Fint *inbuf, MPI_Fint *incount, MPI_Fint *datatype, MPI_Fint *outbuf, MPI_Aint *outsize, MPI_Aint *position, MPI_Fint *ierr) { MPI_Pack_external_fortran_wrapper(datarep, inbuf, incount, datatype, outbuf, outsize, position, ierr); } /* ================= End Wrappers for MPI_Pack_external ================= */ /* ================== C Wrappers for MPI_Pack_external_size ================== */ _EXTERN_C_ int PMPI_Pack_external_size(const char datarep[], int incount, MPI_Datatype datatype, MPI_Aint *size); _EXTERN_C_ int MPI_Pack_external_size(const char datarep[], int incount, MPI_Datatype datatype, MPI_Aint *size) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Pack_external_size(datarep, incount, datatype, size); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Pack_external_size =============== */ static void MPI_Pack_external_size_fortran_wrapper(MPI_Fint datarep[], MPI_Fint *incount, MPI_Fint *datatype, MPI_Aint *size, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Pack_external_size((const char*)datarep, *incount, (MPI_Datatype)(*datatype), (MPI_Aint*)size); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Pack_external_size((const char*)datarep, *incount, MPI_Type_f2c(*datatype), (MPI_Aint*)size); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_PACK_EXTERNAL_SIZE(MPI_Fint datarep[], MPI_Fint *incount, MPI_Fint *datatype, MPI_Aint *size, MPI_Fint *ierr) { MPI_Pack_external_size_fortran_wrapper(datarep, incount, datatype, size, ierr); } _EXTERN_C_ void mpi_pack_external_size(MPI_Fint datarep[], MPI_Fint *incount, MPI_Fint *datatype, MPI_Aint *size, MPI_Fint *ierr) { MPI_Pack_external_size_fortran_wrapper(datarep, incount, datatype, size, ierr); } _EXTERN_C_ void mpi_pack_external_size_(MPI_Fint datarep[], MPI_Fint *incount, MPI_Fint *datatype, MPI_Aint *size, MPI_Fint *ierr) { MPI_Pack_external_size_fortran_wrapper(datarep, incount, datatype, size, ierr); } _EXTERN_C_ void mpi_pack_external_size__(MPI_Fint datarep[], MPI_Fint *incount, MPI_Fint *datatype, MPI_Aint *size, MPI_Fint *ierr) { MPI_Pack_external_size_fortran_wrapper(datarep, incount, datatype, size, ierr); } /* ================= End Wrappers for MPI_Pack_external_size ================= */ /* ================== C Wrappers for MPI_Pack_size ================== */ _EXTERN_C_ int PMPI_Pack_size(int incount, MPI_Datatype datatype, MPI_Comm comm, int *size); _EXTERN_C_ int MPI_Pack_size(int incount, MPI_Datatype datatype, MPI_Comm comm, int *size) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Pack_size(incount, datatype, comm, size); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Pack_size =============== */ static void MPI_Pack_size_fortran_wrapper(MPI_Fint *incount, MPI_Fint *datatype, MPI_Fint *comm, MPI_Fint *size, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Pack_size(*incount, (MPI_Datatype)(*datatype), (MPI_Comm)(*comm), (int*)size); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Pack_size(*incount, MPI_Type_f2c(*datatype), MPI_Comm_f2c(*comm), (int*)size); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_PACK_SIZE(MPI_Fint *incount, MPI_Fint *datatype, MPI_Fint *comm, MPI_Fint *size, MPI_Fint *ierr) { MPI_Pack_size_fortran_wrapper(incount, datatype, comm, size, ierr); } _EXTERN_C_ void mpi_pack_size(MPI_Fint *incount, MPI_Fint *datatype, MPI_Fint *comm, MPI_Fint *size, MPI_Fint *ierr) { MPI_Pack_size_fortran_wrapper(incount, datatype, comm, size, ierr); } _EXTERN_C_ void mpi_pack_size_(MPI_Fint *incount, MPI_Fint *datatype, MPI_Fint *comm, MPI_Fint *size, MPI_Fint *ierr) { MPI_Pack_size_fortran_wrapper(incount, datatype, comm, size, ierr); } _EXTERN_C_ void mpi_pack_size__(MPI_Fint *incount, MPI_Fint *datatype, MPI_Fint *comm, MPI_Fint *size, MPI_Fint *ierr) { MPI_Pack_size_fortran_wrapper(incount, datatype, comm, size, ierr); } /* ================= End Wrappers for MPI_Pack_size ================= */ /* ================== C Wrappers for MPI_Pcontrol ================== */ _EXTERN_C_ int PMPI_Pcontrol(const int level, ...); _EXTERN_C_ int MPI_Pcontrol(const int level, ...) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Pcontrol(level); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Pcontrol =============== */ static void MPI_Pcontrol_fortran_wrapper(MPI_Fint *level, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Pcontrol(*level); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_PCONTROL(MPI_Fint *level, MPI_Fint *ierr) { MPI_Pcontrol_fortran_wrapper(level, ierr); } _EXTERN_C_ void mpi_pcontrol(MPI_Fint *level, MPI_Fint *ierr) { MPI_Pcontrol_fortran_wrapper(level, ierr); } _EXTERN_C_ void mpi_pcontrol_(MPI_Fint *level, MPI_Fint *ierr) { MPI_Pcontrol_fortran_wrapper(level, ierr); } _EXTERN_C_ void mpi_pcontrol__(MPI_Fint *level, MPI_Fint *ierr) { MPI_Pcontrol_fortran_wrapper(level, ierr); } /* ================= End Wrappers for MPI_Pcontrol ================= */ /* ================== C Wrappers for MPI_Probe ================== */ _EXTERN_C_ int PMPI_Probe(int source, int tag, MPI_Comm comm, MPI_Status *status); _EXTERN_C_ int MPI_Probe(int source, int tag, MPI_Comm comm, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Probe(source, tag, comm, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Probe =============== */ static void MPI_Probe_fortran_wrapper(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Probe(*source, *tag, (MPI_Comm)(*comm), (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_Probe(*source, *tag, MPI_Comm_f2c(*comm), &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_PROBE(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Probe_fortran_wrapper(source, tag, comm, status, ierr); } _EXTERN_C_ void mpi_probe(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Probe_fortran_wrapper(source, tag, comm, status, ierr); } _EXTERN_C_ void mpi_probe_(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Probe_fortran_wrapper(source, tag, comm, status, ierr); } _EXTERN_C_ void mpi_probe__(MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Probe_fortran_wrapper(source, tag, comm, status, ierr); } /* ================= End Wrappers for MPI_Probe ================= */ /* ================== C Wrappers for MPI_Publish_name ================== */ _EXTERN_C_ int PMPI_Publish_name(const char *service_name, MPI_Info info, const char *port_name); _EXTERN_C_ int MPI_Publish_name(const char *service_name, MPI_Info info, const char *port_name) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Publish_name(service_name, info, port_name); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Publish_name =============== */ static void MPI_Publish_name_fortran_wrapper(MPI_Fint *service_name, MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Publish_name((const char*)service_name, (MPI_Info)(*info), (const char*)port_name); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Publish_name((const char*)service_name, MPI_Info_f2c(*info), (const char*)port_name); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_PUBLISH_NAME(MPI_Fint *service_name, MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Publish_name_fortran_wrapper(service_name, info, port_name, ierr); } _EXTERN_C_ void mpi_publish_name(MPI_Fint *service_name, MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Publish_name_fortran_wrapper(service_name, info, port_name, ierr); } _EXTERN_C_ void mpi_publish_name_(MPI_Fint *service_name, MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Publish_name_fortran_wrapper(service_name, info, port_name, ierr); } _EXTERN_C_ void mpi_publish_name__(MPI_Fint *service_name, MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Publish_name_fortran_wrapper(service_name, info, port_name, ierr); } /* ================= End Wrappers for MPI_Publish_name ================= */ /* ================== C Wrappers for MPI_Put ================== */ _EXTERN_C_ int PMPI_Put(const void *origin_addr, int origin_count, MPI_Datatype origin_datatype, int target_rank, MPI_Aint target_disp, int target_count, MPI_Datatype target_datatype, MPI_Win win); _EXTERN_C_ int MPI_Put(const void *origin_addr, int origin_count, MPI_Datatype origin_datatype, int target_rank, MPI_Aint target_disp, int target_count, MPI_Datatype target_datatype, MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Put(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Put =============== */ static void MPI_Put_fortran_wrapper(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Put((const void*)origin_addr, *origin_count, (MPI_Datatype)(*origin_datatype), *target_rank, *target_disp, *target_count, (MPI_Datatype)(*target_datatype), (MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Put((const void*)origin_addr, *origin_count, MPI_Type_f2c(*origin_datatype), *target_rank, *target_disp, *target_count, MPI_Type_f2c(*target_datatype), MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_PUT(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *ierr) { MPI_Put_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, win, ierr); } _EXTERN_C_ void mpi_put(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *ierr) { MPI_Put_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, win, ierr); } _EXTERN_C_ void mpi_put_(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *ierr) { MPI_Put_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, win, ierr); } _EXTERN_C_ void mpi_put__(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *ierr) { MPI_Put_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, win, ierr); } /* ================= End Wrappers for MPI_Put ================= */ /* ================== C Wrappers for MPI_Query_thread ================== */ _EXTERN_C_ int PMPI_Query_thread(int *provided); _EXTERN_C_ int MPI_Query_thread(int *provided) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Query_thread(provided); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Query_thread =============== */ static void MPI_Query_thread_fortran_wrapper(MPI_Fint *provided, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Query_thread((int*)provided); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_QUERY_THREAD(MPI_Fint *provided, MPI_Fint *ierr) { MPI_Query_thread_fortran_wrapper(provided, ierr); } _EXTERN_C_ void mpi_query_thread(MPI_Fint *provided, MPI_Fint *ierr) { MPI_Query_thread_fortran_wrapper(provided, ierr); } _EXTERN_C_ void mpi_query_thread_(MPI_Fint *provided, MPI_Fint *ierr) { MPI_Query_thread_fortran_wrapper(provided, ierr); } _EXTERN_C_ void mpi_query_thread__(MPI_Fint *provided, MPI_Fint *ierr) { MPI_Query_thread_fortran_wrapper(provided, ierr); } /* ================= End Wrappers for MPI_Query_thread ================= */ /* ================== C Wrappers for MPI_Raccumulate ================== */ _EXTERN_C_ int PMPI_Raccumulate(const void *origin_addr, int origin_count, MPI_Datatype origin_datatype, int target_rank, MPI_Aint target_disp, int target_count, MPI_Datatype target_datatype, MPI_Op op, MPI_Win win, MPI_Request *request); _EXTERN_C_ int MPI_Raccumulate(const void *origin_addr, int origin_count, MPI_Datatype origin_datatype, int target_rank, MPI_Aint target_disp, int target_count, MPI_Datatype target_datatype, MPI_Op op, MPI_Win win, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Raccumulate(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, op, win, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Raccumulate =============== */ static void MPI_Raccumulate_fortran_wrapper(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Raccumulate((const void*)origin_addr, *origin_count, (MPI_Datatype)(*origin_datatype), *target_rank, *target_disp, *target_count, (MPI_Datatype)(*target_datatype), (MPI_Op)(*op), (MPI_Win)(*win), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Raccumulate((const void*)origin_addr, *origin_count, MPI_Type_f2c(*origin_datatype), *target_rank, *target_disp, *target_count, MPI_Type_f2c(*target_datatype), MPI_Op_f2c(*op), MPI_Win_f2c(*win), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_RACCUMULATE(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { MPI_Raccumulate_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, op, win, request, ierr); } _EXTERN_C_ void mpi_raccumulate(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { MPI_Raccumulate_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, op, win, request, ierr); } _EXTERN_C_ void mpi_raccumulate_(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { MPI_Raccumulate_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, op, win, request, ierr); } _EXTERN_C_ void mpi_raccumulate__(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { MPI_Raccumulate_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, op, win, request, ierr); } /* ================= End Wrappers for MPI_Raccumulate ================= */ /* ================== C Wrappers for MPI_Recv ================== */ _EXTERN_C_ int PMPI_Recv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Status *status); _EXTERN_C_ int MPI_Recv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX uint64_t local_call_counter = 0; if (!wrapper_enabled) { _wrap_py_return_val = PMPI_Recv(buf, count, datatype, source, tag, comm, status); goto end; } #pragma omp atomic capture local_call_counter = ++receive_counter; if (isolation_mode) { MPI_Status replayed_status; backend_replay_data(current_rank, local_call_counter - 1, buf, datatype, count, &replayed_status); *status = replayed_status; _wrap_py_return_val = MPI_SUCCESS; } else { _wrap_py_return_val = PMPI_Recv(buf, count, datatype, source, tag, comm, status); if (MPI_SUCCESS == _wrap_py_return_val) { int actual_count = 0; assert(MPI_SUCCESS == MPI_Get_count(status, datatype, &actual_count)); backend_capture_data(current_rank, local_call_counter - 1, buf, actual_count, datatype, source, tag); } } WRAP_MPI_CALL_POSTFIX } end: return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Recv =============== */ static void MPI_Recv_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Recv((void*)buf, *count, (MPI_Datatype)(*datatype), *source, *tag, (MPI_Comm)(*comm), (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_Recv((void*)buf, *count, MPI_Type_f2c(*datatype), *source, *tag, MPI_Comm_f2c(*comm), &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_RECV(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Recv_fortran_wrapper(buf, count, datatype, source, tag, comm, status, ierr); } _EXTERN_C_ void mpi_recv(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Recv_fortran_wrapper(buf, count, datatype, source, tag, comm, status, ierr); } _EXTERN_C_ void mpi_recv_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Recv_fortran_wrapper(buf, count, datatype, source, tag, comm, status, ierr); } _EXTERN_C_ void mpi_recv__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Recv_fortran_wrapper(buf, count, datatype, source, tag, comm, status, ierr); } /* ================= End Wrappers for MPI_Recv ================= */ /* ================== C Wrappers for MPI_Recv_init ================== */ _EXTERN_C_ int PMPI_Recv_init(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Recv_init(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Recv_init(buf, count, datatype, source, tag, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Recv_init =============== */ static void MPI_Recv_init_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Recv_init((void*)buf, *count, (MPI_Datatype)(*datatype), *source, *tag, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Recv_init((void*)buf, *count, MPI_Type_f2c(*datatype), *source, *tag, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_RECV_INIT(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Recv_init_fortran_wrapper(buf, count, datatype, source, tag, comm, request, ierr); } _EXTERN_C_ void mpi_recv_init(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Recv_init_fortran_wrapper(buf, count, datatype, source, tag, comm, request, ierr); } _EXTERN_C_ void mpi_recv_init_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Recv_init_fortran_wrapper(buf, count, datatype, source, tag, comm, request, ierr); } _EXTERN_C_ void mpi_recv_init__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *source, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Recv_init_fortran_wrapper(buf, count, datatype, source, tag, comm, request, ierr); } /* ================= End Wrappers for MPI_Recv_init ================= */ /* ================== C Wrappers for MPI_Reduce ================== */ _EXTERN_C_ int PMPI_Reduce(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, int root, MPI_Comm comm); _EXTERN_C_ int MPI_Reduce(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, int root, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX uint64_t local_call_counter = 0; if (!wrapper_enabled) { _wrap_py_return_val = PMPI_Reduce(sendbuf, recvbuf, count, datatype, op, root, comm); goto end; } #pragma omp atomic capture local_call_counter = ++receive_counter; if (isolation_mode) { MPI_Status dummy_status; if (root == current_rank) { backend_replay_data(current_rank, local_call_counter - 1, recvbuf, datatype, count, &dummy_status); } _wrap_py_return_val = MPI_SUCCESS; } else { _wrap_py_return_val = PMPI_Reduce(sendbuf, recvbuf, count, datatype, op, root, comm); if (MPI_SUCCESS == _wrap_py_return_val && root == current_rank) { backend_capture_data(current_rank, local_call_counter - 1, recvbuf, count, datatype, 0, 0); } } WRAP_MPI_CALL_POSTFIX } end: return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Reduce =============== */ static void MPI_Reduce_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Reduce(BufferF2C((const void*)sendbuf), (void*)recvbuf, *count, (MPI_Datatype)(*datatype), (MPI_Op)(*op), *root, (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Reduce(BufferF2C((const void*)sendbuf), (void*)recvbuf, *count, MPI_Type_f2c(*datatype), MPI_Op_f2c(*op), *root, MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_REDUCE(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Reduce_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, root, comm, ierr); } _EXTERN_C_ void mpi_reduce(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Reduce_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, root, comm, ierr); } _EXTERN_C_ void mpi_reduce_(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Reduce_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, root, comm, ierr); } _EXTERN_C_ void mpi_reduce__(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Reduce_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, root, comm, ierr); } /* ================= End Wrappers for MPI_Reduce ================= */ /* ================== C Wrappers for MPI_Reduce_local ================== */ _EXTERN_C_ int PMPI_Reduce_local(const void *inbuf, void *inoutbuf, int count, MPI_Datatype datatype, MPI_Op op); _EXTERN_C_ int MPI_Reduce_local(const void *inbuf, void *inoutbuf, int count, MPI_Datatype datatype, MPI_Op op) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Reduce_local(inbuf, inoutbuf, count, datatype, op); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Reduce_local =============== */ static void MPI_Reduce_local_fortran_wrapper(MPI_Fint *inbuf, MPI_Fint *inoutbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Reduce_local((const void*)inbuf, (void*)inoutbuf, *count, (MPI_Datatype)(*datatype), (MPI_Op)(*op)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Reduce_local((const void*)inbuf, (void*)inoutbuf, *count, MPI_Type_f2c(*datatype), MPI_Op_f2c(*op)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_REDUCE_LOCAL(MPI_Fint *inbuf, MPI_Fint *inoutbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *ierr) { MPI_Reduce_local_fortran_wrapper(inbuf, inoutbuf, count, datatype, op, ierr); } _EXTERN_C_ void mpi_reduce_local(MPI_Fint *inbuf, MPI_Fint *inoutbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *ierr) { MPI_Reduce_local_fortran_wrapper(inbuf, inoutbuf, count, datatype, op, ierr); } _EXTERN_C_ void mpi_reduce_local_(MPI_Fint *inbuf, MPI_Fint *inoutbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *ierr) { MPI_Reduce_local_fortran_wrapper(inbuf, inoutbuf, count, datatype, op, ierr); } _EXTERN_C_ void mpi_reduce_local__(MPI_Fint *inbuf, MPI_Fint *inoutbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *ierr) { MPI_Reduce_local_fortran_wrapper(inbuf, inoutbuf, count, datatype, op, ierr); } /* ================= End Wrappers for MPI_Reduce_local ================= */ /* ================== C Wrappers for MPI_Reduce_scatter ================== */ _EXTERN_C_ int PMPI_Reduce_scatter(const void *sendbuf, void *recvbuf, const int recvcounts[], MPI_Datatype datatype, MPI_Op op, MPI_Comm comm); _EXTERN_C_ int MPI_Reduce_scatter(const void *sendbuf, void *recvbuf, const int recvcounts[], MPI_Datatype datatype, MPI_Op op, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Reduce_scatter(sendbuf, recvbuf, recvcounts, datatype, op, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Reduce_scatter =============== */ static void MPI_Reduce_scatter_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Reduce_scatter((const void*)sendbuf, (void*)recvbuf, (const int*)recvcounts, (MPI_Datatype)(*datatype), (MPI_Op)(*op), (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Reduce_scatter((const void*)sendbuf, (void*)recvbuf, (const int*)recvcounts, MPI_Type_f2c(*datatype), MPI_Op_f2c(*op), MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_REDUCE_SCATTER(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Reduce_scatter_fortran_wrapper(sendbuf, recvbuf, recvcounts, datatype, op, comm, ierr); } _EXTERN_C_ void mpi_reduce_scatter(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Reduce_scatter_fortran_wrapper(sendbuf, recvbuf, recvcounts, datatype, op, comm, ierr); } _EXTERN_C_ void mpi_reduce_scatter_(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Reduce_scatter_fortran_wrapper(sendbuf, recvbuf, recvcounts, datatype, op, comm, ierr); } _EXTERN_C_ void mpi_reduce_scatter__(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint recvcounts[], MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Reduce_scatter_fortran_wrapper(sendbuf, recvbuf, recvcounts, datatype, op, comm, ierr); } /* ================= End Wrappers for MPI_Reduce_scatter ================= */ /* ================== C Wrappers for MPI_Reduce_scatter_block ================== */ _EXTERN_C_ int PMPI_Reduce_scatter_block(const void *sendbuf, void *recvbuf, int recvcount, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm); _EXTERN_C_ int MPI_Reduce_scatter_block(const void *sendbuf, void *recvbuf, int recvcount, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Reduce_scatter_block(sendbuf, recvbuf, recvcount, datatype, op, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Reduce_scatter_block =============== */ static void MPI_Reduce_scatter_block_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Reduce_scatter_block((const void*)sendbuf, (void*)recvbuf, *recvcount, (MPI_Datatype)(*datatype), (MPI_Op)(*op), (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Reduce_scatter_block((const void*)sendbuf, (void*)recvbuf, *recvcount, MPI_Type_f2c(*datatype), MPI_Op_f2c(*op), MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_REDUCE_SCATTER_BLOCK(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Reduce_scatter_block_fortran_wrapper(sendbuf, recvbuf, recvcount, datatype, op, comm, ierr); } _EXTERN_C_ void mpi_reduce_scatter_block(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Reduce_scatter_block_fortran_wrapper(sendbuf, recvbuf, recvcount, datatype, op, comm, ierr); } _EXTERN_C_ void mpi_reduce_scatter_block_(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Reduce_scatter_block_fortran_wrapper(sendbuf, recvbuf, recvcount, datatype, op, comm, ierr); } _EXTERN_C_ void mpi_reduce_scatter_block__(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Reduce_scatter_block_fortran_wrapper(sendbuf, recvbuf, recvcount, datatype, op, comm, ierr); } /* ================= End Wrappers for MPI_Reduce_scatter_block ================= */ /* ================== C Wrappers for MPI_Register_datarep ================== */ _EXTERN_C_ int PMPI_Register_datarep(const char *datarep, MPI_Datarep_conversion_function *read_conversion_fn, MPI_Datarep_conversion_function *write_conversion_fn, MPI_Datarep_extent_function *dtype_file_extent_fn, void *extra_state); _EXTERN_C_ int MPI_Register_datarep(const char *datarep, MPI_Datarep_conversion_function *read_conversion_fn, MPI_Datarep_conversion_function *write_conversion_fn, MPI_Datarep_extent_function *dtype_file_extent_fn, void *extra_state) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Register_datarep(datarep, read_conversion_fn, write_conversion_fn, dtype_file_extent_fn, extra_state); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Register_datarep =============== */ static void MPI_Register_datarep_fortran_wrapper(MPI_Fint *datarep, MPI_Datarep_conversion_function *read_conversion_fn, MPI_Datarep_conversion_function *write_conversion_fn, MPI_Datarep_extent_function *dtype_file_extent_fn, MPI_Fint *extra_state, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Register_datarep((const char*)datarep, (MPI_Datarep_conversion_function*)read_conversion_fn, (MPI_Datarep_conversion_function*)write_conversion_fn, (MPI_Datarep_extent_function*)dtype_file_extent_fn, (void*)extra_state); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_REGISTER_DATAREP(MPI_Fint *datarep, MPI_Datarep_conversion_function *read_conversion_fn, MPI_Datarep_conversion_function *write_conversion_fn, MPI_Datarep_extent_function *dtype_file_extent_fn, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Register_datarep_fortran_wrapper(datarep, read_conversion_fn, write_conversion_fn, dtype_file_extent_fn, extra_state, ierr); } _EXTERN_C_ void mpi_register_datarep(MPI_Fint *datarep, MPI_Datarep_conversion_function *read_conversion_fn, MPI_Datarep_conversion_function *write_conversion_fn, MPI_Datarep_extent_function *dtype_file_extent_fn, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Register_datarep_fortran_wrapper(datarep, read_conversion_fn, write_conversion_fn, dtype_file_extent_fn, extra_state, ierr); } _EXTERN_C_ void mpi_register_datarep_(MPI_Fint *datarep, MPI_Datarep_conversion_function *read_conversion_fn, MPI_Datarep_conversion_function *write_conversion_fn, MPI_Datarep_extent_function *dtype_file_extent_fn, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Register_datarep_fortran_wrapper(datarep, read_conversion_fn, write_conversion_fn, dtype_file_extent_fn, extra_state, ierr); } _EXTERN_C_ void mpi_register_datarep__(MPI_Fint *datarep, MPI_Datarep_conversion_function *read_conversion_fn, MPI_Datarep_conversion_function *write_conversion_fn, MPI_Datarep_extent_function *dtype_file_extent_fn, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Register_datarep_fortran_wrapper(datarep, read_conversion_fn, write_conversion_fn, dtype_file_extent_fn, extra_state, ierr); } /* ================= End Wrappers for MPI_Register_datarep ================= */ /* ================== C Wrappers for MPI_Request_free ================== */ _EXTERN_C_ int PMPI_Request_free(MPI_Request *request); _EXTERN_C_ int MPI_Request_free(MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Request_free(request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Request_free =============== */ static void MPI_Request_free_fortran_wrapper(MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Request_free((MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Request_free(&temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_REQUEST_FREE(MPI_Fint *request, MPI_Fint *ierr) { MPI_Request_free_fortran_wrapper(request, ierr); } _EXTERN_C_ void mpi_request_free(MPI_Fint *request, MPI_Fint *ierr) { MPI_Request_free_fortran_wrapper(request, ierr); } _EXTERN_C_ void mpi_request_free_(MPI_Fint *request, MPI_Fint *ierr) { MPI_Request_free_fortran_wrapper(request, ierr); } _EXTERN_C_ void mpi_request_free__(MPI_Fint *request, MPI_Fint *ierr) { MPI_Request_free_fortran_wrapper(request, ierr); } /* ================= End Wrappers for MPI_Request_free ================= */ /* ================== C Wrappers for MPI_Request_get_status ================== */ _EXTERN_C_ int PMPI_Request_get_status(MPI_Request request, int *flag, MPI_Status *status); _EXTERN_C_ int MPI_Request_get_status(MPI_Request request, int *flag, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Request_get_status(request, flag, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Request_get_status =============== */ static void MPI_Request_get_status_fortran_wrapper(MPI_Fint *request, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Request_get_status((MPI_Request)(*request), (int*)flag, (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_Request_get_status(MPI_Request_f2c(*request), (int*)flag, &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_REQUEST_GET_STATUS(MPI_Fint *request, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { MPI_Request_get_status_fortran_wrapper(request, flag, status, ierr); } _EXTERN_C_ void mpi_request_get_status(MPI_Fint *request, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { MPI_Request_get_status_fortran_wrapper(request, flag, status, ierr); } _EXTERN_C_ void mpi_request_get_status_(MPI_Fint *request, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { MPI_Request_get_status_fortran_wrapper(request, flag, status, ierr); } _EXTERN_C_ void mpi_request_get_status__(MPI_Fint *request, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { MPI_Request_get_status_fortran_wrapper(request, flag, status, ierr); } /* ================= End Wrappers for MPI_Request_get_status ================= */ /* ================== C Wrappers for MPI_Rget ================== */ _EXTERN_C_ int PMPI_Rget(void *origin_addr, int origin_count, MPI_Datatype origin_datatype, int target_rank, MPI_Aint target_disp, int target_count, MPI_Datatype target_datatype, MPI_Win win, MPI_Request *request); _EXTERN_C_ int MPI_Rget(void *origin_addr, int origin_count, MPI_Datatype origin_datatype, int target_rank, MPI_Aint target_disp, int target_count, MPI_Datatype target_datatype, MPI_Win win, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Rget(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, win, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Rget =============== */ static void MPI_Rget_fortran_wrapper(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Rget((void*)origin_addr, *origin_count, (MPI_Datatype)(*origin_datatype), *target_rank, *target_disp, *target_count, (MPI_Datatype)(*target_datatype), (MPI_Win)(*win), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Rget((void*)origin_addr, *origin_count, MPI_Type_f2c(*origin_datatype), *target_rank, *target_disp, *target_count, MPI_Type_f2c(*target_datatype), MPI_Win_f2c(*win), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_RGET(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { MPI_Rget_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, win, request, ierr); } _EXTERN_C_ void mpi_rget(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { MPI_Rget_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, win, request, ierr); } _EXTERN_C_ void mpi_rget_(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { MPI_Rget_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, win, request, ierr); } _EXTERN_C_ void mpi_rget__(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { MPI_Rget_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_count, target_datatype, win, request, ierr); } /* ================= End Wrappers for MPI_Rget ================= */ /* ================== C Wrappers for MPI_Rget_accumulate ================== */ _EXTERN_C_ int PMPI_Rget_accumulate(const void *origin_addr, int origin_count, MPI_Datatype origin_datatype, void *result_addr, int result_count, MPI_Datatype result_datatype, int target_rank, MPI_Aint target_disp, int target_count, MPI_Datatype target_datatype, MPI_Op op, MPI_Win win, MPI_Request *request); _EXTERN_C_ int MPI_Rget_accumulate(const void *origin_addr, int origin_count, MPI_Datatype origin_datatype, void *result_addr, int result_count, MPI_Datatype result_datatype, int target_rank, MPI_Aint target_disp, int target_count, MPI_Datatype target_datatype, MPI_Op op, MPI_Win win, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Rget_accumulate(origin_addr, origin_count, origin_datatype, result_addr, result_count, result_datatype, target_rank, target_disp, target_count, target_datatype, op, win, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Rget_accumulate =============== */ static void MPI_Rget_accumulate_fortran_wrapper(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *result_addr, MPI_Fint *result_count, MPI_Fint *result_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Rget_accumulate((const void*)origin_addr, *origin_count, (MPI_Datatype)(*origin_datatype), (void*)result_addr, *result_count, (MPI_Datatype)(*result_datatype), *target_rank, *target_disp, *target_count, (MPI_Datatype)(*target_datatype), (MPI_Op)(*op), (MPI_Win)(*win), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Rget_accumulate((const void*)origin_addr, *origin_count, MPI_Type_f2c(*origin_datatype), (void*)result_addr, *result_count, MPI_Type_f2c(*result_datatype), *target_rank, *target_disp, *target_count, MPI_Type_f2c(*target_datatype), MPI_Op_f2c(*op), MPI_Win_f2c(*win), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_RGET_ACCUMULATE(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *result_addr, MPI_Fint *result_count, MPI_Fint *result_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { MPI_Rget_accumulate_fortran_wrapper(origin_addr, origin_count, origin_datatype, result_addr, result_count, result_datatype, target_rank, target_disp, target_count, target_datatype, op, win, request, ierr); } _EXTERN_C_ void mpi_rget_accumulate(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *result_addr, MPI_Fint *result_count, MPI_Fint *result_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { MPI_Rget_accumulate_fortran_wrapper(origin_addr, origin_count, origin_datatype, result_addr, result_count, result_datatype, target_rank, target_disp, target_count, target_datatype, op, win, request, ierr); } _EXTERN_C_ void mpi_rget_accumulate_(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *result_addr, MPI_Fint *result_count, MPI_Fint *result_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { MPI_Rget_accumulate_fortran_wrapper(origin_addr, origin_count, origin_datatype, result_addr, result_count, result_datatype, target_rank, target_disp, target_count, target_datatype, op, win, request, ierr); } _EXTERN_C_ void mpi_rget_accumulate__(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *result_addr, MPI_Fint *result_count, MPI_Fint *result_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_count, MPI_Fint *target_datatype, MPI_Fint *op, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { MPI_Rget_accumulate_fortran_wrapper(origin_addr, origin_count, origin_datatype, result_addr, result_count, result_datatype, target_rank, target_disp, target_count, target_datatype, op, win, request, ierr); } /* ================= End Wrappers for MPI_Rget_accumulate ================= */ /* ================== C Wrappers for MPI_Rput ================== */ _EXTERN_C_ int PMPI_Rput(const void *origin_addr, int origin_count, MPI_Datatype origin_datatype, int target_rank, MPI_Aint target_disp, int target_cout, MPI_Datatype target_datatype, MPI_Win win, MPI_Request *request); _EXTERN_C_ int MPI_Rput(const void *origin_addr, int origin_count, MPI_Datatype origin_datatype, int target_rank, MPI_Aint target_disp, int target_cout, MPI_Datatype target_datatype, MPI_Win win, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Rput(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_cout, target_datatype, win, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Rput =============== */ static void MPI_Rput_fortran_wrapper(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_cout, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Rput((const void*)origin_addr, *origin_count, (MPI_Datatype)(*origin_datatype), *target_rank, *target_disp, *target_cout, (MPI_Datatype)(*target_datatype), (MPI_Win)(*win), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Rput((const void*)origin_addr, *origin_count, MPI_Type_f2c(*origin_datatype), *target_rank, *target_disp, *target_cout, MPI_Type_f2c(*target_datatype), MPI_Win_f2c(*win), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_RPUT(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_cout, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { MPI_Rput_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_cout, target_datatype, win, request, ierr); } _EXTERN_C_ void mpi_rput(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_cout, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { MPI_Rput_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_cout, target_datatype, win, request, ierr); } _EXTERN_C_ void mpi_rput_(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_cout, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { MPI_Rput_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_cout, target_datatype, win, request, ierr); } _EXTERN_C_ void mpi_rput__(MPI_Fint *origin_addr, MPI_Fint *origin_count, MPI_Fint *origin_datatype, MPI_Fint *target_rank, MPI_Aint *target_disp, MPI_Fint *target_cout, MPI_Fint *target_datatype, MPI_Fint *win, MPI_Fint *request, MPI_Fint *ierr) { MPI_Rput_fortran_wrapper(origin_addr, origin_count, origin_datatype, target_rank, target_disp, target_cout, target_datatype, win, request, ierr); } /* ================= End Wrappers for MPI_Rput ================= */ /* ================== C Wrappers for MPI_Rsend ================== */ _EXTERN_C_ int PMPI_Rsend(const void *ibuf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm); _EXTERN_C_ int MPI_Rsend(const void *ibuf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Rsend(ibuf, count, datatype, dest, tag, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Rsend =============== */ static void MPI_Rsend_fortran_wrapper(MPI_Fint *ibuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Rsend((const void*)ibuf, *count, (MPI_Datatype)(*datatype), *dest, *tag, (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Rsend((const void*)ibuf, *count, MPI_Type_f2c(*datatype), *dest, *tag, MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_RSEND(MPI_Fint *ibuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Rsend_fortran_wrapper(ibuf, count, datatype, dest, tag, comm, ierr); } _EXTERN_C_ void mpi_rsend(MPI_Fint *ibuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Rsend_fortran_wrapper(ibuf, count, datatype, dest, tag, comm, ierr); } _EXTERN_C_ void mpi_rsend_(MPI_Fint *ibuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Rsend_fortran_wrapper(ibuf, count, datatype, dest, tag, comm, ierr); } _EXTERN_C_ void mpi_rsend__(MPI_Fint *ibuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Rsend_fortran_wrapper(ibuf, count, datatype, dest, tag, comm, ierr); } /* ================= End Wrappers for MPI_Rsend ================= */ /* ================== C Wrappers for MPI_Rsend_init ================== */ _EXTERN_C_ int PMPI_Rsend_init(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Rsend_init(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Rsend_init(buf, count, datatype, dest, tag, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Rsend_init =============== */ static void MPI_Rsend_init_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Rsend_init((const void*)buf, *count, (MPI_Datatype)(*datatype), *dest, *tag, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Rsend_init((const void*)buf, *count, MPI_Type_f2c(*datatype), *dest, *tag, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_RSEND_INIT(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Rsend_init_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_rsend_init(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Rsend_init_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_rsend_init_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Rsend_init_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_rsend_init__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Rsend_init_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } /* ================= End Wrappers for MPI_Rsend_init ================= */ /* ================== C Wrappers for MPI_Scan ================== */ _EXTERN_C_ int PMPI_Scan(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm); _EXTERN_C_ int MPI_Scan(const void *sendbuf, void *recvbuf, int count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Scan(sendbuf, recvbuf, count, datatype, op, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Scan =============== */ static void MPI_Scan_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Scan((const void*)sendbuf, (void*)recvbuf, *count, (MPI_Datatype)(*datatype), (MPI_Op)(*op), (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Scan((const void*)sendbuf, (void*)recvbuf, *count, MPI_Type_f2c(*datatype), MPI_Op_f2c(*op), MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_SCAN(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Scan_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, ierr); } _EXTERN_C_ void mpi_scan(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Scan_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, ierr); } _EXTERN_C_ void mpi_scan_(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Scan_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, ierr); } _EXTERN_C_ void mpi_scan__(MPI_Fint *sendbuf, MPI_Fint *recvbuf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *op, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Scan_fortran_wrapper(sendbuf, recvbuf, count, datatype, op, comm, ierr); } /* ================= End Wrappers for MPI_Scan ================= */ /* ================== C Wrappers for MPI_Scatter ================== */ _EXTERN_C_ int PMPI_Scatter(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm); _EXTERN_C_ int MPI_Scatter(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Scatter(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Scatter =============== */ static void MPI_Scatter_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Scatter((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), (void*)recvbuf, *recvcount, (MPI_Datatype)(*recvtype), *root, (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Scatter((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), (void*)recvbuf, *recvcount, MPI_Type_f2c(*recvtype), *root, MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_SCATTER(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Scatter_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, ierr); } _EXTERN_C_ void mpi_scatter(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Scatter_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, ierr); } _EXTERN_C_ void mpi_scatter_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Scatter_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, ierr); } _EXTERN_C_ void mpi_scatter__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Scatter_fortran_wrapper(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, comm, ierr); } /* ================= End Wrappers for MPI_Scatter ================= */ /* ================== C Wrappers for MPI_Scatterv ================== */ _EXTERN_C_ int PMPI_Scatterv(const void *sendbuf, const int sendcounts[], const int displs[], MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm); _EXTERN_C_ int MPI_Scatterv(const void *sendbuf, const int sendcounts[], const int displs[], MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, int root, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Scatterv(sendbuf, sendcounts, displs, sendtype, recvbuf, recvcount, recvtype, root, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Scatterv =============== */ static void MPI_Scatterv_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint displs[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Scatterv((const void*)sendbuf, (const int*)sendcounts, (const int*)displs, (MPI_Datatype)(*sendtype), (void*)recvbuf, *recvcount, (MPI_Datatype)(*recvtype), *root, (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Scatterv((const void*)sendbuf, (const int*)sendcounts, (const int*)displs, MPI_Type_f2c(*sendtype), (void*)recvbuf, *recvcount, MPI_Type_f2c(*recvtype), *root, MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_SCATTERV(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint displs[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Scatterv_fortran_wrapper(sendbuf, sendcounts, displs, sendtype, recvbuf, recvcount, recvtype, root, comm, ierr); } _EXTERN_C_ void mpi_scatterv(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint displs[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Scatterv_fortran_wrapper(sendbuf, sendcounts, displs, sendtype, recvbuf, recvcount, recvtype, root, comm, ierr); } _EXTERN_C_ void mpi_scatterv_(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint displs[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Scatterv_fortran_wrapper(sendbuf, sendcounts, displs, sendtype, recvbuf, recvcount, recvtype, root, comm, ierr); } _EXTERN_C_ void mpi_scatterv__(MPI_Fint *sendbuf, MPI_Fint sendcounts[], MPI_Fint displs[], MPI_Fint *sendtype, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *root, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Scatterv_fortran_wrapper(sendbuf, sendcounts, displs, sendtype, recvbuf, recvcount, recvtype, root, comm, ierr); } /* ================= End Wrappers for MPI_Scatterv ================= */ /* ================== C Wrappers for MPI_Send ================== */ _EXTERN_C_ int PMPI_Send(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm); _EXTERN_C_ int MPI_Send(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX if (isolation_mode && wrapper_enabled) { _wrap_py_return_val = MPI_SUCCESS; } else { _wrap_py_return_val = PMPI_Send(buf, count, datatype, dest, tag, comm); } WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Send =============== */ static void MPI_Send_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Send((const void*)buf, *count, (MPI_Datatype)(*datatype), *dest, *tag, (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Send((const void*)buf, *count, MPI_Type_f2c(*datatype), *dest, *tag, MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_SEND(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Send_fortran_wrapper(buf, count, datatype, dest, tag, comm, ierr); } _EXTERN_C_ void mpi_send(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Send_fortran_wrapper(buf, count, datatype, dest, tag, comm, ierr); } _EXTERN_C_ void mpi_send_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Send_fortran_wrapper(buf, count, datatype, dest, tag, comm, ierr); } _EXTERN_C_ void mpi_send__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Send_fortran_wrapper(buf, count, datatype, dest, tag, comm, ierr); } /* ================= End Wrappers for MPI_Send ================= */ /* ================== C Wrappers for MPI_Send_init ================== */ _EXTERN_C_ int PMPI_Send_init(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Send_init(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Send_init(buf, count, datatype, dest, tag, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Send_init =============== */ static void MPI_Send_init_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Send_init((const void*)buf, *count, (MPI_Datatype)(*datatype), *dest, *tag, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Send_init((const void*)buf, *count, MPI_Type_f2c(*datatype), *dest, *tag, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_SEND_INIT(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Send_init_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_send_init(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Send_init_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_send_init_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Send_init_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_send_init__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Send_init_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } /* ================= End Wrappers for MPI_Send_init ================= */ /* ================== C Wrappers for MPI_Sendrecv ================== */ _EXTERN_C_ int PMPI_Sendrecv(const void *sendbuf, int sendcount, MPI_Datatype sendtype, int dest, int sendtag, void *recvbuf, int recvcount, MPI_Datatype recvtype, int source, int recvtag, MPI_Comm comm, MPI_Status *status); _EXTERN_C_ int MPI_Sendrecv(const void *sendbuf, int sendcount, MPI_Datatype sendtype, int dest, int sendtag, void *recvbuf, int recvcount, MPI_Datatype recvtype, int source, int recvtag, MPI_Comm comm, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Sendrecv(sendbuf, sendcount, sendtype, dest, sendtag, recvbuf, recvcount, recvtype, source, recvtag, comm, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Sendrecv =============== */ static void MPI_Sendrecv_fortran_wrapper(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *dest, MPI_Fint *sendtag, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *source, MPI_Fint *recvtag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Sendrecv((const void*)sendbuf, *sendcount, (MPI_Datatype)(*sendtype), *dest, *sendtag, (void*)recvbuf, *recvcount, (MPI_Datatype)(*recvtype), *source, *recvtag, (MPI_Comm)(*comm), (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_Sendrecv((const void*)sendbuf, *sendcount, MPI_Type_f2c(*sendtype), *dest, *sendtag, (void*)recvbuf, *recvcount, MPI_Type_f2c(*recvtype), *source, *recvtag, MPI_Comm_f2c(*comm), &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_SENDRECV(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *dest, MPI_Fint *sendtag, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *source, MPI_Fint *recvtag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Sendrecv_fortran_wrapper(sendbuf, sendcount, sendtype, dest, sendtag, recvbuf, recvcount, recvtype, source, recvtag, comm, status, ierr); } _EXTERN_C_ void mpi_sendrecv(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *dest, MPI_Fint *sendtag, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *source, MPI_Fint *recvtag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Sendrecv_fortran_wrapper(sendbuf, sendcount, sendtype, dest, sendtag, recvbuf, recvcount, recvtype, source, recvtag, comm, status, ierr); } _EXTERN_C_ void mpi_sendrecv_(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *dest, MPI_Fint *sendtag, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *source, MPI_Fint *recvtag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Sendrecv_fortran_wrapper(sendbuf, sendcount, sendtype, dest, sendtag, recvbuf, recvcount, recvtype, source, recvtag, comm, status, ierr); } _EXTERN_C_ void mpi_sendrecv__(MPI_Fint *sendbuf, MPI_Fint *sendcount, MPI_Fint *sendtype, MPI_Fint *dest, MPI_Fint *sendtag, MPI_Fint *recvbuf, MPI_Fint *recvcount, MPI_Fint *recvtype, MPI_Fint *source, MPI_Fint *recvtag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Sendrecv_fortran_wrapper(sendbuf, sendcount, sendtype, dest, sendtag, recvbuf, recvcount, recvtype, source, recvtag, comm, status, ierr); } /* ================= End Wrappers for MPI_Sendrecv ================= */ /* ================== C Wrappers for MPI_Sendrecv_replace ================== */ _EXTERN_C_ int PMPI_Sendrecv_replace(void *buf, int count, MPI_Datatype datatype, int dest, int sendtag, int source, int recvtag, MPI_Comm comm, MPI_Status *status); _EXTERN_C_ int MPI_Sendrecv_replace(void *buf, int count, MPI_Datatype datatype, int dest, int sendtag, int source, int recvtag, MPI_Comm comm, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Sendrecv_replace(buf, count, datatype, dest, sendtag, source, recvtag, comm, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Sendrecv_replace =============== */ static void MPI_Sendrecv_replace_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *sendtag, MPI_Fint *source, MPI_Fint *recvtag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Sendrecv_replace((void*)buf, *count, (MPI_Datatype)(*datatype), *dest, *sendtag, *source, *recvtag, (MPI_Comm)(*comm), (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_Sendrecv_replace((void*)buf, *count, MPI_Type_f2c(*datatype), *dest, *sendtag, *source, *recvtag, MPI_Comm_f2c(*comm), &temp_status); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_SENDRECV_REPLACE(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *sendtag, MPI_Fint *source, MPI_Fint *recvtag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Sendrecv_replace_fortran_wrapper(buf, count, datatype, dest, sendtag, source, recvtag, comm, status, ierr); } _EXTERN_C_ void mpi_sendrecv_replace(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *sendtag, MPI_Fint *source, MPI_Fint *recvtag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Sendrecv_replace_fortran_wrapper(buf, count, datatype, dest, sendtag, source, recvtag, comm, status, ierr); } _EXTERN_C_ void mpi_sendrecv_replace_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *sendtag, MPI_Fint *source, MPI_Fint *recvtag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Sendrecv_replace_fortran_wrapper(buf, count, datatype, dest, sendtag, source, recvtag, comm, status, ierr); } _EXTERN_C_ void mpi_sendrecv_replace__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *sendtag, MPI_Fint *source, MPI_Fint *recvtag, MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Sendrecv_replace_fortran_wrapper(buf, count, datatype, dest, sendtag, source, recvtag, comm, status, ierr); } /* ================= End Wrappers for MPI_Sendrecv_replace ================= */ /* ================== C Wrappers for MPI_Ssend ================== */ _EXTERN_C_ int PMPI_Ssend(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm); _EXTERN_C_ int MPI_Ssend(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Ssend(buf, count, datatype, dest, tag, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Ssend =============== */ static void MPI_Ssend_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Ssend((const void*)buf, *count, (MPI_Datatype)(*datatype), *dest, *tag, (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Ssend((const void*)buf, *count, MPI_Type_f2c(*datatype), *dest, *tag, MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_SSEND(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Ssend_fortran_wrapper(buf, count, datatype, dest, tag, comm, ierr); } _EXTERN_C_ void mpi_ssend(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Ssend_fortran_wrapper(buf, count, datatype, dest, tag, comm, ierr); } _EXTERN_C_ void mpi_ssend_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Ssend_fortran_wrapper(buf, count, datatype, dest, tag, comm, ierr); } _EXTERN_C_ void mpi_ssend__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Ssend_fortran_wrapper(buf, count, datatype, dest, tag, comm, ierr); } /* ================= End Wrappers for MPI_Ssend ================= */ /* ================== C Wrappers for MPI_Ssend_init ================== */ _EXTERN_C_ int PMPI_Ssend_init(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request); _EXTERN_C_ int MPI_Ssend_init(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Ssend_init(buf, count, datatype, dest, tag, comm, request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Ssend_init =============== */ static void MPI_Ssend_init_fortran_wrapper(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Ssend_init((const void*)buf, *count, (MPI_Datatype)(*datatype), *dest, *tag, (MPI_Comm)(*comm), (MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Ssend_init((const void*)buf, *count, MPI_Type_f2c(*datatype), *dest, *tag, MPI_Comm_f2c(*comm), &temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_SSEND_INIT(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ssend_init_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_ssend_init(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ssend_init_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_ssend_init_(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ssend_init_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } _EXTERN_C_ void mpi_ssend_init__(MPI_Fint *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *dest, MPI_Fint *tag, MPI_Fint *comm, MPI_Fint *request, MPI_Fint *ierr) { MPI_Ssend_init_fortran_wrapper(buf, count, datatype, dest, tag, comm, request, ierr); } /* ================= End Wrappers for MPI_Ssend_init ================= */ /* ================== C Wrappers for MPI_Start ================== */ _EXTERN_C_ int PMPI_Start(MPI_Request *request); _EXTERN_C_ int MPI_Start(MPI_Request *request) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Start(request); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Start =============== */ static void MPI_Start_fortran_wrapper(MPI_Fint *request, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Start((MPI_Request*)request); #else /* MPI-2 safe call */ MPI_Request temp_request; temp_request = MPI_Request_f2c(*request); _wrap_py_return_val = MPI_Start(&temp_request); *request = MPI_Request_c2f(temp_request); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_START(MPI_Fint *request, MPI_Fint *ierr) { MPI_Start_fortran_wrapper(request, ierr); } _EXTERN_C_ void mpi_start(MPI_Fint *request, MPI_Fint *ierr) { MPI_Start_fortran_wrapper(request, ierr); } _EXTERN_C_ void mpi_start_(MPI_Fint *request, MPI_Fint *ierr) { MPI_Start_fortran_wrapper(request, ierr); } _EXTERN_C_ void mpi_start__(MPI_Fint *request, MPI_Fint *ierr) { MPI_Start_fortran_wrapper(request, ierr); } /* ================= End Wrappers for MPI_Start ================= */ /* ================== C Wrappers for MPI_Startall ================== */ _EXTERN_C_ int PMPI_Startall(int count, MPI_Request array_of_requests[]); _EXTERN_C_ int MPI_Startall(int count, MPI_Request array_of_requests[]) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Startall(count, array_of_requests); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Startall =============== */ static void MPI_Startall_fortran_wrapper(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Startall(*count, (MPI_Request*)array_of_requests); #else /* MPI-2 safe call */ MPI_Request* temp_array_of_requests; int i; temp_array_of_requests = (MPI_Request*)malloc(sizeof(MPI_Request) * *count); for (i=0; i < *count; i++) temp_array_of_requests[i] = MPI_Request_f2c(array_of_requests[i]); _wrap_py_return_val = MPI_Startall(*count, temp_array_of_requests); for (i=0; i < *count; i++) array_of_requests[i] = MPI_Request_c2f(temp_array_of_requests[i]); free(temp_array_of_requests); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_STARTALL(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *ierr) { MPI_Startall_fortran_wrapper(count, array_of_requests, ierr); } _EXTERN_C_ void mpi_startall(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *ierr) { MPI_Startall_fortran_wrapper(count, array_of_requests, ierr); } _EXTERN_C_ void mpi_startall_(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *ierr) { MPI_Startall_fortran_wrapper(count, array_of_requests, ierr); } _EXTERN_C_ void mpi_startall__(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *ierr) { MPI_Startall_fortran_wrapper(count, array_of_requests, ierr); } /* ================= End Wrappers for MPI_Startall ================= */ /* ================== C Wrappers for MPI_Status_set_cancelled ================== */ _EXTERN_C_ int PMPI_Status_set_cancelled(MPI_Status *status, int flag); _EXTERN_C_ int MPI_Status_set_cancelled(MPI_Status *status, int flag) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Status_set_cancelled(status, flag); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Status_set_cancelled =============== */ static void MPI_Status_set_cancelled_fortran_wrapper(MPI_Fint *status, MPI_Fint *flag, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Status_set_cancelled((MPI_Status*)status, *flag); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_Status_set_cancelled(&temp_status, *flag); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_STATUS_SET_CANCELLED(MPI_Fint *status, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Status_set_cancelled_fortran_wrapper(status, flag, ierr); } _EXTERN_C_ void mpi_status_set_cancelled(MPI_Fint *status, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Status_set_cancelled_fortran_wrapper(status, flag, ierr); } _EXTERN_C_ void mpi_status_set_cancelled_(MPI_Fint *status, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Status_set_cancelled_fortran_wrapper(status, flag, ierr); } _EXTERN_C_ void mpi_status_set_cancelled__(MPI_Fint *status, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Status_set_cancelled_fortran_wrapper(status, flag, ierr); } /* ================= End Wrappers for MPI_Status_set_cancelled ================= */ /* ================== C Wrappers for MPI_Status_set_elements ================== */ _EXTERN_C_ int PMPI_Status_set_elements(MPI_Status *status, MPI_Datatype datatype, int count); _EXTERN_C_ int MPI_Status_set_elements(MPI_Status *status, MPI_Datatype datatype, int count) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Status_set_elements(status, datatype, count); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Status_set_elements =============== */ static void MPI_Status_set_elements_fortran_wrapper(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Status_set_elements((MPI_Status*)status, (MPI_Datatype)(*datatype), *count); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_Status_set_elements(&temp_status, MPI_Type_f2c(*datatype), *count); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_STATUS_SET_ELEMENTS(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Status_set_elements_fortran_wrapper(status, datatype, count, ierr); } _EXTERN_C_ void mpi_status_set_elements(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Status_set_elements_fortran_wrapper(status, datatype, count, ierr); } _EXTERN_C_ void mpi_status_set_elements_(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Status_set_elements_fortran_wrapper(status, datatype, count, ierr); } _EXTERN_C_ void mpi_status_set_elements__(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Status_set_elements_fortran_wrapper(status, datatype, count, ierr); } /* ================= End Wrappers for MPI_Status_set_elements ================= */ /* ================== C Wrappers for MPI_Status_set_elements_x ================== */ _EXTERN_C_ int PMPI_Status_set_elements_x(MPI_Status *status, MPI_Datatype datatype, MPI_Count count); _EXTERN_C_ int MPI_Status_set_elements_x(MPI_Status *status, MPI_Datatype datatype, MPI_Count count) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Status_set_elements_x(status, datatype, count); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Status_set_elements_x =============== */ static void MPI_Status_set_elements_x_fortran_wrapper(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Status_set_elements_x((MPI_Status*)status, (MPI_Datatype)(*datatype), *count); #else /* MPI-2 safe call */ MPI_Status temp_status; MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_Status_set_elements_x(&temp_status, MPI_Type_f2c(*datatype), *count); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_STATUS_SET_ELEMENTS_X(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Status_set_elements_x_fortran_wrapper(status, datatype, count, ierr); } _EXTERN_C_ void mpi_status_set_elements_x(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Status_set_elements_x_fortran_wrapper(status, datatype, count, ierr); } _EXTERN_C_ void mpi_status_set_elements_x_(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Status_set_elements_x_fortran_wrapper(status, datatype, count, ierr); } _EXTERN_C_ void mpi_status_set_elements_x__(MPI_Fint *status, MPI_Fint *datatype, MPI_Fint *count, MPI_Fint *ierr) { MPI_Status_set_elements_x_fortran_wrapper(status, datatype, count, ierr); } /* ================= End Wrappers for MPI_Status_set_elements_x ================= */ /* ================== C Wrappers for MPI_Test ================== */ _EXTERN_C_ int PMPI_Test(MPI_Request *request, int *flag, MPI_Status *status); _EXTERN_C_ int MPI_Test(MPI_Request *request, int *flag, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Test(request, flag, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Test =============== */ static void MPI_Test_fortran_wrapper(MPI_Fint *request, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Test((MPI_Request*)request, (int*)flag, (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Request temp_request; MPI_Status temp_status; temp_request = MPI_Request_f2c(*request); MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_Test(&temp_request, (int*)flag, &temp_status); *request = MPI_Request_c2f(temp_request); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TEST(MPI_Fint *request, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { MPI_Test_fortran_wrapper(request, flag, status, ierr); } _EXTERN_C_ void mpi_test(MPI_Fint *request, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { MPI_Test_fortran_wrapper(request, flag, status, ierr); } _EXTERN_C_ void mpi_test_(MPI_Fint *request, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { MPI_Test_fortran_wrapper(request, flag, status, ierr); } _EXTERN_C_ void mpi_test__(MPI_Fint *request, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { MPI_Test_fortran_wrapper(request, flag, status, ierr); } /* ================= End Wrappers for MPI_Test ================= */ /* ================== C Wrappers for MPI_Test_cancelled ================== */ _EXTERN_C_ int PMPI_Test_cancelled(const MPI_Status *status, int *flag); _EXTERN_C_ int MPI_Test_cancelled(const MPI_Status *status, int *flag) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Test_cancelled(status, flag); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Test_cancelled =============== */ static void MPI_Test_cancelled_fortran_wrapper(MPI_Fint *status, MPI_Fint *flag, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Test_cancelled((const MPI_Status*)status, (int*)flag); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TEST_CANCELLED(MPI_Fint *status, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Test_cancelled_fortran_wrapper(status, flag, ierr); } _EXTERN_C_ void mpi_test_cancelled(MPI_Fint *status, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Test_cancelled_fortran_wrapper(status, flag, ierr); } _EXTERN_C_ void mpi_test_cancelled_(MPI_Fint *status, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Test_cancelled_fortran_wrapper(status, flag, ierr); } _EXTERN_C_ void mpi_test_cancelled__(MPI_Fint *status, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Test_cancelled_fortran_wrapper(status, flag, ierr); } /* ================= End Wrappers for MPI_Test_cancelled ================= */ /* ================== C Wrappers for MPI_Testall ================== */ _EXTERN_C_ int PMPI_Testall(int count, MPI_Request array_of_requests[], int *flag, MPI_Status array_of_statuses[]); _EXTERN_C_ int MPI_Testall(int count, MPI_Request array_of_requests[], int *flag, MPI_Status array_of_statuses[]) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Testall(count, array_of_requests, flag, array_of_statuses); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Testall =============== */ static void MPI_Testall_fortran_wrapper(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *flag, MPI_Fint array_of_statuses[], MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Testall(*count, (MPI_Request*)array_of_requests, (int*)flag, (MPI_Status*)array_of_statuses); #else /* MPI-2 safe call */ MPI_Status* temp_array_of_statuses; MPI_Request* temp_array_of_requests; int i; temp_array_of_requests = (MPI_Request*)malloc(sizeof(MPI_Request) * *count); for (i=0; i < *count; i++) temp_array_of_requests[i] = MPI_Request_f2c(array_of_requests[i]); temp_array_of_statuses = (MPI_Status*)malloc(sizeof(MPI_Status) * *count); for (i=0; i < *count; i++) MPI_Status_f2c(&array_of_statuses[i], &temp_array_of_statuses[i]); _wrap_py_return_val = MPI_Testall(*count, temp_array_of_requests, (int*)flag, temp_array_of_statuses); for (i=0; i < *count; i++) array_of_requests[i] = MPI_Request_c2f(temp_array_of_requests[i]); free(temp_array_of_requests); for (i=0; i < *count; i++) MPI_Status_c2f(&temp_array_of_statuses[i], &array_of_statuses[i]); free(temp_array_of_statuses); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TESTALL(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *flag, MPI_Fint array_of_statuses[], MPI_Fint *ierr) { MPI_Testall_fortran_wrapper(count, array_of_requests, flag, array_of_statuses, ierr); } _EXTERN_C_ void mpi_testall(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *flag, MPI_Fint array_of_statuses[], MPI_Fint *ierr) { MPI_Testall_fortran_wrapper(count, array_of_requests, flag, array_of_statuses, ierr); } _EXTERN_C_ void mpi_testall_(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *flag, MPI_Fint array_of_statuses[], MPI_Fint *ierr) { MPI_Testall_fortran_wrapper(count, array_of_requests, flag, array_of_statuses, ierr); } _EXTERN_C_ void mpi_testall__(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *flag, MPI_Fint array_of_statuses[], MPI_Fint *ierr) { MPI_Testall_fortran_wrapper(count, array_of_requests, flag, array_of_statuses, ierr); } /* ================= End Wrappers for MPI_Testall ================= */ /* ================== C Wrappers for MPI_Testany ================== */ _EXTERN_C_ int PMPI_Testany(int count, MPI_Request array_of_requests[], int *index, int *flag, MPI_Status *status); _EXTERN_C_ int MPI_Testany(int count, MPI_Request array_of_requests[], int *index, int *flag, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Testany(count, array_of_requests, index, flag, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Testany =============== */ static void MPI_Testany_fortran_wrapper(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *index, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Testany(*count, (MPI_Request*)array_of_requests, (int*)index, (int*)flag, (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Request* temp_array_of_requests; MPI_Status temp_status; int i; temp_array_of_requests = (MPI_Request*)malloc(sizeof(MPI_Request) * *count); for (i=0; i < *count; i++) temp_array_of_requests[i] = MPI_Request_f2c(array_of_requests[i]); MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_Testany(*count, temp_array_of_requests, (int*)index, (int*)flag, &temp_status); for (i=0; i < *count; i++) array_of_requests[i] = MPI_Request_c2f(temp_array_of_requests[i]); free(temp_array_of_requests); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TESTANY(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *index, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { MPI_Testany_fortran_wrapper(count, array_of_requests, index, flag, status, ierr); } _EXTERN_C_ void mpi_testany(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *index, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { MPI_Testany_fortran_wrapper(count, array_of_requests, index, flag, status, ierr); } _EXTERN_C_ void mpi_testany_(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *index, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { MPI_Testany_fortran_wrapper(count, array_of_requests, index, flag, status, ierr); } _EXTERN_C_ void mpi_testany__(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *index, MPI_Fint *flag, MPI_Fint *status, MPI_Fint *ierr) { MPI_Testany_fortran_wrapper(count, array_of_requests, index, flag, status, ierr); } /* ================= End Wrappers for MPI_Testany ================= */ /* ================== C Wrappers for MPI_Testsome ================== */ _EXTERN_C_ int PMPI_Testsome(int incount, MPI_Request array_of_requests[], int *outcount, int array_of_indices[], MPI_Status array_of_statuses[]); _EXTERN_C_ int MPI_Testsome(int incount, MPI_Request array_of_requests[], int *outcount, int array_of_indices[], MPI_Status array_of_statuses[]) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Testsome(incount, array_of_requests, outcount, array_of_indices, array_of_statuses); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Testsome =============== */ static void MPI_Testsome_fortran_wrapper(MPI_Fint *incount, MPI_Fint array_of_requests[], MPI_Fint *outcount, MPI_Fint array_of_indices[], MPI_Fint array_of_statuses[], MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Testsome(*incount, (MPI_Request*)array_of_requests, (int*)outcount, (int*)array_of_indices, (MPI_Status*)array_of_statuses); #else /* MPI-2 safe call */ MPI_Status* temp_array_of_statuses; MPI_Request* temp_array_of_requests; int i; temp_array_of_requests = (MPI_Request*)malloc(sizeof(MPI_Request) * *incount); for (i=0; i < *incount; i++) temp_array_of_requests[i] = MPI_Request_f2c(array_of_requests[i]); temp_array_of_statuses = (MPI_Status*)malloc(sizeof(MPI_Status) * *incount); for (i=0; i < *incount; i++) MPI_Status_f2c(&array_of_statuses[i], &temp_array_of_statuses[i]); _wrap_py_return_val = MPI_Testsome(*incount, temp_array_of_requests, (int*)outcount, (int*)array_of_indices, temp_array_of_statuses); for (i=0; i < *incount; i++) array_of_requests[i] = MPI_Request_c2f(temp_array_of_requests[i]); free(temp_array_of_requests); for (i=0; i < *incount; i++) MPI_Status_c2f(&temp_array_of_statuses[i], &array_of_statuses[i]); free(temp_array_of_statuses); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TESTSOME(MPI_Fint *incount, MPI_Fint array_of_requests[], MPI_Fint *outcount, MPI_Fint array_of_indices[], MPI_Fint array_of_statuses[], MPI_Fint *ierr) { MPI_Testsome_fortran_wrapper(incount, array_of_requests, outcount, array_of_indices, array_of_statuses, ierr); } _EXTERN_C_ void mpi_testsome(MPI_Fint *incount, MPI_Fint array_of_requests[], MPI_Fint *outcount, MPI_Fint array_of_indices[], MPI_Fint array_of_statuses[], MPI_Fint *ierr) { MPI_Testsome_fortran_wrapper(incount, array_of_requests, outcount, array_of_indices, array_of_statuses, ierr); } _EXTERN_C_ void mpi_testsome_(MPI_Fint *incount, MPI_Fint array_of_requests[], MPI_Fint *outcount, MPI_Fint array_of_indices[], MPI_Fint array_of_statuses[], MPI_Fint *ierr) { MPI_Testsome_fortran_wrapper(incount, array_of_requests, outcount, array_of_indices, array_of_statuses, ierr); } _EXTERN_C_ void mpi_testsome__(MPI_Fint *incount, MPI_Fint array_of_requests[], MPI_Fint *outcount, MPI_Fint array_of_indices[], MPI_Fint array_of_statuses[], MPI_Fint *ierr) { MPI_Testsome_fortran_wrapper(incount, array_of_requests, outcount, array_of_indices, array_of_statuses, ierr); } /* ================= End Wrappers for MPI_Testsome ================= */ /* ================== C Wrappers for MPI_Topo_test ================== */ _EXTERN_C_ int PMPI_Topo_test(MPI_Comm comm, int *status); _EXTERN_C_ int MPI_Topo_test(MPI_Comm comm, int *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Topo_test(comm, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Topo_test =============== */ static void MPI_Topo_test_fortran_wrapper(MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Topo_test((MPI_Comm)(*comm), (int*)status); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Topo_test(MPI_Comm_f2c(*comm), (int*)status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TOPO_TEST(MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Topo_test_fortran_wrapper(comm, status, ierr); } _EXTERN_C_ void mpi_topo_test(MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Topo_test_fortran_wrapper(comm, status, ierr); } _EXTERN_C_ void mpi_topo_test_(MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Topo_test_fortran_wrapper(comm, status, ierr); } _EXTERN_C_ void mpi_topo_test__(MPI_Fint *comm, MPI_Fint *status, MPI_Fint *ierr) { MPI_Topo_test_fortran_wrapper(comm, status, ierr); } /* ================= End Wrappers for MPI_Topo_test ================= */ /* ================== C Wrappers for MPI_Type_commit ================== */ _EXTERN_C_ int PMPI_Type_commit(MPI_Datatype *type); _EXTERN_C_ int MPI_Type_commit(MPI_Datatype *type) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_commit(type); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_commit =============== */ static void MPI_Type_commit_fortran_wrapper(MPI_Fint *type, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_commit((MPI_Datatype*)type); #else /* MPI-2 safe call */ MPI_Datatype temp_type; temp_type = MPI_Type_f2c(*type); _wrap_py_return_val = MPI_Type_commit(&temp_type); *type = MPI_Type_c2f(temp_type); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_COMMIT(MPI_Fint *type, MPI_Fint *ierr) { MPI_Type_commit_fortran_wrapper(type, ierr); } _EXTERN_C_ void mpi_type_commit(MPI_Fint *type, MPI_Fint *ierr) { MPI_Type_commit_fortran_wrapper(type, ierr); } _EXTERN_C_ void mpi_type_commit_(MPI_Fint *type, MPI_Fint *ierr) { MPI_Type_commit_fortran_wrapper(type, ierr); } _EXTERN_C_ void mpi_type_commit__(MPI_Fint *type, MPI_Fint *ierr) { MPI_Type_commit_fortran_wrapper(type, ierr); } /* ================= End Wrappers for MPI_Type_commit ================= */ /* ================== C Wrappers for MPI_Type_contiguous ================== */ _EXTERN_C_ int PMPI_Type_contiguous(int count, MPI_Datatype oldtype, MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_contiguous(int count, MPI_Datatype oldtype, MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_contiguous(count, oldtype, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_contiguous =============== */ static void MPI_Type_contiguous_fortran_wrapper(MPI_Fint *count, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_contiguous(*count, (MPI_Datatype)(*oldtype), (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_contiguous(*count, MPI_Type_f2c(*oldtype), &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_CONTIGUOUS(MPI_Fint *count, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_contiguous_fortran_wrapper(count, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_contiguous(MPI_Fint *count, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_contiguous_fortran_wrapper(count, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_contiguous_(MPI_Fint *count, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_contiguous_fortran_wrapper(count, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_contiguous__(MPI_Fint *count, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_contiguous_fortran_wrapper(count, oldtype, newtype, ierr); } /* ================= End Wrappers for MPI_Type_contiguous ================= */ /* ================== C Wrappers for MPI_Type_create_darray ================== */ _EXTERN_C_ int PMPI_Type_create_darray(int size, int rank, int ndims, const int gsize_array[], const int distrib_array[], const int darg_array[], const int psize_array[], int order, MPI_Datatype oldtype, MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_create_darray(int size, int rank, int ndims, const int gsize_array[], const int distrib_array[], const int darg_array[], const int psize_array[], int order, MPI_Datatype oldtype, MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_create_darray(size, rank, ndims, gsize_array, distrib_array, darg_array, psize_array, order, oldtype, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_create_darray =============== */ static void MPI_Type_create_darray_fortran_wrapper(MPI_Fint *size, MPI_Fint *rank, MPI_Fint *ndims, MPI_Fint gsize_array[], MPI_Fint distrib_array[], MPI_Fint darg_array[], MPI_Fint psize_array[], MPI_Fint *order, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_create_darray(*size, *rank, *ndims, (const int*)gsize_array, (const int*)distrib_array, (const int*)darg_array, (const int*)psize_array, *order, (MPI_Datatype)(*oldtype), (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_create_darray(*size, *rank, *ndims, (const int*)gsize_array, (const int*)distrib_array, (const int*)darg_array, (const int*)psize_array, *order, MPI_Type_f2c(*oldtype), &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_CREATE_DARRAY(MPI_Fint *size, MPI_Fint *rank, MPI_Fint *ndims, MPI_Fint gsize_array[], MPI_Fint distrib_array[], MPI_Fint darg_array[], MPI_Fint psize_array[], MPI_Fint *order, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_darray_fortran_wrapper(size, rank, ndims, gsize_array, distrib_array, darg_array, psize_array, order, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_darray(MPI_Fint *size, MPI_Fint *rank, MPI_Fint *ndims, MPI_Fint gsize_array[], MPI_Fint distrib_array[], MPI_Fint darg_array[], MPI_Fint psize_array[], MPI_Fint *order, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_darray_fortran_wrapper(size, rank, ndims, gsize_array, distrib_array, darg_array, psize_array, order, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_darray_(MPI_Fint *size, MPI_Fint *rank, MPI_Fint *ndims, MPI_Fint gsize_array[], MPI_Fint distrib_array[], MPI_Fint darg_array[], MPI_Fint psize_array[], MPI_Fint *order, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_darray_fortran_wrapper(size, rank, ndims, gsize_array, distrib_array, darg_array, psize_array, order, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_darray__(MPI_Fint *size, MPI_Fint *rank, MPI_Fint *ndims, MPI_Fint gsize_array[], MPI_Fint distrib_array[], MPI_Fint darg_array[], MPI_Fint psize_array[], MPI_Fint *order, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_darray_fortran_wrapper(size, rank, ndims, gsize_array, distrib_array, darg_array, psize_array, order, oldtype, newtype, ierr); } /* ================= End Wrappers for MPI_Type_create_darray ================= */ /* ================== C Wrappers for MPI_Type_create_f90_complex ================== */ _EXTERN_C_ int PMPI_Type_create_f90_complex(int p, int r, MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_create_f90_complex(int p, int r, MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_create_f90_complex(p, r, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_create_f90_complex =============== */ static void MPI_Type_create_f90_complex_fortran_wrapper(MPI_Fint *p, MPI_Fint *r, MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_create_f90_complex(*p, *r, (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_create_f90_complex(*p, *r, &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_CREATE_F90_COMPLEX(MPI_Fint *p, MPI_Fint *r, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_f90_complex_fortran_wrapper(p, r, newtype, ierr); } _EXTERN_C_ void mpi_type_create_f90_complex(MPI_Fint *p, MPI_Fint *r, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_f90_complex_fortran_wrapper(p, r, newtype, ierr); } _EXTERN_C_ void mpi_type_create_f90_complex_(MPI_Fint *p, MPI_Fint *r, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_f90_complex_fortran_wrapper(p, r, newtype, ierr); } _EXTERN_C_ void mpi_type_create_f90_complex__(MPI_Fint *p, MPI_Fint *r, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_f90_complex_fortran_wrapper(p, r, newtype, ierr); } /* ================= End Wrappers for MPI_Type_create_f90_complex ================= */ /* ================== C Wrappers for MPI_Type_create_f90_integer ================== */ _EXTERN_C_ int PMPI_Type_create_f90_integer(int r, MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_create_f90_integer(int r, MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_create_f90_integer(r, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_create_f90_integer =============== */ static void MPI_Type_create_f90_integer_fortran_wrapper(MPI_Fint *r, MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_create_f90_integer(*r, (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_create_f90_integer(*r, &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_CREATE_F90_INTEGER(MPI_Fint *r, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_f90_integer_fortran_wrapper(r, newtype, ierr); } _EXTERN_C_ void mpi_type_create_f90_integer(MPI_Fint *r, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_f90_integer_fortran_wrapper(r, newtype, ierr); } _EXTERN_C_ void mpi_type_create_f90_integer_(MPI_Fint *r, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_f90_integer_fortran_wrapper(r, newtype, ierr); } _EXTERN_C_ void mpi_type_create_f90_integer__(MPI_Fint *r, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_f90_integer_fortran_wrapper(r, newtype, ierr); } /* ================= End Wrappers for MPI_Type_create_f90_integer ================= */ /* ================== C Wrappers for MPI_Type_create_f90_real ================== */ _EXTERN_C_ int PMPI_Type_create_f90_real(int p, int r, MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_create_f90_real(int p, int r, MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_create_f90_real(p, r, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_create_f90_real =============== */ static void MPI_Type_create_f90_real_fortran_wrapper(MPI_Fint *p, MPI_Fint *r, MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_create_f90_real(*p, *r, (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_create_f90_real(*p, *r, &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_CREATE_F90_REAL(MPI_Fint *p, MPI_Fint *r, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_f90_real_fortran_wrapper(p, r, newtype, ierr); } _EXTERN_C_ void mpi_type_create_f90_real(MPI_Fint *p, MPI_Fint *r, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_f90_real_fortran_wrapper(p, r, newtype, ierr); } _EXTERN_C_ void mpi_type_create_f90_real_(MPI_Fint *p, MPI_Fint *r, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_f90_real_fortran_wrapper(p, r, newtype, ierr); } _EXTERN_C_ void mpi_type_create_f90_real__(MPI_Fint *p, MPI_Fint *r, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_f90_real_fortran_wrapper(p, r, newtype, ierr); } /* ================= End Wrappers for MPI_Type_create_f90_real ================= */ /* ================== C Wrappers for MPI_Type_create_hindexed ================== */ _EXTERN_C_ int PMPI_Type_create_hindexed(int count, const int array_of_blocklengths[], const MPI_Aint array_of_displacements[], MPI_Datatype oldtype, MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_create_hindexed(int count, const int array_of_blocklengths[], const MPI_Aint array_of_displacements[], MPI_Datatype oldtype, MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_create_hindexed(count, array_of_blocklengths, array_of_displacements, oldtype, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_create_hindexed =============== */ static void MPI_Type_create_hindexed_fortran_wrapper(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_create_hindexed(*count, (const int*)array_of_blocklengths, (const MPI_Aint*)array_of_displacements, (MPI_Datatype)(*oldtype), (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_create_hindexed(*count, (const int*)array_of_blocklengths, (const MPI_Aint*)array_of_displacements, MPI_Type_f2c(*oldtype), &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_CREATE_HINDEXED(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_hindexed_fortran_wrapper(count, array_of_blocklengths, array_of_displacements, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_hindexed(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_hindexed_fortran_wrapper(count, array_of_blocklengths, array_of_displacements, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_hindexed_(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_hindexed_fortran_wrapper(count, array_of_blocklengths, array_of_displacements, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_hindexed__(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_hindexed_fortran_wrapper(count, array_of_blocklengths, array_of_displacements, oldtype, newtype, ierr); } /* ================= End Wrappers for MPI_Type_create_hindexed ================= */ /* ================== C Wrappers for MPI_Type_create_hindexed_block ================== */ _EXTERN_C_ int PMPI_Type_create_hindexed_block(int count, int blocklength, const MPI_Aint array_of_displacements[], MPI_Datatype oldtype, MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_create_hindexed_block(int count, int blocklength, const MPI_Aint array_of_displacements[], MPI_Datatype oldtype, MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_create_hindexed_block(count, blocklength, array_of_displacements, oldtype, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_create_hindexed_block =============== */ static void MPI_Type_create_hindexed_block_fortran_wrapper(MPI_Fint *count, MPI_Fint *blocklength, MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_create_hindexed_block(*count, *blocklength, (const MPI_Aint*)array_of_displacements, (MPI_Datatype)(*oldtype), (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_create_hindexed_block(*count, *blocklength, (const MPI_Aint*)array_of_displacements, MPI_Type_f2c(*oldtype), &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_CREATE_HINDEXED_BLOCK(MPI_Fint *count, MPI_Fint *blocklength, MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_hindexed_block_fortran_wrapper(count, blocklength, array_of_displacements, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_hindexed_block(MPI_Fint *count, MPI_Fint *blocklength, MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_hindexed_block_fortran_wrapper(count, blocklength, array_of_displacements, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_hindexed_block_(MPI_Fint *count, MPI_Fint *blocklength, MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_hindexed_block_fortran_wrapper(count, blocklength, array_of_displacements, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_hindexed_block__(MPI_Fint *count, MPI_Fint *blocklength, MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_hindexed_block_fortran_wrapper(count, blocklength, array_of_displacements, oldtype, newtype, ierr); } /* ================= End Wrappers for MPI_Type_create_hindexed_block ================= */ /* ================== C Wrappers for MPI_Type_create_hvector ================== */ _EXTERN_C_ int PMPI_Type_create_hvector(int count, int blocklength, MPI_Aint stride, MPI_Datatype oldtype, MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_create_hvector(int count, int blocklength, MPI_Aint stride, MPI_Datatype oldtype, MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_create_hvector(count, blocklength, stride, oldtype, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_create_hvector =============== */ static void MPI_Type_create_hvector_fortran_wrapper(MPI_Fint *count, MPI_Fint *blocklength, MPI_Aint *stride, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_create_hvector(*count, *blocklength, *stride, (MPI_Datatype)(*oldtype), (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_create_hvector(*count, *blocklength, *stride, MPI_Type_f2c(*oldtype), &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_CREATE_HVECTOR(MPI_Fint *count, MPI_Fint *blocklength, MPI_Aint *stride, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_hvector_fortran_wrapper(count, blocklength, stride, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_hvector(MPI_Fint *count, MPI_Fint *blocklength, MPI_Aint *stride, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_hvector_fortran_wrapper(count, blocklength, stride, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_hvector_(MPI_Fint *count, MPI_Fint *blocklength, MPI_Aint *stride, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_hvector_fortran_wrapper(count, blocklength, stride, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_hvector__(MPI_Fint *count, MPI_Fint *blocklength, MPI_Aint *stride, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_hvector_fortran_wrapper(count, blocklength, stride, oldtype, newtype, ierr); } /* ================= End Wrappers for MPI_Type_create_hvector ================= */ /* ================== C Wrappers for MPI_Type_create_indexed_block ================== */ _EXTERN_C_ int PMPI_Type_create_indexed_block(int count, int blocklength, const int array_of_displacements[], MPI_Datatype oldtype, MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_create_indexed_block(int count, int blocklength, const int array_of_displacements[], MPI_Datatype oldtype, MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_create_indexed_block(count, blocklength, array_of_displacements, oldtype, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_create_indexed_block =============== */ static void MPI_Type_create_indexed_block_fortran_wrapper(MPI_Fint *count, MPI_Fint *blocklength, MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_create_indexed_block(*count, *blocklength, (const int*)array_of_displacements, (MPI_Datatype)(*oldtype), (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_create_indexed_block(*count, *blocklength, (const int*)array_of_displacements, MPI_Type_f2c(*oldtype), &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_CREATE_INDEXED_BLOCK(MPI_Fint *count, MPI_Fint *blocklength, MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_indexed_block_fortran_wrapper(count, blocklength, array_of_displacements, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_indexed_block(MPI_Fint *count, MPI_Fint *blocklength, MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_indexed_block_fortran_wrapper(count, blocklength, array_of_displacements, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_indexed_block_(MPI_Fint *count, MPI_Fint *blocklength, MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_indexed_block_fortran_wrapper(count, blocklength, array_of_displacements, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_indexed_block__(MPI_Fint *count, MPI_Fint *blocklength, MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_indexed_block_fortran_wrapper(count, blocklength, array_of_displacements, oldtype, newtype, ierr); } /* ================= End Wrappers for MPI_Type_create_indexed_block ================= */ /* ================== C Wrappers for MPI_Type_create_keyval ================== */ _EXTERN_C_ int PMPI_Type_create_keyval(MPI_Type_copy_attr_function *type_copy_attr_fn, MPI_Type_delete_attr_function *type_delete_attr_fn, int *type_keyval, void *extra_state); _EXTERN_C_ int MPI_Type_create_keyval(MPI_Type_copy_attr_function *type_copy_attr_fn, MPI_Type_delete_attr_function *type_delete_attr_fn, int *type_keyval, void *extra_state) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_create_keyval(type_copy_attr_fn, type_delete_attr_fn, type_keyval, extra_state); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_create_keyval =============== */ static void MPI_Type_create_keyval_fortran_wrapper(MPI_Type_copy_attr_function *type_copy_attr_fn, MPI_Type_delete_attr_function *type_delete_attr_fn, MPI_Fint *type_keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Type_create_keyval((MPI_Type_copy_attr_function*)type_copy_attr_fn, (MPI_Type_delete_attr_function*)type_delete_attr_fn, (int*)type_keyval, (void*)extra_state); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_CREATE_KEYVAL(MPI_Type_copy_attr_function *type_copy_attr_fn, MPI_Type_delete_attr_function *type_delete_attr_fn, MPI_Fint *type_keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Type_create_keyval_fortran_wrapper(type_copy_attr_fn, type_delete_attr_fn, type_keyval, extra_state, ierr); } _EXTERN_C_ void mpi_type_create_keyval(MPI_Type_copy_attr_function *type_copy_attr_fn, MPI_Type_delete_attr_function *type_delete_attr_fn, MPI_Fint *type_keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Type_create_keyval_fortran_wrapper(type_copy_attr_fn, type_delete_attr_fn, type_keyval, extra_state, ierr); } _EXTERN_C_ void mpi_type_create_keyval_(MPI_Type_copy_attr_function *type_copy_attr_fn, MPI_Type_delete_attr_function *type_delete_attr_fn, MPI_Fint *type_keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Type_create_keyval_fortran_wrapper(type_copy_attr_fn, type_delete_attr_fn, type_keyval, extra_state, ierr); } _EXTERN_C_ void mpi_type_create_keyval__(MPI_Type_copy_attr_function *type_copy_attr_fn, MPI_Type_delete_attr_function *type_delete_attr_fn, MPI_Fint *type_keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Type_create_keyval_fortran_wrapper(type_copy_attr_fn, type_delete_attr_fn, type_keyval, extra_state, ierr); } /* ================= End Wrappers for MPI_Type_create_keyval ================= */ /* ================== C Wrappers for MPI_Type_create_resized ================== */ _EXTERN_C_ int PMPI_Type_create_resized(MPI_Datatype oldtype, MPI_Aint lb, MPI_Aint extent, MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_create_resized(MPI_Datatype oldtype, MPI_Aint lb, MPI_Aint extent, MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_create_resized(oldtype, lb, extent, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_create_resized =============== */ static void MPI_Type_create_resized_fortran_wrapper(MPI_Fint *oldtype, MPI_Aint *lb, MPI_Aint *extent, MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_create_resized((MPI_Datatype)(*oldtype), *lb, *extent, (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_create_resized(MPI_Type_f2c(*oldtype), *lb, *extent, &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_CREATE_RESIZED(MPI_Fint *oldtype, MPI_Aint *lb, MPI_Aint *extent, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_resized_fortran_wrapper(oldtype, lb, extent, newtype, ierr); } _EXTERN_C_ void mpi_type_create_resized(MPI_Fint *oldtype, MPI_Aint *lb, MPI_Aint *extent, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_resized_fortran_wrapper(oldtype, lb, extent, newtype, ierr); } _EXTERN_C_ void mpi_type_create_resized_(MPI_Fint *oldtype, MPI_Aint *lb, MPI_Aint *extent, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_resized_fortran_wrapper(oldtype, lb, extent, newtype, ierr); } _EXTERN_C_ void mpi_type_create_resized__(MPI_Fint *oldtype, MPI_Aint *lb, MPI_Aint *extent, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_resized_fortran_wrapper(oldtype, lb, extent, newtype, ierr); } /* ================= End Wrappers for MPI_Type_create_resized ================= */ /* ================== C Wrappers for MPI_Type_create_struct ================== */ /* Does not work with ICON this way. */ #if 0 _EXTERN_C_ int PMPI_Type_create_struct(int count, const int array_of_block_lengths[], const MPI_Aint array_of_displacements[], const MPI_Datatype array_of_types[], MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_create_struct(int count, const int array_of_block_lengths[], const MPI_Aint array_of_displacements[], const MPI_Datatype array_of_types[], MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_create_struct(count, array_of_block_lengths, array_of_displacements, array_of_types, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_create_struct =============== */ static void MPI_Type_create_struct_fortran_wrapper(MPI_Fint *count, MPI_Fint array_of_block_lengths[], MPI_Fint array_of_displacements[], MPI_Fint array_of_types[], MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_create_struct(*count, (const int*)array_of_block_lengths, (const MPI_Aint*)array_of_displacements, (const MPI_Datatype*)array_of_types, (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_create_struct(*count, (const int*)array_of_block_lengths, (const MPI_Aint*)array_of_displacements, (const MPI_Datatype*)array_of_types, &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_CREATE_STRUCT(MPI_Fint *count, MPI_Fint array_of_block_lengths[], MPI_Fint array_of_displacements[], MPI_Fint array_of_types[], MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_struct_fortran_wrapper(count, array_of_block_lengths, array_of_displacements, array_of_types, newtype, ierr); } _EXTERN_C_ void mpi_type_create_struct(MPI_Fint *count, MPI_Fint array_of_block_lengths[], MPI_Fint array_of_displacements[], MPI_Fint array_of_types[], MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_struct_fortran_wrapper(count, array_of_block_lengths, array_of_displacements, array_of_types, newtype, ierr); } _EXTERN_C_ void mpi_type_create_struct_(MPI_Fint *count, MPI_Fint array_of_block_lengths[], MPI_Fint array_of_displacements[], MPI_Fint array_of_types[], MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_struct_fortran_wrapper(count, array_of_block_lengths, array_of_displacements, array_of_types, newtype, ierr); } _EXTERN_C_ void mpi_type_create_struct__(MPI_Fint *count, MPI_Fint array_of_block_lengths[], MPI_Fint array_of_displacements[], MPI_Fint array_of_types[], MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_struct_fortran_wrapper(count, array_of_block_lengths, array_of_displacements, array_of_types, newtype, ierr); } /* ================= End Wrappers for MPI_Type_create_struct ================= */ #endif /* ================== C Wrappers for MPI_Type_create_subarray ================== */ _EXTERN_C_ int PMPI_Type_create_subarray(int ndims, const int size_array[], const int subsize_array[], const int start_array[], int order, MPI_Datatype oldtype, MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_create_subarray(int ndims, const int size_array[], const int subsize_array[], const int start_array[], int order, MPI_Datatype oldtype, MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_create_subarray(ndims, size_array, subsize_array, start_array, order, oldtype, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_create_subarray =============== */ static void MPI_Type_create_subarray_fortran_wrapper(MPI_Fint *ndims, MPI_Fint size_array[], MPI_Fint subsize_array[], MPI_Fint start_array[], MPI_Fint *order, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_create_subarray(*ndims, (const int*)size_array, (const int*)subsize_array, (const int*)start_array, *order, (MPI_Datatype)(*oldtype), (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_create_subarray(*ndims, (const int*)size_array, (const int*)subsize_array, (const int*)start_array, *order, MPI_Type_f2c(*oldtype), &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_CREATE_SUBARRAY(MPI_Fint *ndims, MPI_Fint size_array[], MPI_Fint subsize_array[], MPI_Fint start_array[], MPI_Fint *order, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_subarray_fortran_wrapper(ndims, size_array, subsize_array, start_array, order, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_subarray(MPI_Fint *ndims, MPI_Fint size_array[], MPI_Fint subsize_array[], MPI_Fint start_array[], MPI_Fint *order, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_subarray_fortran_wrapper(ndims, size_array, subsize_array, start_array, order, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_subarray_(MPI_Fint *ndims, MPI_Fint size_array[], MPI_Fint subsize_array[], MPI_Fint start_array[], MPI_Fint *order, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_subarray_fortran_wrapper(ndims, size_array, subsize_array, start_array, order, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_create_subarray__(MPI_Fint *ndims, MPI_Fint size_array[], MPI_Fint subsize_array[], MPI_Fint start_array[], MPI_Fint *order, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_create_subarray_fortran_wrapper(ndims, size_array, subsize_array, start_array, order, oldtype, newtype, ierr); } /* ================= End Wrappers for MPI_Type_create_subarray ================= */ /* ================== C Wrappers for MPI_Type_delete_attr ================== */ _EXTERN_C_ int PMPI_Type_delete_attr(MPI_Datatype type, int type_keyval); _EXTERN_C_ int MPI_Type_delete_attr(MPI_Datatype type, int type_keyval) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_delete_attr(type, type_keyval); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_delete_attr =============== */ static void MPI_Type_delete_attr_fortran_wrapper(MPI_Fint *type, MPI_Fint *type_keyval, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_delete_attr((MPI_Datatype)(*type), *type_keyval); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Type_delete_attr(MPI_Type_f2c(*type), *type_keyval); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_DELETE_ATTR(MPI_Fint *type, MPI_Fint *type_keyval, MPI_Fint *ierr) { MPI_Type_delete_attr_fortran_wrapper(type, type_keyval, ierr); } _EXTERN_C_ void mpi_type_delete_attr(MPI_Fint *type, MPI_Fint *type_keyval, MPI_Fint *ierr) { MPI_Type_delete_attr_fortran_wrapper(type, type_keyval, ierr); } _EXTERN_C_ void mpi_type_delete_attr_(MPI_Fint *type, MPI_Fint *type_keyval, MPI_Fint *ierr) { MPI_Type_delete_attr_fortran_wrapper(type, type_keyval, ierr); } _EXTERN_C_ void mpi_type_delete_attr__(MPI_Fint *type, MPI_Fint *type_keyval, MPI_Fint *ierr) { MPI_Type_delete_attr_fortran_wrapper(type, type_keyval, ierr); } /* ================= End Wrappers for MPI_Type_delete_attr ================= */ /* ================== C Wrappers for MPI_Type_dup ================== */ _EXTERN_C_ int PMPI_Type_dup(MPI_Datatype type, MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_dup(MPI_Datatype type, MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_dup(type, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_dup =============== */ static void MPI_Type_dup_fortran_wrapper(MPI_Fint *type, MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_dup((MPI_Datatype)(*type), (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_dup(MPI_Type_f2c(*type), &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_DUP(MPI_Fint *type, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_dup_fortran_wrapper(type, newtype, ierr); } _EXTERN_C_ void mpi_type_dup(MPI_Fint *type, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_dup_fortran_wrapper(type, newtype, ierr); } _EXTERN_C_ void mpi_type_dup_(MPI_Fint *type, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_dup_fortran_wrapper(type, newtype, ierr); } _EXTERN_C_ void mpi_type_dup__(MPI_Fint *type, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_dup_fortran_wrapper(type, newtype, ierr); } /* ================= End Wrappers for MPI_Type_dup ================= */ /* ================== C Wrappers for MPI_Type_extent ================== */ _EXTERN_C_ int PMPI_Type_extent(MPI_Datatype type, MPI_Aint *extent); _EXTERN_C_ int MPI_Type_extent(MPI_Datatype type, MPI_Aint *extent) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_extent(type, extent); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_extent =============== */ static void MPI_Type_extent_fortran_wrapper(MPI_Fint *type, MPI_Aint *extent, MPI_Fint *ierr) { int _wrap_py_return_val = 0; WRAP_MPI_CALL_PREFIX #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_extent((MPI_Datatype)(*type), (MPI_Aint*)extent); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Type_extent(MPI_Type_f2c(*type), (MPI_Aint*)extent); #endif /* MPICH test */ WRAP_MPI_CALL_POSTFIX *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_EXTENT(MPI_Fint *type, MPI_Aint *extent, MPI_Fint *ierr) { MPI_Type_extent_fortran_wrapper(type, extent, ierr); } _EXTERN_C_ void mpi_type_extent(MPI_Fint *type, MPI_Aint *extent, MPI_Fint *ierr) { MPI_Type_extent_fortran_wrapper(type, extent, ierr); } _EXTERN_C_ void mpi_type_extent_(MPI_Fint *type, MPI_Aint *extent, MPI_Fint *ierr) { MPI_Type_extent_fortran_wrapper(type, extent, ierr); } _EXTERN_C_ void mpi_type_extent__(MPI_Fint *type, MPI_Aint *extent, MPI_Fint *ierr) { MPI_Type_extent_fortran_wrapper(type, extent, ierr); } /* ================= End Wrappers for MPI_Type_extent ================= */ /* ================== C Wrappers for MPI_Type_free ================== */ _EXTERN_C_ int PMPI_Type_free(MPI_Datatype *type); _EXTERN_C_ int MPI_Type_free(MPI_Datatype *type) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_free(type); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_free =============== */ static void MPI_Type_free_fortran_wrapper(MPI_Fint *type, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_free((MPI_Datatype*)type); #else /* MPI-2 safe call */ MPI_Datatype temp_type; temp_type = MPI_Type_f2c(*type); _wrap_py_return_val = MPI_Type_free(&temp_type); *type = MPI_Type_c2f(temp_type); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_FREE(MPI_Fint *type, MPI_Fint *ierr) { MPI_Type_free_fortran_wrapper(type, ierr); } _EXTERN_C_ void mpi_type_free(MPI_Fint *type, MPI_Fint *ierr) { MPI_Type_free_fortran_wrapper(type, ierr); } _EXTERN_C_ void mpi_type_free_(MPI_Fint *type, MPI_Fint *ierr) { MPI_Type_free_fortran_wrapper(type, ierr); } _EXTERN_C_ void mpi_type_free__(MPI_Fint *type, MPI_Fint *ierr) { MPI_Type_free_fortran_wrapper(type, ierr); } /* ================= End Wrappers for MPI_Type_free ================= */ /* ================== C Wrappers for MPI_Type_free_keyval ================== */ _EXTERN_C_ int PMPI_Type_free_keyval(int *type_keyval); _EXTERN_C_ int MPI_Type_free_keyval(int *type_keyval) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_free_keyval(type_keyval); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_free_keyval =============== */ static void MPI_Type_free_keyval_fortran_wrapper(MPI_Fint *type_keyval, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Type_free_keyval((int*)type_keyval); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_FREE_KEYVAL(MPI_Fint *type_keyval, MPI_Fint *ierr) { MPI_Type_free_keyval_fortran_wrapper(type_keyval, ierr); } _EXTERN_C_ void mpi_type_free_keyval(MPI_Fint *type_keyval, MPI_Fint *ierr) { MPI_Type_free_keyval_fortran_wrapper(type_keyval, ierr); } _EXTERN_C_ void mpi_type_free_keyval_(MPI_Fint *type_keyval, MPI_Fint *ierr) { MPI_Type_free_keyval_fortran_wrapper(type_keyval, ierr); } _EXTERN_C_ void mpi_type_free_keyval__(MPI_Fint *type_keyval, MPI_Fint *ierr) { MPI_Type_free_keyval_fortran_wrapper(type_keyval, ierr); } /* ================= End Wrappers for MPI_Type_free_keyval ================= */ /* ================== C Wrappers for MPI_Type_get_attr ================== */ _EXTERN_C_ int PMPI_Type_get_attr(MPI_Datatype type, int type_keyval, void *attribute_val, int *flag); _EXTERN_C_ int MPI_Type_get_attr(MPI_Datatype type, int type_keyval, void *attribute_val, int *flag) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_get_attr(type, type_keyval, attribute_val, flag); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_get_attr =============== */ static void MPI_Type_get_attr_fortran_wrapper(MPI_Fint *type, MPI_Fint *type_keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_get_attr((MPI_Datatype)(*type), *type_keyval, (void*)attribute_val, (int*)flag); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Type_get_attr(MPI_Type_f2c(*type), *type_keyval, (void*)attribute_val, (int*)flag); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_GET_ATTR(MPI_Fint *type, MPI_Fint *type_keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Type_get_attr_fortran_wrapper(type, type_keyval, attribute_val, flag, ierr); } _EXTERN_C_ void mpi_type_get_attr(MPI_Fint *type, MPI_Fint *type_keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Type_get_attr_fortran_wrapper(type, type_keyval, attribute_val, flag, ierr); } _EXTERN_C_ void mpi_type_get_attr_(MPI_Fint *type, MPI_Fint *type_keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Type_get_attr_fortran_wrapper(type, type_keyval, attribute_val, flag, ierr); } _EXTERN_C_ void mpi_type_get_attr__(MPI_Fint *type, MPI_Fint *type_keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Type_get_attr_fortran_wrapper(type, type_keyval, attribute_val, flag, ierr); } /* ================= End Wrappers for MPI_Type_get_attr ================= */ /* ================== C Wrappers for MPI_Type_get_contents ================== */ _EXTERN_C_ int PMPI_Type_get_contents(MPI_Datatype mtype, int max_integers, int max_addresses, int max_datatypes, int array_of_integers[], MPI_Aint array_of_addresses[], MPI_Datatype array_of_datatypes[]); _EXTERN_C_ int MPI_Type_get_contents(MPI_Datatype mtype, int max_integers, int max_addresses, int max_datatypes, int array_of_integers[], MPI_Aint array_of_addresses[], MPI_Datatype array_of_datatypes[]) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_get_contents(mtype, max_integers, max_addresses, max_datatypes, array_of_integers, array_of_addresses, array_of_datatypes); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_get_contents =============== */ static void MPI_Type_get_contents_fortran_wrapper(MPI_Fint *mtype, MPI_Fint *max_integers, MPI_Fint *max_addresses, MPI_Fint *max_datatypes, MPI_Fint array_of_integers[], MPI_Aint array_of_addresses[], MPI_Fint array_of_datatypes[], MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_get_contents((MPI_Datatype)(*mtype), *max_integers, *max_addresses, *max_datatypes, (int*)array_of_integers, (MPI_Aint*)array_of_addresses, (MPI_Datatype*)array_of_datatypes); #else /* MPI-2 safe call */ MPI_Datatype* temp_array_of_datatypes; int i; temp_array_of_datatypes = (MPI_Datatype*)malloc(sizeof(MPI_Datatype) * *max_integers); for (i=0; i < *max_integers; i++) temp_array_of_datatypes[i] = MPI_Type_f2c(array_of_datatypes[i]); _wrap_py_return_val = MPI_Type_get_contents(MPI_Type_f2c(*mtype), *max_integers, *max_addresses, *max_datatypes, (int*)array_of_integers, (MPI_Aint*)array_of_addresses, temp_array_of_datatypes); for (i=0; i < *max_integers; i++) array_of_datatypes[i] = MPI_Type_c2f(temp_array_of_datatypes[i]); free(temp_array_of_datatypes); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_GET_CONTENTS(MPI_Fint *mtype, MPI_Fint *max_integers, MPI_Fint *max_addresses, MPI_Fint *max_datatypes, MPI_Fint array_of_integers[], MPI_Aint array_of_addresses[], MPI_Fint array_of_datatypes[], MPI_Fint *ierr) { MPI_Type_get_contents_fortran_wrapper(mtype, max_integers, max_addresses, max_datatypes, array_of_integers, array_of_addresses, array_of_datatypes, ierr); } _EXTERN_C_ void mpi_type_get_contents(MPI_Fint *mtype, MPI_Fint *max_integers, MPI_Fint *max_addresses, MPI_Fint *max_datatypes, MPI_Fint array_of_integers[], MPI_Aint array_of_addresses[], MPI_Fint array_of_datatypes[], MPI_Fint *ierr) { MPI_Type_get_contents_fortran_wrapper(mtype, max_integers, max_addresses, max_datatypes, array_of_integers, array_of_addresses, array_of_datatypes, ierr); } _EXTERN_C_ void mpi_type_get_contents_(MPI_Fint *mtype, MPI_Fint *max_integers, MPI_Fint *max_addresses, MPI_Fint *max_datatypes, MPI_Fint array_of_integers[], MPI_Aint array_of_addresses[], MPI_Fint array_of_datatypes[], MPI_Fint *ierr) { MPI_Type_get_contents_fortran_wrapper(mtype, max_integers, max_addresses, max_datatypes, array_of_integers, array_of_addresses, array_of_datatypes, ierr); } _EXTERN_C_ void mpi_type_get_contents__(MPI_Fint *mtype, MPI_Fint *max_integers, MPI_Fint *max_addresses, MPI_Fint *max_datatypes, MPI_Fint array_of_integers[], MPI_Aint array_of_addresses[], MPI_Fint array_of_datatypes[], MPI_Fint *ierr) { MPI_Type_get_contents_fortran_wrapper(mtype, max_integers, max_addresses, max_datatypes, array_of_integers, array_of_addresses, array_of_datatypes, ierr); } /* ================= End Wrappers for MPI_Type_get_contents ================= */ /* ================== C Wrappers for MPI_Type_get_envelope ================== */ _EXTERN_C_ int PMPI_Type_get_envelope(MPI_Datatype type, int *num_integers, int *num_addresses, int *num_datatypes, int *combiner); _EXTERN_C_ int MPI_Type_get_envelope(MPI_Datatype type, int *num_integers, int *num_addresses, int *num_datatypes, int *combiner) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_get_envelope(type, num_integers, num_addresses, num_datatypes, combiner); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_get_envelope =============== */ static void MPI_Type_get_envelope_fortran_wrapper(MPI_Fint *type, MPI_Fint *num_integers, MPI_Fint *num_addresses, MPI_Fint *num_datatypes, MPI_Fint *combiner, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_get_envelope((MPI_Datatype)(*type), (int*)num_integers, (int*)num_addresses, (int*)num_datatypes, (int*)combiner); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Type_get_envelope(MPI_Type_f2c(*type), (int*)num_integers, (int*)num_addresses, (int*)num_datatypes, (int*)combiner); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_GET_ENVELOPE(MPI_Fint *type, MPI_Fint *num_integers, MPI_Fint *num_addresses, MPI_Fint *num_datatypes, MPI_Fint *combiner, MPI_Fint *ierr) { MPI_Type_get_envelope_fortran_wrapper(type, num_integers, num_addresses, num_datatypes, combiner, ierr); } _EXTERN_C_ void mpi_type_get_envelope(MPI_Fint *type, MPI_Fint *num_integers, MPI_Fint *num_addresses, MPI_Fint *num_datatypes, MPI_Fint *combiner, MPI_Fint *ierr) { MPI_Type_get_envelope_fortran_wrapper(type, num_integers, num_addresses, num_datatypes, combiner, ierr); } _EXTERN_C_ void mpi_type_get_envelope_(MPI_Fint *type, MPI_Fint *num_integers, MPI_Fint *num_addresses, MPI_Fint *num_datatypes, MPI_Fint *combiner, MPI_Fint *ierr) { MPI_Type_get_envelope_fortran_wrapper(type, num_integers, num_addresses, num_datatypes, combiner, ierr); } _EXTERN_C_ void mpi_type_get_envelope__(MPI_Fint *type, MPI_Fint *num_integers, MPI_Fint *num_addresses, MPI_Fint *num_datatypes, MPI_Fint *combiner, MPI_Fint *ierr) { MPI_Type_get_envelope_fortran_wrapper(type, num_integers, num_addresses, num_datatypes, combiner, ierr); } /* ================= End Wrappers for MPI_Type_get_envelope ================= */ /* ================== C Wrappers for MPI_Type_get_extent ================== */ _EXTERN_C_ int PMPI_Type_get_extent(MPI_Datatype type, MPI_Aint *lb, MPI_Aint *extent); _EXTERN_C_ int MPI_Type_get_extent(MPI_Datatype type, MPI_Aint *lb, MPI_Aint *extent) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_get_extent(type, lb, extent); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_get_extent =============== */ static void MPI_Type_get_extent_fortran_wrapper(MPI_Fint *type, MPI_Aint *lb, MPI_Aint *extent, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_get_extent((MPI_Datatype)(*type), (MPI_Aint*)lb, (MPI_Aint*)extent); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Type_get_extent(MPI_Type_f2c(*type), (MPI_Aint*)lb, (MPI_Aint*)extent); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_GET_EXTENT(MPI_Fint *type, MPI_Aint *lb, MPI_Aint *extent, MPI_Fint *ierr) { MPI_Type_get_extent_fortran_wrapper(type, lb, extent, ierr); } _EXTERN_C_ void mpi_type_get_extent(MPI_Fint *type, MPI_Aint *lb, MPI_Aint *extent, MPI_Fint *ierr) { MPI_Type_get_extent_fortran_wrapper(type, lb, extent, ierr); } _EXTERN_C_ void mpi_type_get_extent_(MPI_Fint *type, MPI_Aint *lb, MPI_Aint *extent, MPI_Fint *ierr) { MPI_Type_get_extent_fortran_wrapper(type, lb, extent, ierr); } _EXTERN_C_ void mpi_type_get_extent__(MPI_Fint *type, MPI_Aint *lb, MPI_Aint *extent, MPI_Fint *ierr) { MPI_Type_get_extent_fortran_wrapper(type, lb, extent, ierr); } /* ================= End Wrappers for MPI_Type_get_extent ================= */ /* ================== C Wrappers for MPI_Type_get_extent_x ================== */ _EXTERN_C_ int PMPI_Type_get_extent_x(MPI_Datatype type, MPI_Count *lb, MPI_Count *extent); _EXTERN_C_ int MPI_Type_get_extent_x(MPI_Datatype type, MPI_Count *lb, MPI_Count *extent) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_get_extent_x(type, lb, extent); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_get_extent_x =============== */ static void MPI_Type_get_extent_x_fortran_wrapper(MPI_Fint *type, MPI_Fint *lb, MPI_Fint *extent, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_get_extent_x((MPI_Datatype)(*type), (MPI_Count*)lb, (MPI_Count*)extent); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Type_get_extent_x(MPI_Type_f2c(*type), (MPI_Count*)lb, (MPI_Count*)extent); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_GET_EXTENT_X(MPI_Fint *type, MPI_Fint *lb, MPI_Fint *extent, MPI_Fint *ierr) { MPI_Type_get_extent_x_fortran_wrapper(type, lb, extent, ierr); } _EXTERN_C_ void mpi_type_get_extent_x(MPI_Fint *type, MPI_Fint *lb, MPI_Fint *extent, MPI_Fint *ierr) { MPI_Type_get_extent_x_fortran_wrapper(type, lb, extent, ierr); } _EXTERN_C_ void mpi_type_get_extent_x_(MPI_Fint *type, MPI_Fint *lb, MPI_Fint *extent, MPI_Fint *ierr) { MPI_Type_get_extent_x_fortran_wrapper(type, lb, extent, ierr); } _EXTERN_C_ void mpi_type_get_extent_x__(MPI_Fint *type, MPI_Fint *lb, MPI_Fint *extent, MPI_Fint *ierr) { MPI_Type_get_extent_x_fortran_wrapper(type, lb, extent, ierr); } /* ================= End Wrappers for MPI_Type_get_extent_x ================= */ /* ================== C Wrappers for MPI_Type_get_name ================== */ _EXTERN_C_ int PMPI_Type_get_name(MPI_Datatype type, char *type_name, int *resultlen); _EXTERN_C_ int MPI_Type_get_name(MPI_Datatype type, char *type_name, int *resultlen) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_get_name(type, type_name, resultlen); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_get_name =============== */ static void MPI_Type_get_name_fortran_wrapper(MPI_Fint *type, MPI_Fint *type_name, MPI_Fint *resultlen, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_get_name((MPI_Datatype)(*type), (char*)type_name, (int*)resultlen); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Type_get_name(MPI_Type_f2c(*type), (char*)type_name, (int*)resultlen); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_GET_NAME(MPI_Fint *type, MPI_Fint *type_name, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Type_get_name_fortran_wrapper(type, type_name, resultlen, ierr); } _EXTERN_C_ void mpi_type_get_name(MPI_Fint *type, MPI_Fint *type_name, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Type_get_name_fortran_wrapper(type, type_name, resultlen, ierr); } _EXTERN_C_ void mpi_type_get_name_(MPI_Fint *type, MPI_Fint *type_name, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Type_get_name_fortran_wrapper(type, type_name, resultlen, ierr); } _EXTERN_C_ void mpi_type_get_name__(MPI_Fint *type, MPI_Fint *type_name, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Type_get_name_fortran_wrapper(type, type_name, resultlen, ierr); } /* ================= End Wrappers for MPI_Type_get_name ================= */ /* ================== C Wrappers for MPI_Type_get_true_extent ================== */ _EXTERN_C_ int PMPI_Type_get_true_extent(MPI_Datatype datatype, MPI_Aint *true_lb, MPI_Aint *true_extent); _EXTERN_C_ int MPI_Type_get_true_extent(MPI_Datatype datatype, MPI_Aint *true_lb, MPI_Aint *true_extent) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_get_true_extent(datatype, true_lb, true_extent); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_get_true_extent =============== */ static void MPI_Type_get_true_extent_fortran_wrapper(MPI_Fint *datatype, MPI_Aint *true_lb, MPI_Aint *true_extent, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_get_true_extent((MPI_Datatype)(*datatype), (MPI_Aint*)true_lb, (MPI_Aint*)true_extent); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Type_get_true_extent(MPI_Type_f2c(*datatype), (MPI_Aint*)true_lb, (MPI_Aint*)true_extent); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_GET_TRUE_EXTENT(MPI_Fint *datatype, MPI_Aint *true_lb, MPI_Aint *true_extent, MPI_Fint *ierr) { MPI_Type_get_true_extent_fortran_wrapper(datatype, true_lb, true_extent, ierr); } _EXTERN_C_ void mpi_type_get_true_extent(MPI_Fint *datatype, MPI_Aint *true_lb, MPI_Aint *true_extent, MPI_Fint *ierr) { MPI_Type_get_true_extent_fortran_wrapper(datatype, true_lb, true_extent, ierr); } _EXTERN_C_ void mpi_type_get_true_extent_(MPI_Fint *datatype, MPI_Aint *true_lb, MPI_Aint *true_extent, MPI_Fint *ierr) { MPI_Type_get_true_extent_fortran_wrapper(datatype, true_lb, true_extent, ierr); } _EXTERN_C_ void mpi_type_get_true_extent__(MPI_Fint *datatype, MPI_Aint *true_lb, MPI_Aint *true_extent, MPI_Fint *ierr) { MPI_Type_get_true_extent_fortran_wrapper(datatype, true_lb, true_extent, ierr); } /* ================= End Wrappers for MPI_Type_get_true_extent ================= */ /* ================== C Wrappers for MPI_Type_get_true_extent_x ================== */ _EXTERN_C_ int PMPI_Type_get_true_extent_x(MPI_Datatype datatype, MPI_Count *true_lb, MPI_Count *true_extent); _EXTERN_C_ int MPI_Type_get_true_extent_x(MPI_Datatype datatype, MPI_Count *true_lb, MPI_Count *true_extent) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_get_true_extent_x(datatype, true_lb, true_extent); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_get_true_extent_x =============== */ static void MPI_Type_get_true_extent_x_fortran_wrapper(MPI_Fint *datatype, MPI_Fint *true_lb, MPI_Fint *true_extent, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_get_true_extent_x((MPI_Datatype)(*datatype), (MPI_Count*)true_lb, (MPI_Count*)true_extent); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Type_get_true_extent_x(MPI_Type_f2c(*datatype), (MPI_Count*)true_lb, (MPI_Count*)true_extent); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_GET_TRUE_EXTENT_X(MPI_Fint *datatype, MPI_Fint *true_lb, MPI_Fint *true_extent, MPI_Fint *ierr) { MPI_Type_get_true_extent_x_fortran_wrapper(datatype, true_lb, true_extent, ierr); } _EXTERN_C_ void mpi_type_get_true_extent_x(MPI_Fint *datatype, MPI_Fint *true_lb, MPI_Fint *true_extent, MPI_Fint *ierr) { MPI_Type_get_true_extent_x_fortran_wrapper(datatype, true_lb, true_extent, ierr); } _EXTERN_C_ void mpi_type_get_true_extent_x_(MPI_Fint *datatype, MPI_Fint *true_lb, MPI_Fint *true_extent, MPI_Fint *ierr) { MPI_Type_get_true_extent_x_fortran_wrapper(datatype, true_lb, true_extent, ierr); } _EXTERN_C_ void mpi_type_get_true_extent_x__(MPI_Fint *datatype, MPI_Fint *true_lb, MPI_Fint *true_extent, MPI_Fint *ierr) { MPI_Type_get_true_extent_x_fortran_wrapper(datatype, true_lb, true_extent, ierr); } /* ================= End Wrappers for MPI_Type_get_true_extent_x ================= */ /* ================== C Wrappers for MPI_Type_hindexed ================== */ _EXTERN_C_ int PMPI_Type_hindexed(int count, int array_of_blocklengths[], MPI_Aint array_of_displacements[], MPI_Datatype oldtype, MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_hindexed(int count, int array_of_blocklengths[], MPI_Aint array_of_displacements[], MPI_Datatype oldtype, MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_hindexed(count, array_of_blocklengths, array_of_displacements, oldtype, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_hindexed =============== */ static void MPI_Type_hindexed_fortran_wrapper(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Aint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; WRAP_MPI_CALL_PREFIX #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_hindexed(*count, (int*)array_of_blocklengths, (MPI_Aint*)array_of_displacements, (MPI_Datatype)(*oldtype), (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_hindexed(*count, (int*)array_of_blocklengths, (MPI_Aint*)array_of_displacements, MPI_Type_f2c(*oldtype), &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ WRAP_MPI_CALL_POSTFIX *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_HINDEXED(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Aint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_hindexed_fortran_wrapper(count, array_of_blocklengths, array_of_displacements, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_hindexed(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Aint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_hindexed_fortran_wrapper(count, array_of_blocklengths, array_of_displacements, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_hindexed_(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Aint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_hindexed_fortran_wrapper(count, array_of_blocklengths, array_of_displacements, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_hindexed__(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Aint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_hindexed_fortran_wrapper(count, array_of_blocklengths, array_of_displacements, oldtype, newtype, ierr); } /* ================= End Wrappers for MPI_Type_hindexed ================= */ /* ================== C Wrappers for MPI_Type_hvector ================== */ _EXTERN_C_ int PMPI_Type_hvector(int count, int blocklength, MPI_Aint stride, MPI_Datatype oldtype, MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_hvector(int count, int blocklength, MPI_Aint stride, MPI_Datatype oldtype, MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_hvector(count, blocklength, stride, oldtype, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_hvector =============== */ static void MPI_Type_hvector_fortran_wrapper(MPI_Fint *count, MPI_Fint *blocklength, MPI_Aint *stride, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; WRAP_MPI_CALL_PREFIX #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_hvector(*count, *blocklength, *stride, (MPI_Datatype)(*oldtype), (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_hvector(*count, *blocklength, *stride, MPI_Type_f2c(*oldtype), &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ WRAP_MPI_CALL_POSTFIX *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_HVECTOR(MPI_Fint *count, MPI_Fint *blocklength, MPI_Aint *stride, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_hvector_fortran_wrapper(count, blocklength, stride, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_hvector(MPI_Fint *count, MPI_Fint *blocklength, MPI_Aint *stride, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_hvector_fortran_wrapper(count, blocklength, stride, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_hvector_(MPI_Fint *count, MPI_Fint *blocklength, MPI_Aint *stride, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_hvector_fortran_wrapper(count, blocklength, stride, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_hvector__(MPI_Fint *count, MPI_Fint *blocklength, MPI_Aint *stride, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_hvector_fortran_wrapper(count, blocklength, stride, oldtype, newtype, ierr); } /* ================= End Wrappers for MPI_Type_hvector ================= */ /* ================== C Wrappers for MPI_Type_indexed ================== */ _EXTERN_C_ int PMPI_Type_indexed(int count, const int array_of_blocklengths[], const int array_of_displacements[], MPI_Datatype oldtype, MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_indexed(int count, const int array_of_blocklengths[], const int array_of_displacements[], MPI_Datatype oldtype, MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_indexed(count, array_of_blocklengths, array_of_displacements, oldtype, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_indexed =============== */ static void MPI_Type_indexed_fortran_wrapper(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_indexed(*count, (const int*)array_of_blocklengths, (const int*)array_of_displacements, (MPI_Datatype)(*oldtype), (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_indexed(*count, (const int*)array_of_blocklengths, (const int*)array_of_displacements, MPI_Type_f2c(*oldtype), &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_INDEXED(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_indexed_fortran_wrapper(count, array_of_blocklengths, array_of_displacements, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_indexed(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_indexed_fortran_wrapper(count, array_of_blocklengths, array_of_displacements, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_indexed_(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_indexed_fortran_wrapper(count, array_of_blocklengths, array_of_displacements, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_indexed__(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Fint array_of_displacements[], MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_indexed_fortran_wrapper(count, array_of_blocklengths, array_of_displacements, oldtype, newtype, ierr); } /* ================= End Wrappers for MPI_Type_indexed ================= */ /* ================== C Wrappers for MPI_Type_lb ================== */ _EXTERN_C_ int PMPI_Type_lb(MPI_Datatype type, MPI_Aint *lb); _EXTERN_C_ int MPI_Type_lb(MPI_Datatype type, MPI_Aint *lb) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_lb(type, lb); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_lb =============== */ static void MPI_Type_lb_fortran_wrapper(MPI_Fint *type, MPI_Aint *lb, MPI_Fint *ierr) { int _wrap_py_return_val = 0; WRAP_MPI_CALL_PREFIX #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_lb((MPI_Datatype)(*type), (MPI_Aint*)lb); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Type_lb(MPI_Type_f2c(*type), (MPI_Aint*)lb); #endif /* MPICH test */ WRAP_MPI_CALL_POSTFIX *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_LB(MPI_Fint *type, MPI_Aint *lb, MPI_Fint *ierr) { MPI_Type_lb_fortran_wrapper(type, lb, ierr); } _EXTERN_C_ void mpi_type_lb(MPI_Fint *type, MPI_Aint *lb, MPI_Fint *ierr) { MPI_Type_lb_fortran_wrapper(type, lb, ierr); } _EXTERN_C_ void mpi_type_lb_(MPI_Fint *type, MPI_Aint *lb, MPI_Fint *ierr) { MPI_Type_lb_fortran_wrapper(type, lb, ierr); } _EXTERN_C_ void mpi_type_lb__(MPI_Fint *type, MPI_Aint *lb, MPI_Fint *ierr) { MPI_Type_lb_fortran_wrapper(type, lb, ierr); } /* ================= End Wrappers for MPI_Type_lb ================= */ /* ================== C Wrappers for MPI_Type_match_size ================== */ _EXTERN_C_ int PMPI_Type_match_size(int typeclass, int size, MPI_Datatype *type); _EXTERN_C_ int MPI_Type_match_size(int typeclass, int size, MPI_Datatype *type) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_match_size(typeclass, size, type); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_match_size =============== */ static void MPI_Type_match_size_fortran_wrapper(MPI_Fint *typeclass, MPI_Fint *size, MPI_Fint *type, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_match_size(*typeclass, *size, (MPI_Datatype*)type); #else /* MPI-2 safe call */ MPI_Datatype temp_type; temp_type = MPI_Type_f2c(*type); _wrap_py_return_val = MPI_Type_match_size(*typeclass, *size, &temp_type); *type = MPI_Type_c2f(temp_type); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_MATCH_SIZE(MPI_Fint *typeclass, MPI_Fint *size, MPI_Fint *type, MPI_Fint *ierr) { MPI_Type_match_size_fortran_wrapper(typeclass, size, type, ierr); } _EXTERN_C_ void mpi_type_match_size(MPI_Fint *typeclass, MPI_Fint *size, MPI_Fint *type, MPI_Fint *ierr) { MPI_Type_match_size_fortran_wrapper(typeclass, size, type, ierr); } _EXTERN_C_ void mpi_type_match_size_(MPI_Fint *typeclass, MPI_Fint *size, MPI_Fint *type, MPI_Fint *ierr) { MPI_Type_match_size_fortran_wrapper(typeclass, size, type, ierr); } _EXTERN_C_ void mpi_type_match_size__(MPI_Fint *typeclass, MPI_Fint *size, MPI_Fint *type, MPI_Fint *ierr) { MPI_Type_match_size_fortran_wrapper(typeclass, size, type, ierr); } /* ================= End Wrappers for MPI_Type_match_size ================= */ /* ================== C Wrappers for MPI_Type_set_attr ================== */ _EXTERN_C_ int PMPI_Type_set_attr(MPI_Datatype type, int type_keyval, void *attr_val); _EXTERN_C_ int MPI_Type_set_attr(MPI_Datatype type, int type_keyval, void *attr_val) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_set_attr(type, type_keyval, attr_val); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_set_attr =============== */ static void MPI_Type_set_attr_fortran_wrapper(MPI_Fint *type, MPI_Fint *type_keyval, MPI_Fint *attr_val, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_set_attr((MPI_Datatype)(*type), *type_keyval, (void*)attr_val); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Type_set_attr(MPI_Type_f2c(*type), *type_keyval, (void*)attr_val); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_SET_ATTR(MPI_Fint *type, MPI_Fint *type_keyval, MPI_Fint *attr_val, MPI_Fint *ierr) { MPI_Type_set_attr_fortran_wrapper(type, type_keyval, attr_val, ierr); } _EXTERN_C_ void mpi_type_set_attr(MPI_Fint *type, MPI_Fint *type_keyval, MPI_Fint *attr_val, MPI_Fint *ierr) { MPI_Type_set_attr_fortran_wrapper(type, type_keyval, attr_val, ierr); } _EXTERN_C_ void mpi_type_set_attr_(MPI_Fint *type, MPI_Fint *type_keyval, MPI_Fint *attr_val, MPI_Fint *ierr) { MPI_Type_set_attr_fortran_wrapper(type, type_keyval, attr_val, ierr); } _EXTERN_C_ void mpi_type_set_attr__(MPI_Fint *type, MPI_Fint *type_keyval, MPI_Fint *attr_val, MPI_Fint *ierr) { MPI_Type_set_attr_fortran_wrapper(type, type_keyval, attr_val, ierr); } /* ================= End Wrappers for MPI_Type_set_attr ================= */ /* ================== C Wrappers for MPI_Type_set_name ================== */ _EXTERN_C_ int PMPI_Type_set_name(MPI_Datatype type, const char *type_name); _EXTERN_C_ int MPI_Type_set_name(MPI_Datatype type, const char *type_name) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_set_name(type, type_name); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_set_name =============== */ static void MPI_Type_set_name_fortran_wrapper(MPI_Fint *type, MPI_Fint *type_name, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_set_name((MPI_Datatype)(*type), (const char*)type_name); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Type_set_name(MPI_Type_f2c(*type), (const char*)type_name); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_SET_NAME(MPI_Fint *type, MPI_Fint *type_name, MPI_Fint *ierr) { MPI_Type_set_name_fortran_wrapper(type, type_name, ierr); } _EXTERN_C_ void mpi_type_set_name(MPI_Fint *type, MPI_Fint *type_name, MPI_Fint *ierr) { MPI_Type_set_name_fortran_wrapper(type, type_name, ierr); } _EXTERN_C_ void mpi_type_set_name_(MPI_Fint *type, MPI_Fint *type_name, MPI_Fint *ierr) { MPI_Type_set_name_fortran_wrapper(type, type_name, ierr); } _EXTERN_C_ void mpi_type_set_name__(MPI_Fint *type, MPI_Fint *type_name, MPI_Fint *ierr) { MPI_Type_set_name_fortran_wrapper(type, type_name, ierr); } /* ================= End Wrappers for MPI_Type_set_name ================= */ /* ================== C Wrappers for MPI_Type_size ================== */ _EXTERN_C_ int PMPI_Type_size(MPI_Datatype type, int *size); _EXTERN_C_ int MPI_Type_size(MPI_Datatype type, int *size) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_size(type, size); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_size =============== */ static void MPI_Type_size_fortran_wrapper(MPI_Fint *type, MPI_Fint *size, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_size((MPI_Datatype)(*type), (int*)size); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Type_size(MPI_Type_f2c(*type), (int*)size); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_SIZE(MPI_Fint *type, MPI_Fint *size, MPI_Fint *ierr) { MPI_Type_size_fortran_wrapper(type, size, ierr); } _EXTERN_C_ void mpi_type_size(MPI_Fint *type, MPI_Fint *size, MPI_Fint *ierr) { MPI_Type_size_fortran_wrapper(type, size, ierr); } _EXTERN_C_ void mpi_type_size_(MPI_Fint *type, MPI_Fint *size, MPI_Fint *ierr) { MPI_Type_size_fortran_wrapper(type, size, ierr); } _EXTERN_C_ void mpi_type_size__(MPI_Fint *type, MPI_Fint *size, MPI_Fint *ierr) { MPI_Type_size_fortran_wrapper(type, size, ierr); } /* ================= End Wrappers for MPI_Type_size ================= */ /* ================== C Wrappers for MPI_Type_size_x ================== */ _EXTERN_C_ int PMPI_Type_size_x(MPI_Datatype type, MPI_Count *size); _EXTERN_C_ int MPI_Type_size_x(MPI_Datatype type, MPI_Count *size) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_size_x(type, size); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_size_x =============== */ static void MPI_Type_size_x_fortran_wrapper(MPI_Fint *type, MPI_Fint *size, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_size_x((MPI_Datatype)(*type), (MPI_Count*)size); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Type_size_x(MPI_Type_f2c(*type), (MPI_Count*)size); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_SIZE_X(MPI_Fint *type, MPI_Fint *size, MPI_Fint *ierr) { MPI_Type_size_x_fortran_wrapper(type, size, ierr); } _EXTERN_C_ void mpi_type_size_x(MPI_Fint *type, MPI_Fint *size, MPI_Fint *ierr) { MPI_Type_size_x_fortran_wrapper(type, size, ierr); } _EXTERN_C_ void mpi_type_size_x_(MPI_Fint *type, MPI_Fint *size, MPI_Fint *ierr) { MPI_Type_size_x_fortran_wrapper(type, size, ierr); } _EXTERN_C_ void mpi_type_size_x__(MPI_Fint *type, MPI_Fint *size, MPI_Fint *ierr) { MPI_Type_size_x_fortran_wrapper(type, size, ierr); } /* ================= End Wrappers for MPI_Type_size_x ================= */ /* ================== C Wrappers for MPI_Type_struct ================== */ _EXTERN_C_ int PMPI_Type_struct(int count, int array_of_blocklengths[], MPI_Aint array_of_displacements[], MPI_Datatype array_of_types[], MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_struct(int count, int array_of_blocklengths[], MPI_Aint array_of_displacements[], MPI_Datatype array_of_types[], MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_struct(count, array_of_blocklengths, array_of_displacements, array_of_types, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_struct =============== */ static void MPI_Type_struct_fortran_wrapper(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Aint array_of_displacements[], MPI_Fint array_of_types[], MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; WRAP_MPI_CALL_PREFIX #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_struct(*count, (int*)array_of_blocklengths, (MPI_Aint*)array_of_displacements, (MPI_Datatype*)array_of_types, (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; MPI_Datatype* temp_array_of_types; int i; temp_array_of_types = (MPI_Datatype*)malloc(sizeof(MPI_Datatype) * *count); for (i=0; i < *count; i++) temp_array_of_types[i] = MPI_Type_f2c(array_of_types[i]); temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_struct(*count, (int*)array_of_blocklengths, (MPI_Aint*)array_of_displacements, temp_array_of_types, &temp_newtype); for (i=0; i < *count; i++) array_of_types[i] = MPI_Type_c2f(temp_array_of_types[i]); free(temp_array_of_types); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ WRAP_MPI_CALL_POSTFIX *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_STRUCT(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Aint array_of_displacements[], MPI_Fint array_of_types[], MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_struct_fortran_wrapper(count, array_of_blocklengths, array_of_displacements, array_of_types, newtype, ierr); } _EXTERN_C_ void mpi_type_struct(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Aint array_of_displacements[], MPI_Fint array_of_types[], MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_struct_fortran_wrapper(count, array_of_blocklengths, array_of_displacements, array_of_types, newtype, ierr); } _EXTERN_C_ void mpi_type_struct_(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Aint array_of_displacements[], MPI_Fint array_of_types[], MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_struct_fortran_wrapper(count, array_of_blocklengths, array_of_displacements, array_of_types, newtype, ierr); } _EXTERN_C_ void mpi_type_struct__(MPI_Fint *count, MPI_Fint array_of_blocklengths[], MPI_Aint array_of_displacements[], MPI_Fint array_of_types[], MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_struct_fortran_wrapper(count, array_of_blocklengths, array_of_displacements, array_of_types, newtype, ierr); } /* ================= End Wrappers for MPI_Type_struct ================= */ /* ================== C Wrappers for MPI_Type_ub ================== */ _EXTERN_C_ int PMPI_Type_ub(MPI_Datatype mtype, MPI_Aint *ub); _EXTERN_C_ int MPI_Type_ub(MPI_Datatype mtype, MPI_Aint *ub) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_ub(mtype, ub); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_ub =============== */ static void MPI_Type_ub_fortran_wrapper(MPI_Fint *mtype, MPI_Aint *ub, MPI_Fint *ierr) { int _wrap_py_return_val = 0; WRAP_MPI_CALL_PREFIX #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_ub((MPI_Datatype)(*mtype), (MPI_Aint*)ub); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Type_ub(MPI_Type_f2c(*mtype), (MPI_Aint*)ub); #endif /* MPICH test */ WRAP_MPI_CALL_POSTFIX *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_UB(MPI_Fint *mtype, MPI_Aint *ub, MPI_Fint *ierr) { MPI_Type_ub_fortran_wrapper(mtype, ub, ierr); } _EXTERN_C_ void mpi_type_ub(MPI_Fint *mtype, MPI_Aint *ub, MPI_Fint *ierr) { MPI_Type_ub_fortran_wrapper(mtype, ub, ierr); } _EXTERN_C_ void mpi_type_ub_(MPI_Fint *mtype, MPI_Aint *ub, MPI_Fint *ierr) { MPI_Type_ub_fortran_wrapper(mtype, ub, ierr); } _EXTERN_C_ void mpi_type_ub__(MPI_Fint *mtype, MPI_Aint *ub, MPI_Fint *ierr) { MPI_Type_ub_fortran_wrapper(mtype, ub, ierr); } /* ================= End Wrappers for MPI_Type_ub ================= */ /* ================== C Wrappers for MPI_Type_vector ================== */ _EXTERN_C_ int PMPI_Type_vector(int count, int blocklength, int stride, MPI_Datatype oldtype, MPI_Datatype *newtype); _EXTERN_C_ int MPI_Type_vector(int count, int blocklength, int stride, MPI_Datatype oldtype, MPI_Datatype *newtype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Type_vector(count, blocklength, stride, oldtype, newtype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Type_vector =============== */ static void MPI_Type_vector_fortran_wrapper(MPI_Fint *count, MPI_Fint *blocklength, MPI_Fint *stride, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Type_vector(*count, *blocklength, *stride, (MPI_Datatype)(*oldtype), (MPI_Datatype*)newtype); #else /* MPI-2 safe call */ MPI_Datatype temp_newtype; temp_newtype = MPI_Type_f2c(*newtype); _wrap_py_return_val = MPI_Type_vector(*count, *blocklength, *stride, MPI_Type_f2c(*oldtype), &temp_newtype); *newtype = MPI_Type_c2f(temp_newtype); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_TYPE_VECTOR(MPI_Fint *count, MPI_Fint *blocklength, MPI_Fint *stride, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_vector_fortran_wrapper(count, blocklength, stride, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_vector(MPI_Fint *count, MPI_Fint *blocklength, MPI_Fint *stride, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_vector_fortran_wrapper(count, blocklength, stride, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_vector_(MPI_Fint *count, MPI_Fint *blocklength, MPI_Fint *stride, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_vector_fortran_wrapper(count, blocklength, stride, oldtype, newtype, ierr); } _EXTERN_C_ void mpi_type_vector__(MPI_Fint *count, MPI_Fint *blocklength, MPI_Fint *stride, MPI_Fint *oldtype, MPI_Fint *newtype, MPI_Fint *ierr) { MPI_Type_vector_fortran_wrapper(count, blocklength, stride, oldtype, newtype, ierr); } /* ================= End Wrappers for MPI_Type_vector ================= */ /* ================== C Wrappers for MPI_Unpack ================== */ _EXTERN_C_ int PMPI_Unpack(const void *inbuf, int insize, int *position, void *outbuf, int outcount, MPI_Datatype datatype, MPI_Comm comm); _EXTERN_C_ int MPI_Unpack(const void *inbuf, int insize, int *position, void *outbuf, int outcount, MPI_Datatype datatype, MPI_Comm comm) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Unpack(inbuf, insize, position, outbuf, outcount, datatype, comm); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Unpack =============== */ static void MPI_Unpack_fortran_wrapper(MPI_Fint *inbuf, MPI_Fint *insize, MPI_Fint *position, MPI_Fint *outbuf, MPI_Fint *outcount, MPI_Fint *datatype, MPI_Fint *comm, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Unpack((const void*)inbuf, *insize, (int*)position, (void*)outbuf, *outcount, (MPI_Datatype)(*datatype), (MPI_Comm)(*comm)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Unpack((const void*)inbuf, *insize, (int*)position, (void*)outbuf, *outcount, MPI_Type_f2c(*datatype), MPI_Comm_f2c(*comm)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_UNPACK(MPI_Fint *inbuf, MPI_Fint *insize, MPI_Fint *position, MPI_Fint *outbuf, MPI_Fint *outcount, MPI_Fint *datatype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Unpack_fortran_wrapper(inbuf, insize, position, outbuf, outcount, datatype, comm, ierr); } _EXTERN_C_ void mpi_unpack(MPI_Fint *inbuf, MPI_Fint *insize, MPI_Fint *position, MPI_Fint *outbuf, MPI_Fint *outcount, MPI_Fint *datatype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Unpack_fortran_wrapper(inbuf, insize, position, outbuf, outcount, datatype, comm, ierr); } _EXTERN_C_ void mpi_unpack_(MPI_Fint *inbuf, MPI_Fint *insize, MPI_Fint *position, MPI_Fint *outbuf, MPI_Fint *outcount, MPI_Fint *datatype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Unpack_fortran_wrapper(inbuf, insize, position, outbuf, outcount, datatype, comm, ierr); } _EXTERN_C_ void mpi_unpack__(MPI_Fint *inbuf, MPI_Fint *insize, MPI_Fint *position, MPI_Fint *outbuf, MPI_Fint *outcount, MPI_Fint *datatype, MPI_Fint *comm, MPI_Fint *ierr) { MPI_Unpack_fortran_wrapper(inbuf, insize, position, outbuf, outcount, datatype, comm, ierr); } /* ================= End Wrappers for MPI_Unpack ================= */ /* ================== C Wrappers for MPI_Unpack_external ================== */ _EXTERN_C_ int PMPI_Unpack_external(const char datarep[], const void *inbuf, MPI_Aint insize, MPI_Aint *position, void *outbuf, int outcount, MPI_Datatype datatype); _EXTERN_C_ int MPI_Unpack_external(const char datarep[], const void *inbuf, MPI_Aint insize, MPI_Aint *position, void *outbuf, int outcount, MPI_Datatype datatype) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Unpack_external(datarep, inbuf, insize, position, outbuf, outcount, datatype); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Unpack_external =============== */ static void MPI_Unpack_external_fortran_wrapper(MPI_Fint datarep[], MPI_Fint *inbuf, MPI_Aint *insize, MPI_Aint *position, MPI_Fint *outbuf, MPI_Fint *outcount, MPI_Fint *datatype, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Unpack_external((const char*)datarep, (const void*)inbuf, *insize, (MPI_Aint*)position, (void*)outbuf, *outcount, (MPI_Datatype)(*datatype)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Unpack_external((const char*)datarep, (const void*)inbuf, *insize, (MPI_Aint*)position, (void*)outbuf, *outcount, MPI_Type_f2c(*datatype)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_UNPACK_EXTERNAL(MPI_Fint datarep[], MPI_Fint *inbuf, MPI_Aint *insize, MPI_Aint *position, MPI_Fint *outbuf, MPI_Fint *outcount, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_Unpack_external_fortran_wrapper(datarep, inbuf, insize, position, outbuf, outcount, datatype, ierr); } _EXTERN_C_ void mpi_unpack_external(MPI_Fint datarep[], MPI_Fint *inbuf, MPI_Aint *insize, MPI_Aint *position, MPI_Fint *outbuf, MPI_Fint *outcount, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_Unpack_external_fortran_wrapper(datarep, inbuf, insize, position, outbuf, outcount, datatype, ierr); } _EXTERN_C_ void mpi_unpack_external_(MPI_Fint datarep[], MPI_Fint *inbuf, MPI_Aint *insize, MPI_Aint *position, MPI_Fint *outbuf, MPI_Fint *outcount, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_Unpack_external_fortran_wrapper(datarep, inbuf, insize, position, outbuf, outcount, datatype, ierr); } _EXTERN_C_ void mpi_unpack_external__(MPI_Fint datarep[], MPI_Fint *inbuf, MPI_Aint *insize, MPI_Aint *position, MPI_Fint *outbuf, MPI_Fint *outcount, MPI_Fint *datatype, MPI_Fint *ierr) { MPI_Unpack_external_fortran_wrapper(datarep, inbuf, insize, position, outbuf, outcount, datatype, ierr); } /* ================= End Wrappers for MPI_Unpack_external ================= */ /* ================== C Wrappers for MPI_Unpublish_name ================== */ _EXTERN_C_ int PMPI_Unpublish_name(const char *service_name, MPI_Info info, const char *port_name); _EXTERN_C_ int MPI_Unpublish_name(const char *service_name, MPI_Info info, const char *port_name) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Unpublish_name(service_name, info, port_name); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Unpublish_name =============== */ static void MPI_Unpublish_name_fortran_wrapper(MPI_Fint *service_name, MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Unpublish_name((const char*)service_name, (MPI_Info)(*info), (const char*)port_name); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Unpublish_name((const char*)service_name, MPI_Info_f2c(*info), (const char*)port_name); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_UNPUBLISH_NAME(MPI_Fint *service_name, MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Unpublish_name_fortran_wrapper(service_name, info, port_name, ierr); } _EXTERN_C_ void mpi_unpublish_name(MPI_Fint *service_name, MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Unpublish_name_fortran_wrapper(service_name, info, port_name, ierr); } _EXTERN_C_ void mpi_unpublish_name_(MPI_Fint *service_name, MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Unpublish_name_fortran_wrapper(service_name, info, port_name, ierr); } _EXTERN_C_ void mpi_unpublish_name__(MPI_Fint *service_name, MPI_Fint *info, MPI_Fint *port_name, MPI_Fint *ierr) { MPI_Unpublish_name_fortran_wrapper(service_name, info, port_name, ierr); } /* ================= End Wrappers for MPI_Unpublish_name ================= */ /* ================== C Wrappers for MPI_Wait ================== */ _EXTERN_C_ int PMPI_Wait(MPI_Request *request, MPI_Status *status); _EXTERN_C_ int MPI_Wait(MPI_Request *request, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX if (!wrapper_enabled) { _wrap_py_return_val = PMPI_Wait(request, status); goto end; } if (isolation_mode) { assert(MPI_SUCCESS == MPI_Status_set_cancelled(status, 0)); status->MPI_ERROR = MPI_SUCCESS; _wrap_py_return_val = MPI_SUCCESS; } else { MPI_Request request_copy = *request; _wrap_py_return_val = PMPI_Wait(request, status); if (MPI_SUCCESS == _wrap_py_return_val) { int8_t request_name[SHA256_HEX_CHARS] = {0}; rw_mpi_request_to_unique_string(&request_copy, request_name); RW_AsyncMarker marker; if (-1 != backend_obtain_pending_request(current_rank, request_name, &marker)) { switch (marker.call_id) { case RW_MPI_CALL_ID_IRECV: assert(MPI_SUCCESS == MPI_Get_count(status, marker.type, &(marker.type_count))); backend_capture_data(current_rank, marker.call_number, marker.data_address, marker.type_count, marker.type, marker.source, marker.tag); break; default: assert(0); } } } } WRAP_MPI_CALL_POSTFIX } end: return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Wait =============== */ static void MPI_Wait_fortran_wrapper(MPI_Fint *request, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Wait((MPI_Request*)request, (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Request temp_request; MPI_Status temp_status; temp_request = MPI_Request_f2c(*request); MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_Wait(&temp_request, &temp_status); *request = MPI_Request_c2f(temp_request); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WAIT(MPI_Fint *request, MPI_Fint *status, MPI_Fint *ierr) { MPI_Wait_fortran_wrapper(request, status, ierr); } _EXTERN_C_ void mpi_wait(MPI_Fint *request, MPI_Fint *status, MPI_Fint *ierr) { MPI_Wait_fortran_wrapper(request, status, ierr); } _EXTERN_C_ void mpi_wait_(MPI_Fint *request, MPI_Fint *status, MPI_Fint *ierr) { MPI_Wait_fortran_wrapper(request, status, ierr); } _EXTERN_C_ void mpi_wait__(MPI_Fint *request, MPI_Fint *status, MPI_Fint *ierr) { MPI_Wait_fortran_wrapper(request, status, ierr); } /* ================= End Wrappers for MPI_Wait ================= */ /* ================== C Wrappers for MPI_Waitall ================== */ _EXTERN_C_ int PMPI_Waitall(int count, MPI_Request array_of_requests[], MPI_Status *array_of_statuses); _EXTERN_C_ int MPI_Waitall(int count, MPI_Request array_of_requests[], MPI_Status *array_of_statuses) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Waitall(count, array_of_requests, array_of_statuses); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Waitall =============== */ static void MPI_Waitall_fortran_wrapper(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *array_of_statuses, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Waitall(*count, (MPI_Request*)array_of_requests, (MPI_Status*)array_of_statuses); #else /* MPI-2 safe call */ MPI_Status* temp_array_of_statuses; MPI_Request* temp_array_of_requests; int i; temp_array_of_requests = (MPI_Request*)malloc(sizeof(MPI_Request) * *count); for (i=0; i < *count; i++) temp_array_of_requests[i] = MPI_Request_f2c(array_of_requests[i]); temp_array_of_statuses = (MPI_Status*)malloc(sizeof(MPI_Status) * *count); for (i=0; i < *count; i++) MPI_Status_f2c(&array_of_statuses[i], &temp_array_of_statuses[i]); _wrap_py_return_val = MPI_Waitall(*count, temp_array_of_requests, temp_array_of_statuses); for (i=0; i < *count; i++) array_of_requests[i] = MPI_Request_c2f(temp_array_of_requests[i]); free(temp_array_of_requests); for (i=0; i < *count; i++) MPI_Status_c2f(&temp_array_of_statuses[i], &array_of_statuses[i]); free(temp_array_of_statuses); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WAITALL(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *array_of_statuses, MPI_Fint *ierr) { MPI_Waitall_fortran_wrapper(count, array_of_requests, array_of_statuses, ierr); } _EXTERN_C_ void mpi_waitall(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *array_of_statuses, MPI_Fint *ierr) { MPI_Waitall_fortran_wrapper(count, array_of_requests, array_of_statuses, ierr); } _EXTERN_C_ void mpi_waitall_(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *array_of_statuses, MPI_Fint *ierr) { MPI_Waitall_fortran_wrapper(count, array_of_requests, array_of_statuses, ierr); } _EXTERN_C_ void mpi_waitall__(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *array_of_statuses, MPI_Fint *ierr) { MPI_Waitall_fortran_wrapper(count, array_of_requests, array_of_statuses, ierr); } /* ================= End Wrappers for MPI_Waitall ================= */ /* ================== C Wrappers for MPI_Waitany ================== */ _EXTERN_C_ int PMPI_Waitany(int count, MPI_Request array_of_requests[], int *index, MPI_Status *status); _EXTERN_C_ int MPI_Waitany(int count, MPI_Request array_of_requests[], int *index, MPI_Status *status) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Waitany(count, array_of_requests, index, status); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Waitany =============== */ static void MPI_Waitany_fortran_wrapper(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *index, MPI_Fint *status, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Waitany(*count, (MPI_Request*)array_of_requests, (int*)index, (MPI_Status*)status); #else /* MPI-2 safe call */ MPI_Request* temp_array_of_requests; MPI_Status temp_status; int i; temp_array_of_requests = (MPI_Request*)malloc(sizeof(MPI_Request) * *count); for (i=0; i < *count; i++) temp_array_of_requests[i] = MPI_Request_f2c(array_of_requests[i]); MPI_Status_f2c(status, &temp_status); _wrap_py_return_val = MPI_Waitany(*count, temp_array_of_requests, (int*)index, &temp_status); for (i=0; i < *count; i++) array_of_requests[i] = MPI_Request_c2f(temp_array_of_requests[i]); free(temp_array_of_requests); MPI_Status_c2f(&temp_status, status); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WAITANY(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *index, MPI_Fint *status, MPI_Fint *ierr) { MPI_Waitany_fortran_wrapper(count, array_of_requests, index, status, ierr); } _EXTERN_C_ void mpi_waitany(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *index, MPI_Fint *status, MPI_Fint *ierr) { MPI_Waitany_fortran_wrapper(count, array_of_requests, index, status, ierr); } _EXTERN_C_ void mpi_waitany_(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *index, MPI_Fint *status, MPI_Fint *ierr) { MPI_Waitany_fortran_wrapper(count, array_of_requests, index, status, ierr); } _EXTERN_C_ void mpi_waitany__(MPI_Fint *count, MPI_Fint array_of_requests[], MPI_Fint *index, MPI_Fint *status, MPI_Fint *ierr) { MPI_Waitany_fortran_wrapper(count, array_of_requests, index, status, ierr); } /* ================= End Wrappers for MPI_Waitany ================= */ /* ================== C Wrappers for MPI_Waitsome ================== */ _EXTERN_C_ int PMPI_Waitsome(int incount, MPI_Request array_of_requests[], int *outcount, int array_of_indices[], MPI_Status array_of_statuses[]); _EXTERN_C_ int MPI_Waitsome(int incount, MPI_Request array_of_requests[], int *outcount, int array_of_indices[], MPI_Status array_of_statuses[]) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Waitsome(incount, array_of_requests, outcount, array_of_indices, array_of_statuses); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Waitsome =============== */ static void MPI_Waitsome_fortran_wrapper(MPI_Fint *incount, MPI_Fint array_of_requests[], MPI_Fint *outcount, MPI_Fint array_of_indices[], MPI_Fint array_of_statuses[], MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Waitsome(*incount, (MPI_Request*)array_of_requests, (int*)outcount, (int*)array_of_indices, (MPI_Status*)array_of_statuses); #else /* MPI-2 safe call */ MPI_Status* temp_array_of_statuses; MPI_Request* temp_array_of_requests; int i; temp_array_of_requests = (MPI_Request*)malloc(sizeof(MPI_Request) * *incount); for (i=0; i < *incount; i++) temp_array_of_requests[i] = MPI_Request_f2c(array_of_requests[i]); temp_array_of_statuses = (MPI_Status*)malloc(sizeof(MPI_Status) * *incount); for (i=0; i < *incount; i++) MPI_Status_f2c(&array_of_statuses[i], &temp_array_of_statuses[i]); _wrap_py_return_val = MPI_Waitsome(*incount, temp_array_of_requests, (int*)outcount, (int*)array_of_indices, temp_array_of_statuses); for (i=0; i < *incount; i++) array_of_requests[i] = MPI_Request_c2f(temp_array_of_requests[i]); free(temp_array_of_requests); for (i=0; i < *incount; i++) MPI_Status_c2f(&temp_array_of_statuses[i], &array_of_statuses[i]); free(temp_array_of_statuses); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WAITSOME(MPI_Fint *incount, MPI_Fint array_of_requests[], MPI_Fint *outcount, MPI_Fint array_of_indices[], MPI_Fint array_of_statuses[], MPI_Fint *ierr) { MPI_Waitsome_fortran_wrapper(incount, array_of_requests, outcount, array_of_indices, array_of_statuses, ierr); } _EXTERN_C_ void mpi_waitsome(MPI_Fint *incount, MPI_Fint array_of_requests[], MPI_Fint *outcount, MPI_Fint array_of_indices[], MPI_Fint array_of_statuses[], MPI_Fint *ierr) { MPI_Waitsome_fortran_wrapper(incount, array_of_requests, outcount, array_of_indices, array_of_statuses, ierr); } _EXTERN_C_ void mpi_waitsome_(MPI_Fint *incount, MPI_Fint array_of_requests[], MPI_Fint *outcount, MPI_Fint array_of_indices[], MPI_Fint array_of_statuses[], MPI_Fint *ierr) { MPI_Waitsome_fortran_wrapper(incount, array_of_requests, outcount, array_of_indices, array_of_statuses, ierr); } _EXTERN_C_ void mpi_waitsome__(MPI_Fint *incount, MPI_Fint array_of_requests[], MPI_Fint *outcount, MPI_Fint array_of_indices[], MPI_Fint array_of_statuses[], MPI_Fint *ierr) { MPI_Waitsome_fortran_wrapper(incount, array_of_requests, outcount, array_of_indices, array_of_statuses, ierr); } /* ================= End Wrappers for MPI_Waitsome ================= */ /* ================== C Wrappers for MPI_Win_allocate ================== */ _EXTERN_C_ int PMPI_Win_allocate(MPI_Aint size, int disp_unit, MPI_Info info, MPI_Comm comm, void *baseptr, MPI_Win *win); _EXTERN_C_ int MPI_Win_allocate(MPI_Aint size, int disp_unit, MPI_Info info, MPI_Comm comm, void *baseptr, MPI_Win *win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_allocate(size, disp_unit, info, comm, baseptr, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_allocate =============== */ static void MPI_Win_allocate_fortran_wrapper(MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *info, MPI_Fint *comm, MPI_Fint *baseptr, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_allocate(*size, *disp_unit, (MPI_Info)(*info), (MPI_Comm)(*comm), (void*)baseptr, (MPI_Win*)win); #else /* MPI-2 safe call */ MPI_Win temp_win; temp_win = MPI_Win_f2c(*win); _wrap_py_return_val = MPI_Win_allocate(*size, *disp_unit, MPI_Info_f2c(*info), MPI_Comm_f2c(*comm), (void*)baseptr, &temp_win); *win = MPI_Win_c2f(temp_win); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_ALLOCATE(MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *info, MPI_Fint *comm, MPI_Fint *baseptr, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_allocate_fortran_wrapper(size, disp_unit, info, comm, baseptr, win, ierr); } _EXTERN_C_ void mpi_win_allocate(MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *info, MPI_Fint *comm, MPI_Fint *baseptr, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_allocate_fortran_wrapper(size, disp_unit, info, comm, baseptr, win, ierr); } _EXTERN_C_ void mpi_win_allocate_(MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *info, MPI_Fint *comm, MPI_Fint *baseptr, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_allocate_fortran_wrapper(size, disp_unit, info, comm, baseptr, win, ierr); } _EXTERN_C_ void mpi_win_allocate__(MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *info, MPI_Fint *comm, MPI_Fint *baseptr, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_allocate_fortran_wrapper(size, disp_unit, info, comm, baseptr, win, ierr); } /* ================= End Wrappers for MPI_Win_allocate ================= */ /* ================== C Wrappers for MPI_Win_allocate_shared ================== */ _EXTERN_C_ int PMPI_Win_allocate_shared(MPI_Aint size, int disp_unit, MPI_Info info, MPI_Comm comm, void *baseptr, MPI_Win *win); _EXTERN_C_ int MPI_Win_allocate_shared(MPI_Aint size, int disp_unit, MPI_Info info, MPI_Comm comm, void *baseptr, MPI_Win *win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_allocate_shared(size, disp_unit, info, comm, baseptr, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_allocate_shared =============== */ static void MPI_Win_allocate_shared_fortran_wrapper(MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *info, MPI_Fint *comm, MPI_Fint *baseptr, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_allocate_shared(*size, *disp_unit, (MPI_Info)(*info), (MPI_Comm)(*comm), (void*)baseptr, (MPI_Win*)win); #else /* MPI-2 safe call */ MPI_Win temp_win; temp_win = MPI_Win_f2c(*win); _wrap_py_return_val = MPI_Win_allocate_shared(*size, *disp_unit, MPI_Info_f2c(*info), MPI_Comm_f2c(*comm), (void*)baseptr, &temp_win); *win = MPI_Win_c2f(temp_win); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_ALLOCATE_SHARED(MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *info, MPI_Fint *comm, MPI_Fint *baseptr, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_allocate_shared_fortran_wrapper(size, disp_unit, info, comm, baseptr, win, ierr); } _EXTERN_C_ void mpi_win_allocate_shared(MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *info, MPI_Fint *comm, MPI_Fint *baseptr, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_allocate_shared_fortran_wrapper(size, disp_unit, info, comm, baseptr, win, ierr); } _EXTERN_C_ void mpi_win_allocate_shared_(MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *info, MPI_Fint *comm, MPI_Fint *baseptr, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_allocate_shared_fortran_wrapper(size, disp_unit, info, comm, baseptr, win, ierr); } _EXTERN_C_ void mpi_win_allocate_shared__(MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *info, MPI_Fint *comm, MPI_Fint *baseptr, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_allocate_shared_fortran_wrapper(size, disp_unit, info, comm, baseptr, win, ierr); } /* ================= End Wrappers for MPI_Win_allocate_shared ================= */ /* ================== C Wrappers for MPI_Win_attach ================== */ _EXTERN_C_ int PMPI_Win_attach(MPI_Win win, void *base, MPI_Aint size); _EXTERN_C_ int MPI_Win_attach(MPI_Win win, void *base, MPI_Aint size) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_attach(win, base, size); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_attach =============== */ static void MPI_Win_attach_fortran_wrapper(MPI_Fint *win, MPI_Fint *base, MPI_Aint *size, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_attach((MPI_Win)(*win), (void*)base, *size); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_attach(MPI_Win_f2c(*win), (void*)base, *size); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_ATTACH(MPI_Fint *win, MPI_Fint *base, MPI_Aint *size, MPI_Fint *ierr) { MPI_Win_attach_fortran_wrapper(win, base, size, ierr); } _EXTERN_C_ void mpi_win_attach(MPI_Fint *win, MPI_Fint *base, MPI_Aint *size, MPI_Fint *ierr) { MPI_Win_attach_fortran_wrapper(win, base, size, ierr); } _EXTERN_C_ void mpi_win_attach_(MPI_Fint *win, MPI_Fint *base, MPI_Aint *size, MPI_Fint *ierr) { MPI_Win_attach_fortran_wrapper(win, base, size, ierr); } _EXTERN_C_ void mpi_win_attach__(MPI_Fint *win, MPI_Fint *base, MPI_Aint *size, MPI_Fint *ierr) { MPI_Win_attach_fortran_wrapper(win, base, size, ierr); } /* ================= End Wrappers for MPI_Win_attach ================= */ /* ================== C Wrappers for MPI_Win_call_errhandler ================== */ _EXTERN_C_ int PMPI_Win_call_errhandler(MPI_Win win, int errorcode); _EXTERN_C_ int MPI_Win_call_errhandler(MPI_Win win, int errorcode) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_call_errhandler(win, errorcode); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_call_errhandler =============== */ static void MPI_Win_call_errhandler_fortran_wrapper(MPI_Fint *win, MPI_Fint *errorcode, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_call_errhandler((MPI_Win)(*win), *errorcode); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_call_errhandler(MPI_Win_f2c(*win), *errorcode); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_CALL_ERRHANDLER(MPI_Fint *win, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_Win_call_errhandler_fortran_wrapper(win, errorcode, ierr); } _EXTERN_C_ void mpi_win_call_errhandler(MPI_Fint *win, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_Win_call_errhandler_fortran_wrapper(win, errorcode, ierr); } _EXTERN_C_ void mpi_win_call_errhandler_(MPI_Fint *win, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_Win_call_errhandler_fortran_wrapper(win, errorcode, ierr); } _EXTERN_C_ void mpi_win_call_errhandler__(MPI_Fint *win, MPI_Fint *errorcode, MPI_Fint *ierr) { MPI_Win_call_errhandler_fortran_wrapper(win, errorcode, ierr); } /* ================= End Wrappers for MPI_Win_call_errhandler ================= */ /* ================== C Wrappers for MPI_Win_complete ================== */ _EXTERN_C_ int PMPI_Win_complete(MPI_Win win); _EXTERN_C_ int MPI_Win_complete(MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_complete(win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_complete =============== */ static void MPI_Win_complete_fortran_wrapper(MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_complete((MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_complete(MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_COMPLETE(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_complete_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_complete(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_complete_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_complete_(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_complete_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_complete__(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_complete_fortran_wrapper(win, ierr); } /* ================= End Wrappers for MPI_Win_complete ================= */ /* ================== C Wrappers for MPI_Win_create ================== */ _EXTERN_C_ int PMPI_Win_create(void *base, MPI_Aint size, int disp_unit, MPI_Info info, MPI_Comm comm, MPI_Win *win); _EXTERN_C_ int MPI_Win_create(void *base, MPI_Aint size, int disp_unit, MPI_Info info, MPI_Comm comm, MPI_Win *win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_create(base, size, disp_unit, info, comm, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_create =============== */ static void MPI_Win_create_fortran_wrapper(MPI_Fint *base, MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *info, MPI_Fint *comm, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_create((void*)base, *size, *disp_unit, (MPI_Info)(*info), (MPI_Comm)(*comm), (MPI_Win*)win); #else /* MPI-2 safe call */ MPI_Win temp_win; temp_win = MPI_Win_f2c(*win); _wrap_py_return_val = MPI_Win_create((void*)base, *size, *disp_unit, MPI_Info_f2c(*info), MPI_Comm_f2c(*comm), &temp_win); *win = MPI_Win_c2f(temp_win); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_CREATE(MPI_Fint *base, MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *info, MPI_Fint *comm, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_create_fortran_wrapper(base, size, disp_unit, info, comm, win, ierr); } _EXTERN_C_ void mpi_win_create(MPI_Fint *base, MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *info, MPI_Fint *comm, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_create_fortran_wrapper(base, size, disp_unit, info, comm, win, ierr); } _EXTERN_C_ void mpi_win_create_(MPI_Fint *base, MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *info, MPI_Fint *comm, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_create_fortran_wrapper(base, size, disp_unit, info, comm, win, ierr); } _EXTERN_C_ void mpi_win_create__(MPI_Fint *base, MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *info, MPI_Fint *comm, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_create_fortran_wrapper(base, size, disp_unit, info, comm, win, ierr); } /* ================= End Wrappers for MPI_Win_create ================= */ /* ================== C Wrappers for MPI_Win_create_dynamic ================== */ _EXTERN_C_ int PMPI_Win_create_dynamic(MPI_Info info, MPI_Comm comm, MPI_Win *win); _EXTERN_C_ int MPI_Win_create_dynamic(MPI_Info info, MPI_Comm comm, MPI_Win *win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_create_dynamic(info, comm, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_create_dynamic =============== */ static void MPI_Win_create_dynamic_fortran_wrapper(MPI_Fint *info, MPI_Fint *comm, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_create_dynamic((MPI_Info)(*info), (MPI_Comm)(*comm), (MPI_Win*)win); #else /* MPI-2 safe call */ MPI_Win temp_win; temp_win = MPI_Win_f2c(*win); _wrap_py_return_val = MPI_Win_create_dynamic(MPI_Info_f2c(*info), MPI_Comm_f2c(*comm), &temp_win); *win = MPI_Win_c2f(temp_win); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_CREATE_DYNAMIC(MPI_Fint *info, MPI_Fint *comm, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_create_dynamic_fortran_wrapper(info, comm, win, ierr); } _EXTERN_C_ void mpi_win_create_dynamic(MPI_Fint *info, MPI_Fint *comm, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_create_dynamic_fortran_wrapper(info, comm, win, ierr); } _EXTERN_C_ void mpi_win_create_dynamic_(MPI_Fint *info, MPI_Fint *comm, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_create_dynamic_fortran_wrapper(info, comm, win, ierr); } _EXTERN_C_ void mpi_win_create_dynamic__(MPI_Fint *info, MPI_Fint *comm, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_create_dynamic_fortran_wrapper(info, comm, win, ierr); } /* ================= End Wrappers for MPI_Win_create_dynamic ================= */ /* ================== C Wrappers for MPI_Win_create_errhandler ================== */ _EXTERN_C_ int PMPI_Win_create_errhandler(MPI_Win_errhandler_function *function, MPI_Errhandler *errhandler); _EXTERN_C_ int MPI_Win_create_errhandler(MPI_Win_errhandler_function *function, MPI_Errhandler *errhandler) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_create_errhandler(function, errhandler); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_create_errhandler =============== */ static void MPI_Win_create_errhandler_fortran_wrapper(MPI_Win_errhandler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_create_errhandler((MPI_Win_errhandler_function*)function, (MPI_Errhandler*)errhandler); #else /* MPI-2 safe call */ MPI_Errhandler temp_errhandler; temp_errhandler = MPI_Errhandler_f2c(*errhandler); _wrap_py_return_val = MPI_Win_create_errhandler((MPI_Win_errhandler_function*)function, &temp_errhandler); *errhandler = MPI_Errhandler_c2f(temp_errhandler); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_CREATE_ERRHANDLER(MPI_Win_errhandler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Win_create_errhandler_fortran_wrapper(function, errhandler, ierr); } _EXTERN_C_ void mpi_win_create_errhandler(MPI_Win_errhandler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Win_create_errhandler_fortran_wrapper(function, errhandler, ierr); } _EXTERN_C_ void mpi_win_create_errhandler_(MPI_Win_errhandler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Win_create_errhandler_fortran_wrapper(function, errhandler, ierr); } _EXTERN_C_ void mpi_win_create_errhandler__(MPI_Win_errhandler_function *function, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Win_create_errhandler_fortran_wrapper(function, errhandler, ierr); } /* ================= End Wrappers for MPI_Win_create_errhandler ================= */ /* ================== C Wrappers for MPI_Win_create_keyval ================== */ _EXTERN_C_ int PMPI_Win_create_keyval(MPI_Win_copy_attr_function *win_copy_attr_fn, MPI_Win_delete_attr_function *win_delete_attr_fn, int *win_keyval, void *extra_state); _EXTERN_C_ int MPI_Win_create_keyval(MPI_Win_copy_attr_function *win_copy_attr_fn, MPI_Win_delete_attr_function *win_delete_attr_fn, int *win_keyval, void *extra_state) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_create_keyval(win_copy_attr_fn, win_delete_attr_fn, win_keyval, extra_state); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_create_keyval =============== */ static void MPI_Win_create_keyval_fortran_wrapper(MPI_Win_copy_attr_function *win_copy_attr_fn, MPI_Win_delete_attr_function *win_delete_attr_fn, MPI_Fint *win_keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Win_create_keyval((MPI_Win_copy_attr_function*)win_copy_attr_fn, (MPI_Win_delete_attr_function*)win_delete_attr_fn, (int*)win_keyval, (void*)extra_state); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_CREATE_KEYVAL(MPI_Win_copy_attr_function *win_copy_attr_fn, MPI_Win_delete_attr_function *win_delete_attr_fn, MPI_Fint *win_keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Win_create_keyval_fortran_wrapper(win_copy_attr_fn, win_delete_attr_fn, win_keyval, extra_state, ierr); } _EXTERN_C_ void mpi_win_create_keyval(MPI_Win_copy_attr_function *win_copy_attr_fn, MPI_Win_delete_attr_function *win_delete_attr_fn, MPI_Fint *win_keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Win_create_keyval_fortran_wrapper(win_copy_attr_fn, win_delete_attr_fn, win_keyval, extra_state, ierr); } _EXTERN_C_ void mpi_win_create_keyval_(MPI_Win_copy_attr_function *win_copy_attr_fn, MPI_Win_delete_attr_function *win_delete_attr_fn, MPI_Fint *win_keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Win_create_keyval_fortran_wrapper(win_copy_attr_fn, win_delete_attr_fn, win_keyval, extra_state, ierr); } _EXTERN_C_ void mpi_win_create_keyval__(MPI_Win_copy_attr_function *win_copy_attr_fn, MPI_Win_delete_attr_function *win_delete_attr_fn, MPI_Fint *win_keyval, MPI_Fint *extra_state, MPI_Fint *ierr) { MPI_Win_create_keyval_fortran_wrapper(win_copy_attr_fn, win_delete_attr_fn, win_keyval, extra_state, ierr); } /* ================= End Wrappers for MPI_Win_create_keyval ================= */ /* ================== C Wrappers for MPI_Win_delete_attr ================== */ _EXTERN_C_ int PMPI_Win_delete_attr(MPI_Win win, int win_keyval); _EXTERN_C_ int MPI_Win_delete_attr(MPI_Win win, int win_keyval) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_delete_attr(win, win_keyval); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_delete_attr =============== */ static void MPI_Win_delete_attr_fortran_wrapper(MPI_Fint *win, MPI_Fint *win_keyval, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_delete_attr((MPI_Win)(*win), *win_keyval); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_delete_attr(MPI_Win_f2c(*win), *win_keyval); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_DELETE_ATTR(MPI_Fint *win, MPI_Fint *win_keyval, MPI_Fint *ierr) { MPI_Win_delete_attr_fortran_wrapper(win, win_keyval, ierr); } _EXTERN_C_ void mpi_win_delete_attr(MPI_Fint *win, MPI_Fint *win_keyval, MPI_Fint *ierr) { MPI_Win_delete_attr_fortran_wrapper(win, win_keyval, ierr); } _EXTERN_C_ void mpi_win_delete_attr_(MPI_Fint *win, MPI_Fint *win_keyval, MPI_Fint *ierr) { MPI_Win_delete_attr_fortran_wrapper(win, win_keyval, ierr); } _EXTERN_C_ void mpi_win_delete_attr__(MPI_Fint *win, MPI_Fint *win_keyval, MPI_Fint *ierr) { MPI_Win_delete_attr_fortran_wrapper(win, win_keyval, ierr); } /* ================= End Wrappers for MPI_Win_delete_attr ================= */ /* ================== C Wrappers for MPI_Win_detach ================== */ _EXTERN_C_ int PMPI_Win_detach(MPI_Win win, const void *base); _EXTERN_C_ int MPI_Win_detach(MPI_Win win, const void *base) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_detach(win, base); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_detach =============== */ static void MPI_Win_detach_fortran_wrapper(MPI_Fint *win, MPI_Fint *base, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_detach((MPI_Win)(*win), (const void*)base); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_detach(MPI_Win_f2c(*win), (const void*)base); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_DETACH(MPI_Fint *win, MPI_Fint *base, MPI_Fint *ierr) { MPI_Win_detach_fortran_wrapper(win, base, ierr); } _EXTERN_C_ void mpi_win_detach(MPI_Fint *win, MPI_Fint *base, MPI_Fint *ierr) { MPI_Win_detach_fortran_wrapper(win, base, ierr); } _EXTERN_C_ void mpi_win_detach_(MPI_Fint *win, MPI_Fint *base, MPI_Fint *ierr) { MPI_Win_detach_fortran_wrapper(win, base, ierr); } _EXTERN_C_ void mpi_win_detach__(MPI_Fint *win, MPI_Fint *base, MPI_Fint *ierr) { MPI_Win_detach_fortran_wrapper(win, base, ierr); } /* ================= End Wrappers for MPI_Win_detach ================= */ /* ================== C Wrappers for MPI_Win_fence ================== */ _EXTERN_C_ int PMPI_Win_fence(int assert, MPI_Win win); _EXTERN_C_ int MPI_Win_fence(int assert, MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_fence(assert, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_fence =============== */ static void MPI_Win_fence_fortran_wrapper(MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_fence(*assert, (MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_fence(*assert, MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_FENCE(MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_fence_fortran_wrapper(assert, win, ierr); } _EXTERN_C_ void mpi_win_fence(MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_fence_fortran_wrapper(assert, win, ierr); } _EXTERN_C_ void mpi_win_fence_(MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_fence_fortran_wrapper(assert, win, ierr); } _EXTERN_C_ void mpi_win_fence__(MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_fence_fortran_wrapper(assert, win, ierr); } /* ================= End Wrappers for MPI_Win_fence ================= */ /* ================== C Wrappers for MPI_Win_flush ================== */ _EXTERN_C_ int PMPI_Win_flush(int rank, MPI_Win win); _EXTERN_C_ int MPI_Win_flush(int rank, MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_flush(rank, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_flush =============== */ static void MPI_Win_flush_fortran_wrapper(MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_flush(*rank, (MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_flush(*rank, MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_FLUSH(MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_flush_fortran_wrapper(rank, win, ierr); } _EXTERN_C_ void mpi_win_flush(MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_flush_fortran_wrapper(rank, win, ierr); } _EXTERN_C_ void mpi_win_flush_(MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_flush_fortran_wrapper(rank, win, ierr); } _EXTERN_C_ void mpi_win_flush__(MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_flush_fortran_wrapper(rank, win, ierr); } /* ================= End Wrappers for MPI_Win_flush ================= */ /* ================== C Wrappers for MPI_Win_flush_all ================== */ _EXTERN_C_ int PMPI_Win_flush_all(MPI_Win win); _EXTERN_C_ int MPI_Win_flush_all(MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_flush_all(win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_flush_all =============== */ static void MPI_Win_flush_all_fortran_wrapper(MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_flush_all((MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_flush_all(MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_FLUSH_ALL(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_flush_all_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_flush_all(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_flush_all_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_flush_all_(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_flush_all_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_flush_all__(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_flush_all_fortran_wrapper(win, ierr); } /* ================= End Wrappers for MPI_Win_flush_all ================= */ /* ================== C Wrappers for MPI_Win_flush_local ================== */ _EXTERN_C_ int PMPI_Win_flush_local(int rank, MPI_Win win); _EXTERN_C_ int MPI_Win_flush_local(int rank, MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_flush_local(rank, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_flush_local =============== */ static void MPI_Win_flush_local_fortran_wrapper(MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_flush_local(*rank, (MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_flush_local(*rank, MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_FLUSH_LOCAL(MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_flush_local_fortran_wrapper(rank, win, ierr); } _EXTERN_C_ void mpi_win_flush_local(MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_flush_local_fortran_wrapper(rank, win, ierr); } _EXTERN_C_ void mpi_win_flush_local_(MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_flush_local_fortran_wrapper(rank, win, ierr); } _EXTERN_C_ void mpi_win_flush_local__(MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_flush_local_fortran_wrapper(rank, win, ierr); } /* ================= End Wrappers for MPI_Win_flush_local ================= */ /* ================== C Wrappers for MPI_Win_flush_local_all ================== */ _EXTERN_C_ int PMPI_Win_flush_local_all(MPI_Win win); _EXTERN_C_ int MPI_Win_flush_local_all(MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_flush_local_all(win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_flush_local_all =============== */ static void MPI_Win_flush_local_all_fortran_wrapper(MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_flush_local_all((MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_flush_local_all(MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_FLUSH_LOCAL_ALL(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_flush_local_all_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_flush_local_all(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_flush_local_all_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_flush_local_all_(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_flush_local_all_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_flush_local_all__(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_flush_local_all_fortran_wrapper(win, ierr); } /* ================= End Wrappers for MPI_Win_flush_local_all ================= */ /* ================== C Wrappers for MPI_Win_free ================== */ _EXTERN_C_ int PMPI_Win_free(MPI_Win *win); _EXTERN_C_ int MPI_Win_free(MPI_Win *win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_free(win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_free =============== */ static void MPI_Win_free_fortran_wrapper(MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_free((MPI_Win*)win); #else /* MPI-2 safe call */ MPI_Win temp_win; temp_win = MPI_Win_f2c(*win); _wrap_py_return_val = MPI_Win_free(&temp_win); *win = MPI_Win_c2f(temp_win); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_FREE(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_free_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_free(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_free_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_free_(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_free_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_free__(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_free_fortran_wrapper(win, ierr); } /* ================= End Wrappers for MPI_Win_free ================= */ /* ================== C Wrappers for MPI_Win_free_keyval ================== */ _EXTERN_C_ int PMPI_Win_free_keyval(int *win_keyval); _EXTERN_C_ int MPI_Win_free_keyval(int *win_keyval) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_free_keyval(win_keyval); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_free_keyval =============== */ static void MPI_Win_free_keyval_fortran_wrapper(MPI_Fint *win_keyval, MPI_Fint *ierr) { int _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Win_free_keyval((int*)win_keyval); *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_FREE_KEYVAL(MPI_Fint *win_keyval, MPI_Fint *ierr) { MPI_Win_free_keyval_fortran_wrapper(win_keyval, ierr); } _EXTERN_C_ void mpi_win_free_keyval(MPI_Fint *win_keyval, MPI_Fint *ierr) { MPI_Win_free_keyval_fortran_wrapper(win_keyval, ierr); } _EXTERN_C_ void mpi_win_free_keyval_(MPI_Fint *win_keyval, MPI_Fint *ierr) { MPI_Win_free_keyval_fortran_wrapper(win_keyval, ierr); } _EXTERN_C_ void mpi_win_free_keyval__(MPI_Fint *win_keyval, MPI_Fint *ierr) { MPI_Win_free_keyval_fortran_wrapper(win_keyval, ierr); } /* ================= End Wrappers for MPI_Win_free_keyval ================= */ /* ================== C Wrappers for MPI_Win_get_attr ================== */ _EXTERN_C_ int PMPI_Win_get_attr(MPI_Win win, int win_keyval, void *attribute_val, int *flag); _EXTERN_C_ int MPI_Win_get_attr(MPI_Win win, int win_keyval, void *attribute_val, int *flag) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_get_attr(win, win_keyval, attribute_val, flag); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_get_attr =============== */ static void MPI_Win_get_attr_fortran_wrapper(MPI_Fint *win, MPI_Fint *win_keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_get_attr((MPI_Win)(*win), *win_keyval, (void*)attribute_val, (int*)flag); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_get_attr(MPI_Win_f2c(*win), *win_keyval, (void*)attribute_val, (int*)flag); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_GET_ATTR(MPI_Fint *win, MPI_Fint *win_keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Win_get_attr_fortran_wrapper(win, win_keyval, attribute_val, flag, ierr); } _EXTERN_C_ void mpi_win_get_attr(MPI_Fint *win, MPI_Fint *win_keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Win_get_attr_fortran_wrapper(win, win_keyval, attribute_val, flag, ierr); } _EXTERN_C_ void mpi_win_get_attr_(MPI_Fint *win, MPI_Fint *win_keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Win_get_attr_fortran_wrapper(win, win_keyval, attribute_val, flag, ierr); } _EXTERN_C_ void mpi_win_get_attr__(MPI_Fint *win, MPI_Fint *win_keyval, MPI_Fint *attribute_val, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Win_get_attr_fortran_wrapper(win, win_keyval, attribute_val, flag, ierr); } /* ================= End Wrappers for MPI_Win_get_attr ================= */ /* ================== C Wrappers for MPI_Win_get_errhandler ================== */ _EXTERN_C_ int PMPI_Win_get_errhandler(MPI_Win win, MPI_Errhandler *errhandler); _EXTERN_C_ int MPI_Win_get_errhandler(MPI_Win win, MPI_Errhandler *errhandler) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_get_errhandler(win, errhandler); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_get_errhandler =============== */ static void MPI_Win_get_errhandler_fortran_wrapper(MPI_Fint *win, MPI_Fint *errhandler, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_get_errhandler((MPI_Win)(*win), (MPI_Errhandler*)errhandler); #else /* MPI-2 safe call */ MPI_Errhandler temp_errhandler; temp_errhandler = MPI_Errhandler_f2c(*errhandler); _wrap_py_return_val = MPI_Win_get_errhandler(MPI_Win_f2c(*win), &temp_errhandler); *errhandler = MPI_Errhandler_c2f(temp_errhandler); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_GET_ERRHANDLER(MPI_Fint *win, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Win_get_errhandler_fortran_wrapper(win, errhandler, ierr); } _EXTERN_C_ void mpi_win_get_errhandler(MPI_Fint *win, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Win_get_errhandler_fortran_wrapper(win, errhandler, ierr); } _EXTERN_C_ void mpi_win_get_errhandler_(MPI_Fint *win, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Win_get_errhandler_fortran_wrapper(win, errhandler, ierr); } _EXTERN_C_ void mpi_win_get_errhandler__(MPI_Fint *win, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Win_get_errhandler_fortran_wrapper(win, errhandler, ierr); } /* ================= End Wrappers for MPI_Win_get_errhandler ================= */ /* ================== C Wrappers for MPI_Win_get_group ================== */ _EXTERN_C_ int PMPI_Win_get_group(MPI_Win win, MPI_Group *group); _EXTERN_C_ int MPI_Win_get_group(MPI_Win win, MPI_Group *group) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_get_group(win, group); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_get_group =============== */ static void MPI_Win_get_group_fortran_wrapper(MPI_Fint *win, MPI_Fint *group, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_get_group((MPI_Win)(*win), (MPI_Group*)group); #else /* MPI-2 safe call */ MPI_Group temp_group; temp_group = MPI_Group_f2c(*group); _wrap_py_return_val = MPI_Win_get_group(MPI_Win_f2c(*win), &temp_group); *group = MPI_Group_c2f(temp_group); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_GET_GROUP(MPI_Fint *win, MPI_Fint *group, MPI_Fint *ierr) { MPI_Win_get_group_fortran_wrapper(win, group, ierr); } _EXTERN_C_ void mpi_win_get_group(MPI_Fint *win, MPI_Fint *group, MPI_Fint *ierr) { MPI_Win_get_group_fortran_wrapper(win, group, ierr); } _EXTERN_C_ void mpi_win_get_group_(MPI_Fint *win, MPI_Fint *group, MPI_Fint *ierr) { MPI_Win_get_group_fortran_wrapper(win, group, ierr); } _EXTERN_C_ void mpi_win_get_group__(MPI_Fint *win, MPI_Fint *group, MPI_Fint *ierr) { MPI_Win_get_group_fortran_wrapper(win, group, ierr); } /* ================= End Wrappers for MPI_Win_get_group ================= */ /* ================== C Wrappers for MPI_Win_get_info ================== */ _EXTERN_C_ int PMPI_Win_get_info(MPI_Win win, MPI_Info *info_used); _EXTERN_C_ int MPI_Win_get_info(MPI_Win win, MPI_Info *info_used) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_get_info(win, info_used); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_get_info =============== */ static void MPI_Win_get_info_fortran_wrapper(MPI_Fint *win, MPI_Fint *info_used, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_get_info((MPI_Win)(*win), (MPI_Info*)info_used); #else /* MPI-2 safe call */ MPI_Info temp_info_used; temp_info_used = MPI_Info_f2c(*info_used); _wrap_py_return_val = MPI_Win_get_info(MPI_Win_f2c(*win), &temp_info_used); *info_used = MPI_Info_c2f(temp_info_used); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_GET_INFO(MPI_Fint *win, MPI_Fint *info_used, MPI_Fint *ierr) { MPI_Win_get_info_fortran_wrapper(win, info_used, ierr); } _EXTERN_C_ void mpi_win_get_info(MPI_Fint *win, MPI_Fint *info_used, MPI_Fint *ierr) { MPI_Win_get_info_fortran_wrapper(win, info_used, ierr); } _EXTERN_C_ void mpi_win_get_info_(MPI_Fint *win, MPI_Fint *info_used, MPI_Fint *ierr) { MPI_Win_get_info_fortran_wrapper(win, info_used, ierr); } _EXTERN_C_ void mpi_win_get_info__(MPI_Fint *win, MPI_Fint *info_used, MPI_Fint *ierr) { MPI_Win_get_info_fortran_wrapper(win, info_used, ierr); } /* ================= End Wrappers for MPI_Win_get_info ================= */ /* ================== C Wrappers for MPI_Win_get_name ================== */ _EXTERN_C_ int PMPI_Win_get_name(MPI_Win win, char *win_name, int *resultlen); _EXTERN_C_ int MPI_Win_get_name(MPI_Win win, char *win_name, int *resultlen) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_get_name(win, win_name, resultlen); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_get_name =============== */ static void MPI_Win_get_name_fortran_wrapper(MPI_Fint *win, MPI_Fint *win_name, MPI_Fint *resultlen, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_get_name((MPI_Win)(*win), (char*)win_name, (int*)resultlen); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_get_name(MPI_Win_f2c(*win), (char*)win_name, (int*)resultlen); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_GET_NAME(MPI_Fint *win, MPI_Fint *win_name, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Win_get_name_fortran_wrapper(win, win_name, resultlen, ierr); } _EXTERN_C_ void mpi_win_get_name(MPI_Fint *win, MPI_Fint *win_name, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Win_get_name_fortran_wrapper(win, win_name, resultlen, ierr); } _EXTERN_C_ void mpi_win_get_name_(MPI_Fint *win, MPI_Fint *win_name, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Win_get_name_fortran_wrapper(win, win_name, resultlen, ierr); } _EXTERN_C_ void mpi_win_get_name__(MPI_Fint *win, MPI_Fint *win_name, MPI_Fint *resultlen, MPI_Fint *ierr) { MPI_Win_get_name_fortran_wrapper(win, win_name, resultlen, ierr); } /* ================= End Wrappers for MPI_Win_get_name ================= */ /* ================== C Wrappers for MPI_Win_lock ================== */ _EXTERN_C_ int PMPI_Win_lock(int lock_type, int rank, int assert, MPI_Win win); _EXTERN_C_ int MPI_Win_lock(int lock_type, int rank, int assert, MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_lock(lock_type, rank, assert, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_lock =============== */ static void MPI_Win_lock_fortran_wrapper(MPI_Fint *lock_type, MPI_Fint *rank, MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_lock(*lock_type, *rank, *assert, (MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_lock(*lock_type, *rank, *assert, MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_LOCK(MPI_Fint *lock_type, MPI_Fint *rank, MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_lock_fortran_wrapper(lock_type, rank, assert, win, ierr); } _EXTERN_C_ void mpi_win_lock(MPI_Fint *lock_type, MPI_Fint *rank, MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_lock_fortran_wrapper(lock_type, rank, assert, win, ierr); } _EXTERN_C_ void mpi_win_lock_(MPI_Fint *lock_type, MPI_Fint *rank, MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_lock_fortran_wrapper(lock_type, rank, assert, win, ierr); } _EXTERN_C_ void mpi_win_lock__(MPI_Fint *lock_type, MPI_Fint *rank, MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_lock_fortran_wrapper(lock_type, rank, assert, win, ierr); } /* ================= End Wrappers for MPI_Win_lock ================= */ /* ================== C Wrappers for MPI_Win_lock_all ================== */ _EXTERN_C_ int PMPI_Win_lock_all(int assert, MPI_Win win); _EXTERN_C_ int MPI_Win_lock_all(int assert, MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_lock_all(assert, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_lock_all =============== */ static void MPI_Win_lock_all_fortran_wrapper(MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_lock_all(*assert, (MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_lock_all(*assert, MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_LOCK_ALL(MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_lock_all_fortran_wrapper(assert, win, ierr); } _EXTERN_C_ void mpi_win_lock_all(MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_lock_all_fortran_wrapper(assert, win, ierr); } _EXTERN_C_ void mpi_win_lock_all_(MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_lock_all_fortran_wrapper(assert, win, ierr); } _EXTERN_C_ void mpi_win_lock_all__(MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_lock_all_fortran_wrapper(assert, win, ierr); } /* ================= End Wrappers for MPI_Win_lock_all ================= */ /* ================== C Wrappers for MPI_Win_post ================== */ _EXTERN_C_ int PMPI_Win_post(MPI_Group group, int assert, MPI_Win win); _EXTERN_C_ int MPI_Win_post(MPI_Group group, int assert, MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_post(group, assert, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_post =============== */ static void MPI_Win_post_fortran_wrapper(MPI_Fint *group, MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_post((MPI_Group)(*group), *assert, (MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_post(MPI_Group_f2c(*group), *assert, MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_POST(MPI_Fint *group, MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_post_fortran_wrapper(group, assert, win, ierr); } _EXTERN_C_ void mpi_win_post(MPI_Fint *group, MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_post_fortran_wrapper(group, assert, win, ierr); } _EXTERN_C_ void mpi_win_post_(MPI_Fint *group, MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_post_fortran_wrapper(group, assert, win, ierr); } _EXTERN_C_ void mpi_win_post__(MPI_Fint *group, MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_post_fortran_wrapper(group, assert, win, ierr); } /* ================= End Wrappers for MPI_Win_post ================= */ /* ================== C Wrappers for MPI_Win_set_attr ================== */ _EXTERN_C_ int PMPI_Win_set_attr(MPI_Win win, int win_keyval, void *attribute_val); _EXTERN_C_ int MPI_Win_set_attr(MPI_Win win, int win_keyval, void *attribute_val) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_set_attr(win, win_keyval, attribute_val); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_set_attr =============== */ static void MPI_Win_set_attr_fortran_wrapper(MPI_Fint *win, MPI_Fint *win_keyval, MPI_Fint *attribute_val, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_set_attr((MPI_Win)(*win), *win_keyval, (void*)attribute_val); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_set_attr(MPI_Win_f2c(*win), *win_keyval, (void*)attribute_val); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_SET_ATTR(MPI_Fint *win, MPI_Fint *win_keyval, MPI_Fint *attribute_val, MPI_Fint *ierr) { MPI_Win_set_attr_fortran_wrapper(win, win_keyval, attribute_val, ierr); } _EXTERN_C_ void mpi_win_set_attr(MPI_Fint *win, MPI_Fint *win_keyval, MPI_Fint *attribute_val, MPI_Fint *ierr) { MPI_Win_set_attr_fortran_wrapper(win, win_keyval, attribute_val, ierr); } _EXTERN_C_ void mpi_win_set_attr_(MPI_Fint *win, MPI_Fint *win_keyval, MPI_Fint *attribute_val, MPI_Fint *ierr) { MPI_Win_set_attr_fortran_wrapper(win, win_keyval, attribute_val, ierr); } _EXTERN_C_ void mpi_win_set_attr__(MPI_Fint *win, MPI_Fint *win_keyval, MPI_Fint *attribute_val, MPI_Fint *ierr) { MPI_Win_set_attr_fortran_wrapper(win, win_keyval, attribute_val, ierr); } /* ================= End Wrappers for MPI_Win_set_attr ================= */ /* ================== C Wrappers for MPI_Win_set_errhandler ================== */ _EXTERN_C_ int PMPI_Win_set_errhandler(MPI_Win win, MPI_Errhandler errhandler); _EXTERN_C_ int MPI_Win_set_errhandler(MPI_Win win, MPI_Errhandler errhandler) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_set_errhandler(win, errhandler); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_set_errhandler =============== */ static void MPI_Win_set_errhandler_fortran_wrapper(MPI_Fint *win, MPI_Fint *errhandler, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_set_errhandler((MPI_Win)(*win), (MPI_Errhandler)(*errhandler)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_set_errhandler(MPI_Win_f2c(*win), MPI_Errhandler_f2c(*errhandler)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_SET_ERRHANDLER(MPI_Fint *win, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Win_set_errhandler_fortran_wrapper(win, errhandler, ierr); } _EXTERN_C_ void mpi_win_set_errhandler(MPI_Fint *win, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Win_set_errhandler_fortran_wrapper(win, errhandler, ierr); } _EXTERN_C_ void mpi_win_set_errhandler_(MPI_Fint *win, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Win_set_errhandler_fortran_wrapper(win, errhandler, ierr); } _EXTERN_C_ void mpi_win_set_errhandler__(MPI_Fint *win, MPI_Fint *errhandler, MPI_Fint *ierr) { MPI_Win_set_errhandler_fortran_wrapper(win, errhandler, ierr); } /* ================= End Wrappers for MPI_Win_set_errhandler ================= */ /* ================== C Wrappers for MPI_Win_set_info ================== */ _EXTERN_C_ int PMPI_Win_set_info(MPI_Win win, MPI_Info info); _EXTERN_C_ int MPI_Win_set_info(MPI_Win win, MPI_Info info) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_set_info(win, info); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_set_info =============== */ static void MPI_Win_set_info_fortran_wrapper(MPI_Fint *win, MPI_Fint *info, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_set_info((MPI_Win)(*win), (MPI_Info)(*info)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_set_info(MPI_Win_f2c(*win), MPI_Info_f2c(*info)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_SET_INFO(MPI_Fint *win, MPI_Fint *info, MPI_Fint *ierr) { MPI_Win_set_info_fortran_wrapper(win, info, ierr); } _EXTERN_C_ void mpi_win_set_info(MPI_Fint *win, MPI_Fint *info, MPI_Fint *ierr) { MPI_Win_set_info_fortran_wrapper(win, info, ierr); } _EXTERN_C_ void mpi_win_set_info_(MPI_Fint *win, MPI_Fint *info, MPI_Fint *ierr) { MPI_Win_set_info_fortran_wrapper(win, info, ierr); } _EXTERN_C_ void mpi_win_set_info__(MPI_Fint *win, MPI_Fint *info, MPI_Fint *ierr) { MPI_Win_set_info_fortran_wrapper(win, info, ierr); } /* ================= End Wrappers for MPI_Win_set_info ================= */ /* ================== C Wrappers for MPI_Win_set_name ================== */ _EXTERN_C_ int PMPI_Win_set_name(MPI_Win win, const char *win_name); _EXTERN_C_ int MPI_Win_set_name(MPI_Win win, const char *win_name) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_set_name(win, win_name); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_set_name =============== */ static void MPI_Win_set_name_fortran_wrapper(MPI_Fint *win, MPI_Fint *win_name, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_set_name((MPI_Win)(*win), (const char*)win_name); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_set_name(MPI_Win_f2c(*win), (const char*)win_name); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_SET_NAME(MPI_Fint *win, MPI_Fint *win_name, MPI_Fint *ierr) { MPI_Win_set_name_fortran_wrapper(win, win_name, ierr); } _EXTERN_C_ void mpi_win_set_name(MPI_Fint *win, MPI_Fint *win_name, MPI_Fint *ierr) { MPI_Win_set_name_fortran_wrapper(win, win_name, ierr); } _EXTERN_C_ void mpi_win_set_name_(MPI_Fint *win, MPI_Fint *win_name, MPI_Fint *ierr) { MPI_Win_set_name_fortran_wrapper(win, win_name, ierr); } _EXTERN_C_ void mpi_win_set_name__(MPI_Fint *win, MPI_Fint *win_name, MPI_Fint *ierr) { MPI_Win_set_name_fortran_wrapper(win, win_name, ierr); } /* ================= End Wrappers for MPI_Win_set_name ================= */ /* ================== C Wrappers for MPI_Win_shared_query ================== */ _EXTERN_C_ int PMPI_Win_shared_query(MPI_Win win, int rank, MPI_Aint *size, int *disp_unit, void *baseptr); _EXTERN_C_ int MPI_Win_shared_query(MPI_Win win, int rank, MPI_Aint *size, int *disp_unit, void *baseptr) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_shared_query(win, rank, size, disp_unit, baseptr); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_shared_query =============== */ static void MPI_Win_shared_query_fortran_wrapper(MPI_Fint *win, MPI_Fint *rank, MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *baseptr, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_shared_query((MPI_Win)(*win), *rank, (MPI_Aint*)size, (int*)disp_unit, (void*)baseptr); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_shared_query(MPI_Win_f2c(*win), *rank, (MPI_Aint*)size, (int*)disp_unit, (void*)baseptr); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_SHARED_QUERY(MPI_Fint *win, MPI_Fint *rank, MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *baseptr, MPI_Fint *ierr) { MPI_Win_shared_query_fortran_wrapper(win, rank, size, disp_unit, baseptr, ierr); } _EXTERN_C_ void mpi_win_shared_query(MPI_Fint *win, MPI_Fint *rank, MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *baseptr, MPI_Fint *ierr) { MPI_Win_shared_query_fortran_wrapper(win, rank, size, disp_unit, baseptr, ierr); } _EXTERN_C_ void mpi_win_shared_query_(MPI_Fint *win, MPI_Fint *rank, MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *baseptr, MPI_Fint *ierr) { MPI_Win_shared_query_fortran_wrapper(win, rank, size, disp_unit, baseptr, ierr); } _EXTERN_C_ void mpi_win_shared_query__(MPI_Fint *win, MPI_Fint *rank, MPI_Aint *size, MPI_Fint *disp_unit, MPI_Fint *baseptr, MPI_Fint *ierr) { MPI_Win_shared_query_fortran_wrapper(win, rank, size, disp_unit, baseptr, ierr); } /* ================= End Wrappers for MPI_Win_shared_query ================= */ /* ================== C Wrappers for MPI_Win_start ================== */ _EXTERN_C_ int PMPI_Win_start(MPI_Group group, int assert, MPI_Win win); _EXTERN_C_ int MPI_Win_start(MPI_Group group, int assert, MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_start(group, assert, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_start =============== */ static void MPI_Win_start_fortran_wrapper(MPI_Fint *group, MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_start((MPI_Group)(*group), *assert, (MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_start(MPI_Group_f2c(*group), *assert, MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_START(MPI_Fint *group, MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_start_fortran_wrapper(group, assert, win, ierr); } _EXTERN_C_ void mpi_win_start(MPI_Fint *group, MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_start_fortran_wrapper(group, assert, win, ierr); } _EXTERN_C_ void mpi_win_start_(MPI_Fint *group, MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_start_fortran_wrapper(group, assert, win, ierr); } _EXTERN_C_ void mpi_win_start__(MPI_Fint *group, MPI_Fint *assert, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_start_fortran_wrapper(group, assert, win, ierr); } /* ================= End Wrappers for MPI_Win_start ================= */ /* ================== C Wrappers for MPI_Win_sync ================== */ _EXTERN_C_ int PMPI_Win_sync(MPI_Win win); _EXTERN_C_ int MPI_Win_sync(MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_sync(win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_sync =============== */ static void MPI_Win_sync_fortran_wrapper(MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_sync((MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_sync(MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_SYNC(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_sync_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_sync(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_sync_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_sync_(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_sync_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_sync__(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_sync_fortran_wrapper(win, ierr); } /* ================= End Wrappers for MPI_Win_sync ================= */ /* ================== C Wrappers for MPI_Win_test ================== */ _EXTERN_C_ int PMPI_Win_test(MPI_Win win, int *flag); _EXTERN_C_ int MPI_Win_test(MPI_Win win, int *flag) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_test(win, flag); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_test =============== */ static void MPI_Win_test_fortran_wrapper(MPI_Fint *win, MPI_Fint *flag, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_test((MPI_Win)(*win), (int*)flag); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_test(MPI_Win_f2c(*win), (int*)flag); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_TEST(MPI_Fint *win, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Win_test_fortran_wrapper(win, flag, ierr); } _EXTERN_C_ void mpi_win_test(MPI_Fint *win, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Win_test_fortran_wrapper(win, flag, ierr); } _EXTERN_C_ void mpi_win_test_(MPI_Fint *win, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Win_test_fortran_wrapper(win, flag, ierr); } _EXTERN_C_ void mpi_win_test__(MPI_Fint *win, MPI_Fint *flag, MPI_Fint *ierr) { MPI_Win_test_fortran_wrapper(win, flag, ierr); } /* ================= End Wrappers for MPI_Win_test ================= */ /* ================== C Wrappers for MPI_Win_unlock ================== */ _EXTERN_C_ int PMPI_Win_unlock(int rank, MPI_Win win); _EXTERN_C_ int MPI_Win_unlock(int rank, MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_unlock(rank, win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_unlock =============== */ static void MPI_Win_unlock_fortran_wrapper(MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_unlock(*rank, (MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_unlock(*rank, MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_UNLOCK(MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_unlock_fortran_wrapper(rank, win, ierr); } _EXTERN_C_ void mpi_win_unlock(MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_unlock_fortran_wrapper(rank, win, ierr); } _EXTERN_C_ void mpi_win_unlock_(MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_unlock_fortran_wrapper(rank, win, ierr); } _EXTERN_C_ void mpi_win_unlock__(MPI_Fint *rank, MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_unlock_fortran_wrapper(rank, win, ierr); } /* ================= End Wrappers for MPI_Win_unlock ================= */ /* ================== C Wrappers for MPI_Win_unlock_all ================== */ _EXTERN_C_ int PMPI_Win_unlock_all(MPI_Win win); _EXTERN_C_ int MPI_Win_unlock_all(MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_unlock_all(win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_unlock_all =============== */ static void MPI_Win_unlock_all_fortran_wrapper(MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_unlock_all((MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_unlock_all(MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_UNLOCK_ALL(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_unlock_all_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_unlock_all(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_unlock_all_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_unlock_all_(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_unlock_all_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_unlock_all__(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_unlock_all_fortran_wrapper(win, ierr); } /* ================= End Wrappers for MPI_Win_unlock_all ================= */ /* ================== C Wrappers for MPI_Win_wait ================== */ _EXTERN_C_ int PMPI_Win_wait(MPI_Win win); _EXTERN_C_ int MPI_Win_wait(MPI_Win win) { int _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Win_wait(win); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Win_wait =============== */ static void MPI_Win_wait_fortran_wrapper(MPI_Fint *win, MPI_Fint *ierr) { int _wrap_py_return_val = 0; #if (!defined(MPICH_HAS_C2F) && defined(MPICH_NAME) && (MPICH_NAME == 1)) /* MPICH test */ _wrap_py_return_val = MPI_Win_wait((MPI_Win)(*win)); #else /* MPI-2 safe call */ _wrap_py_return_val = MPI_Win_wait(MPI_Win_f2c(*win)); #endif /* MPICH test */ *ierr = _wrap_py_return_val; } _EXTERN_C_ void MPI_WIN_WAIT(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_wait_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_wait(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_wait_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_wait_(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_wait_fortran_wrapper(win, ierr); } _EXTERN_C_ void mpi_win_wait__(MPI_Fint *win, MPI_Fint *ierr) { MPI_Win_wait_fortran_wrapper(win, ierr); } /* ================= End Wrappers for MPI_Win_wait ================= */ /* ================== C Wrappers for MPI_Wtick ================== */ _EXTERN_C_ double PMPI_Wtick(); _EXTERN_C_ double MPI_Wtick() { double _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Wtick(); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Wtick =============== */ static double MPI_Wtick_fortran_wrapper() { double _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Wtick(); return _wrap_py_return_val; } _EXTERN_C_ double MPI_WTICK() { return MPI_Wtick_fortran_wrapper(); } _EXTERN_C_ double mpi_wtick() { return MPI_Wtick_fortran_wrapper(); } _EXTERN_C_ double mpi_wtick_() { return MPI_Wtick_fortran_wrapper(); } _EXTERN_C_ double mpi_wtick__() { return MPI_Wtick_fortran_wrapper(); } /* ================= End Wrappers for MPI_Wtick ================= */ /* ================== C Wrappers for MPI_Wtime ================== */ _EXTERN_C_ double PMPI_Wtime(); _EXTERN_C_ double MPI_Wtime() { double _wrap_py_return_val = 0; { WRAP_MPI_CALL_PREFIX _wrap_py_return_val = PMPI_Wtime(); WRAP_MPI_CALL_POSTFIX } return _wrap_py_return_val; } /* =============== Fortran Wrappers for MPI_Wtime =============== */ static double MPI_Wtime_fortran_wrapper() { double _wrap_py_return_val = 0; _wrap_py_return_val = MPI_Wtime(); return _wrap_py_return_val; } _EXTERN_C_ double MPI_WTIME() { return MPI_Wtime_fortran_wrapper(); } _EXTERN_C_ double mpi_wtime() { return MPI_Wtime_fortran_wrapper(); } _EXTERN_C_ double mpi_wtime_() { return MPI_Wtime_fortran_wrapper(); } _EXTERN_C_ double mpi_wtime__() { return MPI_Wtime_fortran_wrapper(); } /* ================= End Wrappers for MPI_Wtime ================= */
GB_binop__isge_int16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__isge_int16) // A.*B function (eWiseMult): GB (_AemultB_08__isge_int16) // A.*B function (eWiseMult): GB (_AemultB_02__isge_int16) // A.*B function (eWiseMult): GB (_AemultB_04__isge_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isge_int16) // A*D function (colscale): GB (_AxD__isge_int16) // D*A function (rowscale): GB (_DxB__isge_int16) // C+=B function (dense accum): GB (_Cdense_accumB__isge_int16) // C+=b function (dense accum): GB (_Cdense_accumb__isge_int16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isge_int16) // C=scalar+B GB (_bind1st__isge_int16) // C=scalar+B' GB (_bind1st_tran__isge_int16) // C=A+scalar GB (_bind2nd__isge_int16) // C=A'+scalar GB (_bind2nd_tran__isge_int16) // C type: int16_t // A type: int16_t // A pattern? 0 // B type: int16_t // B pattern? 0 // BinaryOp: cij = (aij >= bij) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int16_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int16_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x >= y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISGE || GxB_NO_INT16 || GxB_NO_ISGE_INT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__isge_int16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__isge_int16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__isge_int16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int16_t int16_t bwork = (*((int16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__isge_int16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__isge_int16) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isge_int16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; int16_t alpha_scalar ; int16_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int16_t *) alpha_scalar_in)) ; beta_scalar = (*((int16_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__isge_int16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__isge_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__isge_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__isge_int16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__isge_int16) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int16_t bij = GBX (Bx, p, false) ; Cx [p] = (x >= bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__isge_int16) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = GBX (Ax, p, false) ; Cx [p] = (aij >= y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x >= aij) ; \ } GrB_Info GB (_bind1st_tran__isge_int16) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij >= y) ; \ } GrB_Info GB (_bind2nd_tran__isge_int16) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
grib_bits_fast_big_endian_omp.c
/* * (C) Copyright 2005- ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * * In applying this licence, ECMWF does not waive the privileges and immunities granted to it by * virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction. */ /*************************************************************************** * Enrico Fucile - 19.06.2007 * * * ***************************************************************************/ int grib_decode_long_array(const unsigned char* p, long* bitp, long nbits, size_t size, long* val) { long i = 0; long countOfLeftmostBits = 0, leftmostBits = 0; long startBit; long remainingBits = nbits; long* pp = (long*)p; int inited = 0; unsigned long uval = 0; if ((max_nbits % nbits == 0) && (*bitp % nbits == 0)) { #pragma omp parallel for schedule(static) firstprivate(inited, pp) private(startBit, countOfLeftmostBits, remainingBits, leftmostBits) for (i = 0; i < size; i++) { if (!inited) { startBit = *bitp + i * nbits; remainingBits = nbits; if (startBit >= max_nbits) { pp += startBit / max_nbits; startBit %= max_nbits; } inited = 1; } if (startBit == max_nbits) { startBit = 0; pp++; } val[i] = VALUE(*pp, startBit, remainingBits); startBit += remainingBits; remainingBits = nbits; } } else { #pragma omp parallel for schedule(static) firstprivate(inited, pp) private(startBit, countOfLeftmostBits, remainingBits, leftmostBits) for (i = 0; i < size; i++) { if (!inited) { startBit = *bitp + i * nbits; remainingBits = nbits; if (startBit >= max_nbits) { pp += startBit / max_nbits; startBit %= max_nbits; } inited = 1; } countOfLeftmostBits = startBit + remainingBits; if (countOfLeftmostBits > max_nbits) { countOfLeftmostBits = max_nbits - startBit; remainingBits -= countOfLeftmostBits; leftmostBits = (VALUE(*(pp++), startBit, countOfLeftmostBits)) << remainingBits; startBit = 0; } else leftmostBits = 0; val[i] = leftmostBits + (VALUE(*pp, startBit, remainingBits)); startBit += remainingBits; remainingBits = nbits; } } *bitp += size * nbits; return GRIB_SUCCESS; } int grib_decode_double_array(const unsigned char* p, long* bitp, long nbits, double reference_value, double s, double d, size_t size, double* val) { long i = 0; long countOfLeftmostBits = 0, leftmostBits = 0; long startBit; long remainingBits = nbits; long* pp = (long*)p; int inited = 0; unsigned long uval = 0; double fact = s * d; double bias = reference_value * d; if ((max_nbits % nbits == 0) && (*bitp % nbits == 0)) { #pragma omp parallel for schedule(static) firstprivate(inited, pp) private(startBit, countOfLeftmostBits, remainingBits, leftmostBits) for (i = 0; i < size; i++) { if (!inited) { startBit = *bitp + i * nbits; remainingBits = nbits; if (startBit >= max_nbits) { pp += startBit / max_nbits; startBit %= max_nbits; } inited = 1; } if (startBit == max_nbits) { startBit = 0; pp++; } val[i] = VALUE(*pp, startBit, remainingBits); val[i] = val[i] * fact + bias; startBit += remainingBits; remainingBits = nbits; } } else { #pragma omp parallel for schedule(static) firstprivate(inited, pp) private(startBit, countOfLeftmostBits, remainingBits, leftmostBits) for (i = 0; i < size; i++) { if (!inited) { startBit = *bitp + i * nbits; remainingBits = nbits; if (startBit >= max_nbits) { pp += startBit / max_nbits; startBit %= max_nbits; } inited = 1; } countOfLeftmostBits = startBit + remainingBits; if (countOfLeftmostBits > max_nbits) { countOfLeftmostBits = max_nbits - startBit; remainingBits -= countOfLeftmostBits; leftmostBits = (VALUE(*(pp++), startBit, countOfLeftmostBits)) << remainingBits; startBit = 0; } else leftmostBits = 0; val[i] = leftmostBits + (VALUE(*pp, startBit, remainingBits)); val[i] = val[i] * fact + bias; startBit += remainingBits; remainingBits = nbits; } } *bitp += size * nbits; return GRIB_SUCCESS; } int grib_decode_double_array_complex(const unsigned char* p, long* bitp, long nbits, double reference_value, double s, double* d, size_t size, double* val) { long i = 0; long countOfLeftmostBits = 0, leftmostBits = 0; long startBit; long remainingBits = nbits; long* pp = (long*)p; int inited = 0; unsigned long uval = 0; if ((max_nbits % nbits == 0) && (*bitp % nbits == 0)) { #pragma omp parallel for schedule(static) firstprivate(inited, pp) private(startBit, countOfLeftmostBits, remainingBits, leftmostBits) for (i = 0; i < size; i++) { if (!inited) { startBit = *bitp + i * nbits; remainingBits = nbits; if (startBit >= max_nbits) { pp += startBit / max_nbits; startBit %= max_nbits; } inited = 1; } if (startBit == max_nbits) { startBit = 0; pp++; } val[i] = VALUE(*pp, startBit, remainingBits); val[i] = ((((val[i]) * s) + reference_value) * d[i / 2]); startBit += remainingBits; remainingBits = nbits; } } else { #pragma omp parallel for schedule(static) firstprivate(inited, pp) private(startBit, countOfLeftmostBits, remainingBits, leftmostBits) for (i = 0; i < size; i++) { if (!inited) { startBit = *bitp + i * nbits; remainingBits = nbits; if (startBit >= max_nbits) { pp += startBit / max_nbits; startBit %= max_nbits; } inited = 1; } countOfLeftmostBits = startBit + remainingBits; if (countOfLeftmostBits > max_nbits) { countOfLeftmostBits = max_nbits - startBit; remainingBits -= countOfLeftmostBits; leftmostBits = (VALUE(*pp, startBit, countOfLeftmostBits)) << remainingBits; startBit = 0; pp++; } else leftmostBits = 0; val[i] = leftmostBits + (VALUE(*pp, startBit, remainingBits)); val[i] = ((((val[i]) * s) + reference_value) * d[i / 2]); startBit += remainingBits; remainingBits = nbits; } } *bitp += size * nbits; return GRIB_SUCCESS; } int grib_encode_double_array(size_t n_vals, const double* val, long nbits, double reference_value, double d, double divisor, unsigned char* p, long* bitp) { long* destination = (long*)p; double* v = (double*)val; long countOfLeftmostBits = 0, startBit = 0, remainingBits = 0, rightmostBits = 0; unsigned long uval = 0; size_t i = 0; startBit = *bitp; remainingBits = nbits; if (startBit >= max_nbits) { destination += startBit / max_nbits; startBit %= max_nbits; } if ((max_nbits % nbits == 0) && (*bitp % nbits == 0)) { for (i = 0; i < n_vals; i++) { uval = (unsigned long)(((((*v) * d) - reference_value) * divisor) + 0.5); if (startBit == max_nbits) { startBit = 0; destination++; } rightmostBits = VALUE(uval, max_nbits - remainingBits, remainingBits); *destination = ((*destination) & ~MASKVALUE(startBit, remainingBits)) + (rightmostBits << max_nbits - (remainingBits + startBit)); startBit += remainingBits; remainingBits = nbits; v++; } } else { for (i = 0; i < n_vals; i++) { countOfLeftmostBits = startBit + remainingBits; uval = (unsigned long)(((((*v) * d) - reference_value) * divisor) + 0.5); if (countOfLeftmostBits > max_nbits) { countOfLeftmostBits = max_nbits - startBit; startBit = max_nbits - remainingBits; remainingBits -= countOfLeftmostBits; *destination = (((*destination) >> countOfLeftmostBits) << countOfLeftmostBits) + (VALUE(uval, startBit, countOfLeftmostBits)); startBit = 0; destination++; } rightmostBits = VALUE(uval, max_nbits - remainingBits, remainingBits); *destination = ((*destination) & ~MASKVALUE(startBit, remainingBits)) + (rightmostBits << max_nbits - (remainingBits + startBit)); startBit += remainingBits; remainingBits = nbits; v++; } } *bitp += n_vals * nbits; return GRIB_SUCCESS; } int grib_encode_double_array_complex(size_t n_vals, double* val, long nbits, double reference_value, double* scal, double d, double divisor, unsigned char* p, long* bitp) { long* destination = (long*)p; double* v = val; long countOfLeftmostBits = 0, startBit = 0, remainingBits = 0, rightmostBits = 0; unsigned long uval = 0; size_t i = 0; startBit = *bitp; remainingBits = nbits; if (startBit >= max_nbits) { destination += startBit / max_nbits; startBit %= max_nbits; } if ((max_nbits % nbits == 0) && (*bitp % nbits == 0)) { for (i = 0; i < n_vals; i++) { uval = (unsigned long)(((((*v) * d * scal[i / 2]) - reference_value) * divisor) + 0.5); if (startBit == max_nbits) { startBit = 0; destination++; } rightmostBits = VALUE(uval, max_nbits - remainingBits, remainingBits); *destination = ((*destination) & ~MASKVALUE(startBit, remainingBits)) + (rightmostBits << max_nbits - (remainingBits + startBit)); startBit += remainingBits; remainingBits = nbits; v++; } } else { for (i = 0; i < n_vals; i++) { countOfLeftmostBits = startBit + remainingBits; uval = (unsigned long)(((((*v) * d * scal[i / 2]) - reference_value) * divisor) + 0.5); if (countOfLeftmostBits > max_nbits) { countOfLeftmostBits = max_nbits - startBit; startBit = max_nbits - remainingBits; remainingBits -= countOfLeftmostBits; *destination = (((*destination) >> countOfLeftmostBits) << countOfLeftmostBits) + (VALUE(uval, startBit, countOfLeftmostBits)); startBit = 0; destination++; } rightmostBits = VALUE(uval, max_nbits - remainingBits, remainingBits); *destination = ((*destination) & ~MASKVALUE(startBit, remainingBits)) + (rightmostBits << max_nbits - (remainingBits + startBit)); startBit += remainingBits; remainingBits = nbits; v++; } } *bitp += n_vals * nbits; return 0; }
sgemv.c
/*********************************************************************/ /* Copyright 2009, 2010 The University of Texas at Austin. */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or */ /* without modification, are permitted provided that the following */ /* conditions are met: */ /* */ /* 1. Redistributions of source code must retain the above */ /* copyright notice, this list of conditions and the following */ /* disclaimer. */ /* */ /* 2. Redistributions in binary form must reproduce the above */ /* copyright notice, this list of conditions and the following */ /* disclaimer in the documentation and/or other materials */ /* provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF TEXAS AT */ /* AUSTIN ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, */ /* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */ /* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF TEXAS AT */ /* AUSTIN OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE */ /* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR */ /* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF */ /* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT */ /* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ /* POSSIBILITY OF SUCH DAMAGE. */ /* */ /* The views and conclusions contained in the software and */ /* documentation are those of the authors and should not be */ /* interpreted as representing official policies, either expressed */ /* or implied, of The University of Texas at Austin. */ /*********************************************************************/ /* Modified by Marko Vitez for Purdue University */ #include <omp.h> #include <stdio.h> #include <stdlib.h> #include "blas.h" #define GEMM_MULTITHREAD_THRESHOLD 4 void sgemv(char trans, int m, int n, float alpha, float *a, int lda, float *x, int incx, float beta, float *y, int incy) { long range[MAX_CPU_NUMBER+1]; int nthreads; long width; double MNK; int lenx, leny; int i, num_cpu; lenx = m; leny = n; if(trans != 't') { fprintf(stderr, "sgemv not supported for untransposed matrix\n"); exit(0); } if(beta != 1) { fprintf(stderr, "sgemv not supported for beta != 1\n"); exit(0); } if(alpha == 0) return; if(incx < 0) x -= (lenx - 1) * incx; if(incy < 0) y -= (leny - 1) * incy; if(omp_in_parallel()) { sgemv_t(m, n, 0, alpha, a, lda, x, incx, y, incy, 0); return; } MNK = (double) m * (double) n; if(MNK <= 24.0 * 24.0 * GEMM_MULTITHREAD_THRESHOLD*GEMM_MULTITHREAD_THRESHOLD) { sgemv_t(m, n, 0, alpha, a, lda, x, incx, y, incy, 0); return; } range[0] = 0; i = n; nthreads = threads_num; num_cpu = 0; while(i > 0) { width = (i + nthreads - num_cpu - 1) / (nthreads - num_cpu); if(width < 4) width = 4; if(i < width) width = i; range[num_cpu + 1] = range[num_cpu] + width; num_cpu ++; i -= width; } #pragma omp parallel for for(i = 0; i < num_cpu; i++) sgemv_t(m, range[i+1] - range[i], 0, alpha, a + range[i] * lda, lda, x, incx, y + range[i] * incy, incy, 0); }
reduc_map_prob.c
#include <stdio.h> #include <stdlib.h> #define N 5000000 int main(){ double *B, *C; B = (double*)malloc(sizeof(double) * N); C = (double*)malloc(sizeof(double) * N); for(int i = 0; i < N; i++){ B[i] = 1.0; C[i] = 1.0; } double sum = 0; #pragma omp target data map(to:B[0:N], C[0:N]) #pragma omp target teams distribute parallel for reduction(+:sum) map(tofrom:sum) for(int i = 0; i < N; i++) sum += B[i] * C[i]; printf("SUM = %f\n", sum); if (sum != N){ printf("Failed!\n"); return -1; } else{ printf("SUCCESS!\n"); } free(B); free(C); return 0; }
Sqrt.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/Sqrt.c" #else void THNN_(Sqrt_updateOutput)( THNNState *state, THTensor *input, THTensor *output, accreal eps_) { THTensor_(resizeAs)(output, input); THTensor_(sqrt)(output, input); } void THNN_(Sqrt_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THTensor *output) { THNN_CHECK_SHAPE(output, gradOutput); THTensor_(resizeAs)(gradInput, input); if (THTensor_nDimensionLegacyAll(output) == 1 || !THTensor_(isContiguous)(output) || !THTensor_(isContiguous)(gradOutput) || !THTensor_(isContiguous)(gradInput)) { TH_TENSOR_APPLY3(real, gradInput, real, gradOutput, real, output, *gradInput_data = (*output_data == 0.0) ? 0.0 : (0.5 * (*gradOutput_data / *output_data)); ); } else { real *gradOutput_data = THTensor_(data)(gradOutput); real *gradInput_data = THTensor_(data)(gradInput); real *output_data = THTensor_(data)(output); int64_t i; #pragma omp parallel for private(i) for(i = 0; i < THTensor_(nElement)(output); i++) { if (output_data[i] == 0.0) gradInput_data[i] = 0.0; else gradInput_data[i] = 0.5 * (gradOutput_data[i] / output_data[i]); } } } #endif
sparselu.c
/**********************************************************************************************/ /* This program is part of the Barcelona OpenMP Tasks Suite */ /* Copyright (C) 2009 Barcelona Supercomputing Center - Centro Nacional de Supercomputacion */ /* Copyright (C) 2009 Universitat Politecnica de Catalunya */ /* */ /* This program is free software; you can redistribute it and/or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation; either version 2 of the License, or */ /* (at your option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with this program; if not, write to the Free Software */ /* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /**********************************************************************************************/ #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <libgen.h> #include "bots.h" #include "sparselu.h" #include "my_include.h" /*********************************************************************** * checkmat: **********************************************************************/ //float tmp[bots_arg_size][bots_arg_size][bots_arg_size_1*bots_arg_size_1]; int checkmat (float *M, float *N) { //printf("11111\n"); int i, j; float r_err; for (i = 0; i < bots_arg_size_1; i++) { for (j = 0; j < bots_arg_size_1; j++) { r_err = M[i*bots_arg_size_1+j] - N[i*bots_arg_size_1+j]; if (r_err < 0.0 ) r_err = -r_err; r_err = r_err / M[i*bots_arg_size_1+j]; if(r_err > EPSILON) { bots_message("Checking failure: A[%d][%d]=%f B[%d][%d]=%f; Relative Error=%f\n", i,j, M[i*bots_arg_size_1+j], i,j, N[i*bots_arg_size_1+j], r_err); return FALSE; } } } return TRUE; } /*********************************************************************** * genmat: **********************************************************************/ void genmat (float *M[]) { int null_entry, init_val, i, j, ii, jj; float *p; float *prow; float rowsum; init_val = 1325; /* generating the structure */ for (ii=0; ii < bots_arg_size; ii++) { for (jj=0; jj < bots_arg_size; jj++) { /* computing null entries */ null_entry=FALSE; if ((ii<jj) && (ii%3 !=0)) null_entry = TRUE; if ((ii>jj) && (jj%3 !=0)) null_entry = TRUE; if (ii%2==1) null_entry = TRUE; if (jj%2==1) null_entry = TRUE; if (ii==jj) null_entry = FALSE; if (ii==jj-1) null_entry = FALSE; if (ii-1 == jj) null_entry = FALSE; /* allocating matrix */ if (null_entry == FALSE){ // M[ii*bots_arg_size+jj] = (float *) malloc(bots_arg_size_1*bots_arg_size_1*sizeof(float)); M[ii*bots_arg_size+jj] = (float*)tmp + tmp_pos; tmp_pos += bots_arg_size_1*bots_arg_size_1*sizeof(float); if ((M[ii*bots_arg_size+jj] == NULL)) { bots_message("Error: Out of memory\n"); exit(101); } /* initializing matrix */ /* Modify diagonal element of each row in order */ /* to ensure matrix is diagonally dominant and */ /* well conditioned. */ prow = p = M[ii*bots_arg_size+jj]; for (i = 0; i < bots_arg_size_1; i++) { rowsum = 0.0; for (j = 0; j < bots_arg_size_1; j++) { init_val = (3125 * init_val) % 65536; (*p) = (float)((init_val - 32768.0) / 16384.0); rowsum += abs(*p); p++; } if (ii == jj) *(prow+i) = rowsum * (float) bots_arg_size + abs(*(prow+i)); prow += bots_arg_size_1; } } else { M[ii*bots_arg_size+jj] = NULL; } } } } /*********************************************************************** * print_structure: **********************************************************************/ void print_structure(char *name, float *M[]) { int ii, jj; bots_message("Structure for matrix %s @ 0x%p\n",name, M); for (ii = 0; ii < bots_arg_size; ii++) { for (jj = 0; jj < bots_arg_size; jj++) { if (M[ii*bots_arg_size+jj]!=NULL) {bots_message("x");} else bots_message(" "); } bots_message("\n"); } bots_message("\n"); } /*********************************************************************** * allocate_clean_block: **********************************************************************/ float * allocate_clean_block() { int i,j; float *p, *q; //printf("1\n"); //p = (float *) malloc(bots_arg_size_1*bots_arg_size_1*sizeof(float)); p = (float*)tmp + tmp_pos; tmp_pos += bots_arg_size_1*bots_arg_size_1*sizeof(float); q=p; if (p!=NULL){ for (i = 0; i < bots_arg_size_1; i++) for (j = 0; j < bots_arg_size_1; j++){(*p)=0.0; p++;} } else { bots_message("Error: Out of memory\n"); exit (101); } return (q); } /*********************************************************************** * lu0: **********************************************************************/ void lu0(float *diag) { int i, j, k; for (k=0; k<bots_arg_size_1; k++) for (i=k+1; i<bots_arg_size_1; i++) { diag[i*bots_arg_size_1+k] = diag[i*bots_arg_size_1+k] / diag[k*bots_arg_size_1+k]; for (j=k+1; j<bots_arg_size_1; j++) diag[i*bots_arg_size_1+j] = diag[i*bots_arg_size_1+j] - diag[i*bots_arg_size_1+k] * diag[k*bots_arg_size_1+j]; } } /*********************************************************************** * bdiv: **********************************************************************/ void bdiv(float *diag, float *row) { int i, j, k; for (i=0; i<bots_arg_size_1; i++) { for (k=0; k<bots_arg_size_1; k++) { row[i*bots_arg_size_1+k] = row[i*bots_arg_size_1+k] / diag[k*bots_arg_size_1+k]; for (j=k+1; j<bots_arg_size_1; j++) row[i*bots_arg_size_1+j] = row[i*bots_arg_size_1+j] - row[i*bots_arg_size_1+k]*diag[k*bots_arg_size_1+j]; } //kai flag5 = i; } } /*********************************************************************** * bmod: **********************************************************************/ void bmod(float *row, float *col, float *inner) { int i, j, k; for (i=0; i<bots_arg_size_1; i++) for (j=0; j<bots_arg_size_1; j++) for (k=0; k<bots_arg_size_1; k++) inner[i*bots_arg_size_1+j] = inner[i*bots_arg_size_1+j] - row[i*bots_arg_size_1+k]*col[k*bots_arg_size_1+j]; } /*********************************************************************** * fwd: **********************************************************************/ void fwd(float *diag, float *col) { int i, j, k; for (j=0; j<bots_arg_size_1; j++) for (k=0; k<bots_arg_size_1; k++) for (i=k+1; i<bots_arg_size_1; i++) col[i*bots_arg_size_1+j] = col[i*bots_arg_size_1+j] - diag[i*bots_arg_size_1+k]*col[k*bots_arg_size_1+j]; } void sparselu_init (float ***pBENCH, char *pass) { // *pBENCH = (float **) malloc(bots_arg_size*bots_arg_size*sizeof(float *)); // printf("%s\n", pass): tmp = malloc(bots_arg_size*bots_arg_size*sizeof(float *) + (3)*(bots_arg_size*bots_arg_size*bots_arg_size_1*bots_arg_size_1*sizeof(float))); *pBENCH = (float **)tmp + tmp_pos; tmp_pos += bots_arg_size*bots_arg_size*sizeof(float *); genmat(*pBENCH); crucial_data(tmp, "double", bots_arg_size*bots_arg_size*sizeof(float *) + (bots_arg_size*bots_arg_size*bots_arg_size_1*bots_arg_size_1*sizeof(float))); /* spec print_structure(pass, *pBENCH); */ } void sparselu_par_call(float **BENCH) { //printf("1111\n"); int ii, jj, kk; bots_message("Computing SparseLU Factorization (%dx%d matrix with %dx%d blocks) ", bots_arg_size,bots_arg_size,bots_arg_size_1,bots_arg_size_1); //kai consistent_data(&flag1, "int", 1); consistent_data(&flag2, "int", 1); start_crash(); #pragma omp parallel #pragma omp single nowait for (kk=0; kk<bots_arg_size; kk++) { lu0(BENCH[kk*bots_arg_size+kk]); for (jj=kk+1; jj<bots_arg_size; jj++) { if (BENCH[kk*bots_arg_size+jj] != NULL) #pragma omp task untied firstprivate(kk, jj) shared(BENCH) { fwd(BENCH[kk*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj]); } //kai flag2 = kk; } for (ii=kk+1; ii<bots_arg_size; ii++) { if (BENCH[ii*bots_arg_size+kk] != NULL) #pragma omp task untied firstprivate(kk, ii) shared(BENCH) { bdiv (BENCH[kk*bots_arg_size+kk], BENCH[ii*bots_arg_size+kk]); } //kai flag3 = ii; } #pragma omp taskwait //printf("1111111111111\n"); for (ii=kk+1; ii<bots_arg_size; ii++) { if (BENCH[ii*bots_arg_size+kk] != NULL) for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) #pragma omp task untied firstprivate(kk, jj, ii) shared(BENCH) { if (BENCH[ii*bots_arg_size+jj]==NULL) BENCH[ii*bots_arg_size+jj] = allocate_clean_block(); bmod(BENCH[ii*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj], BENCH[ii*bots_arg_size+jj]); } //kai flag4 = ii; } #pragma omp taskwait flag1 = kk; } //kai end_crash(); bots_message(" completed!\n"); } void sparselu_seq_call(float **BENCH) { int ii, jj, kk; for (kk=0; kk<bots_arg_size; kk++) { lu0(BENCH[kk*bots_arg_size+kk]); for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) { fwd(BENCH[kk*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj]); } for (ii=kk+1; ii<bots_arg_size; ii++) if (BENCH[ii*bots_arg_size+kk] != NULL) { bdiv (BENCH[kk*bots_arg_size+kk], BENCH[ii*bots_arg_size+kk]); } for (ii=kk+1; ii<bots_arg_size; ii++) if (BENCH[ii*bots_arg_size+kk] != NULL) for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) { if (BENCH[ii*bots_arg_size+jj]==NULL) BENCH[ii*bots_arg_size+jj] = allocate_clean_block(); bmod(BENCH[ii*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj], BENCH[ii*bots_arg_size+jj]); } } } void sparselu_fini (float **BENCH, char *pass) { /* spec print_structure(pass, BENCH); */ return; } /* * changes for SPEC, original source * int sparselu_check(float **SEQ, float **BENCH) { int ii,jj,ok=1; for (ii=0; ((ii<bots_arg_size) && ok); ii++) { for (jj=0; ((jj<bots_arg_size) && ok); jj++) { if ((SEQ[ii*bots_arg_size+jj] == NULL) && (BENCH[ii*bots_arg_size+jj] != NULL)) ok = FALSE; if ((SEQ[ii*bots_arg_size+jj] != NULL) && (BENCH[ii*bots_arg_size+jj] == NULL)) ok = FALSE; if ((SEQ[ii*bots_arg_size+jj] != NULL) && (BENCH[ii*bots_arg_size+jj] != NULL)) ok = checkmat(SEQ[ii*bots_arg_size+jj], BENCH[ii*bots_arg_size+jj]); } } if (ok) return BOTS_RESULT_SUCCESSFUL; else return BOTS_RESULT_UNSUCCESSFUL; } */ /* * SPEC modified check, print out values * */ int sparselu_check(float **SEQ, float **BENCH) { int i, j, ok; bots_message("Output size: %d\n",bots_arg_size); for (i = 0; i < bots_arg_size; i+=50) { for (j = 0; j < bots_arg_size; j+=40) { ok = checkmat1(BENCH[i*bots_arg_size+j]); } } return BOTS_RESULT_SUCCESSFUL; } int checkmat1 (float *N) { int i, j; for (i = 0; i < bots_arg_size_1; i+=20) { for (j = 0; j < bots_arg_size_1; j+=20) { bots_message("Output Matrix: A[%d][%d]=%8.12f \n", i,j, N[i*bots_arg_size_1+j]); } } //printf("111111111\n"); return TRUE; }
wand-view.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % W W AAA N N DDDD % % W W A A NN N D D % % W W W AAAAA N N N D D % % WW WW A A N NN D D % % W W A A N N DDDD % % % % V V IIIII EEEEE W W % % V V I E W W % % V V I EEE W W W % % V V I E WW WW % % V IIIII EEEEE W W % % % % % % MagickWand Wand View Methods % % % % Software Design % % Cristy % % March 2003 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickWand/studio.h" #include "MagickWand/MagickWand.h" #include "MagickWand/magick-wand-private.h" #include "MagickWand/wand.h" #include "MagickCore/monitor-private.h" #include "MagickCore/thread-private.h" /* Define declarations. */ #define WandViewId "WandView" /* Typedef declarations. */ struct _WandView { size_t id; char name[MagickPathExtent], *description; RectangleInfo extent; MagickWand *wand; Image *image; CacheView *view; PixelWand ***pixel_wands; ExceptionInfo *exception; MagickBooleanType debug; size_t signature; }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e W a n d V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneWandView() makes a copy of the specified wand view. % % The format of the CloneWandView method is: % % WandView *CloneWandView(const WandView *wand_view) % % A description of each parameter follows: % % o wand_view: the wand view. % */ WandExport WandView *CloneWandView(const WandView *wand_view) { WandView *clone_view; register ssize_t i; assert(wand_view != (WandView *) NULL); assert(wand_view->signature == MagickWandSignature); if (wand_view->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand_view->name); clone_view=(WandView *) AcquireMagickMemory(sizeof(*clone_view)); if (clone_view == (WandView *) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", wand_view->name); (void) ResetMagickMemory(clone_view,0,sizeof(*clone_view)); clone_view->id=AcquireWandId(); (void) FormatLocaleString(clone_view->name,MagickPathExtent,"%s-%.20g", WandViewId,(double) clone_view->id); clone_view->description=ConstantString(wand_view->description); clone_view->image=CloneImage(wand_view->image,0,0,MagickTrue, wand_view->exception); clone_view->view=CloneCacheView(wand_view->view); clone_view->extent=wand_view->extent; clone_view->exception=AcquireExceptionInfo(); InheritException(clone_view->exception,wand_view->exception); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) clone_view->pixel_wands[i]=ClonePixelWands((const PixelWand **) wand_view->pixel_wands[i],wand_view->extent.width); clone_view->debug=wand_view->debug; if (clone_view->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",clone_view->name); clone_view->signature=MagickWandSignature; return(clone_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y W a n d V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyWandView() deallocates memory associated with a wand view. % % The format of the DestroyWandView method is: % % WandView *DestroyWandView(WandView *wand_view) % % A description of each parameter follows: % % o wand_view: the wand view. % */ static PixelWand ***DestroyPixelsThreadSet(PixelWand ***pixel_wands, const size_t number_wands) { register ssize_t i; assert(pixel_wands != (PixelWand ***) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixel_wands[i] != (PixelWand **) NULL) pixel_wands[i]=DestroyPixelWands(pixel_wands[i],number_wands); pixel_wands=(PixelWand ***) RelinquishMagickMemory(pixel_wands); return(pixel_wands); } WandExport WandView *DestroyWandView(WandView *wand_view) { assert(wand_view != (WandView *) NULL); assert(wand_view->signature == MagickWandSignature); wand_view->pixel_wands=DestroyPixelsThreadSet(wand_view->pixel_wands, wand_view->extent.width); wand_view->image=DestroyImage(wand_view->image); wand_view->view=DestroyCacheView(wand_view->view); wand_view->exception=DestroyExceptionInfo(wand_view->exception); wand_view->signature=(~MagickWandSignature); RelinquishWandId(wand_view->id); wand_view=(WandView *) RelinquishMagickMemory(wand_view); return(wand_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D u p l e x T r a n s f e r W a n d V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DuplexTransferWandViewIterator() iterates over three wand views in % parallel and calls your transfer method for each scanline of the view. The % source and duplex pixel extent is not confined to the image canvas-- that is % you can include negative offsets or widths or heights that exceed the image % dimension. However, the destination wand view is confined to the image % canvas-- that is no negative offsets or widths or heights that exceed the % image dimension are permitted. % % The callback signature is: % % MagickBooleanType DuplexTransferImageViewMethod(const WandView *source, % const WandView *duplex,WandView *destination,const ssize_t y, % const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback transfer method that must be % executed by a single thread at a time. % % The format of the DuplexTransferWandViewIterator method is: % % MagickBooleanType DuplexTransferWandViewIterator(WandView *source, % WandView *duplex,WandView *destination, % DuplexTransferWandViewMethod transfer,void *context) % % A description of each parameter follows: % % o source: the source wand view. % % o duplex: the duplex wand view. % % o destination: the destination wand view. % % o transfer: the transfer callback method. % % o context: the user defined context. % */ WandExport MagickBooleanType DuplexTransferWandViewIterator(WandView *source, WandView *duplex,WandView *destination,DuplexTransferWandViewMethod transfer, void *context) { Image *destination_image, *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (WandView *) NULL); assert(source->signature == MagickWandSignature); if (transfer == (DuplexTransferWandViewMethod) NULL) return(MagickFalse); source_image=source->wand->images; destination_image=destination->wand->images; status=SetImageStorageClass(destination_image,DirectClass, destination->exception); if (status == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=source->extent.height-source->extent.y; #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(source_image,destination_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register const Quantum *magick_restrict duplex_pixels, *magick_restrict pixels; register ssize_t x; register Quantum *magick_restrict destination_pixels; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source->extent.width; x++) { PixelSetQuantumPixel(source->image,pixels,source->pixel_wands[id][x]); pixels+=GetPixelChannels(source->image); } duplex_pixels=GetCacheViewVirtualPixels(duplex->view,duplex->extent.x,y, duplex->extent.width,1,duplex->exception); if (duplex_pixels == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) duplex->extent.width; x++) { PixelSetQuantumPixel(duplex->image,duplex_pixels, duplex->pixel_wands[id][x]); duplex_pixels+=GetPixelChannels(duplex->image); } destination_pixels=GetCacheViewAuthenticPixels(destination->view, destination->extent.x,y,destination->extent.width,1, destination->exception); if (destination_pixels == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) destination->extent.width; x++) { PixelSetQuantumPixel(destination->image,destination_pixels, destination->pixel_wands[id][x]); destination_pixels+=GetPixelChannels(destination->image); } if (transfer(source,duplex,destination,y,id,context) == MagickFalse) status=MagickFalse; destination_pixels=GetCacheViewAuthenticPixels(destination->view, destination->extent.x,y,destination->extent.width,1, destination->exception); for (x=0; x < (ssize_t) destination->extent.width; x++) { PixelGetQuantumPixel(destination->image,destination->pixel_wands[id][x], destination_pixels); destination_pixels+=GetPixelChannels(destination->image); } sync=SyncCacheViewAuthenticPixels(destination->view,destination->exception); if (sync == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickWand_DuplexTransferWandViewIterator) #endif proceed=SetImageProgress(source_image,source->description,progress++, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t W a n d V i e w E x c e p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetWandViewException() returns the severity, reason, and description of any % error that occurs when utilizing a wand view. % % The format of the GetWandViewException method is: % % char *GetWandViewException(const WandView *wand_view, % ExceptionType *severity) % % A description of each parameter follows: % % o wand_view: the pixel wand_view. % % o severity: the severity of the error is returned here. % */ WandExport char *GetWandViewException(const WandView *wand_view, ExceptionType *severity) { char *description; assert(wand_view != (const WandView *) NULL); assert(wand_view->signature == MagickWandSignature); if (wand_view->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand_view->name); assert(severity != (ExceptionType *) NULL); *severity=wand_view->exception->severity; description=(char *) AcquireQuantumMemory(2UL*MagickPathExtent, sizeof(*description)); if (description == (char *) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", wand_view->name); *description='\0'; if (wand_view->exception->reason != (char *) NULL) (void) CopyMagickString(description,GetLocaleExceptionMessage( wand_view->exception->severity,wand_view->exception->reason), MagickPathExtent); if (wand_view->exception->description != (char *) NULL) { (void) ConcatenateMagickString(description," (",MagickPathExtent); (void) ConcatenateMagickString(description,GetLocaleExceptionMessage( wand_view->exception->severity,wand_view->exception->description), MagickPathExtent); (void) ConcatenateMagickString(description,")",MagickPathExtent); } return(description); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t W a n d V i e w E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetWandViewExtent() returns the wand view extent. % % The format of the GetWandViewExtent method is: % % RectangleInfo GetWandViewExtent(const WandView *wand_view) % % A description of each parameter follows: % % o wand_view: the wand view. % */ WandExport RectangleInfo GetWandViewExtent(const WandView *wand_view) { assert(wand_view != (WandView *) NULL); assert(wand_view->signature == MagickWandSignature); return(wand_view->extent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t W a n d V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetWandViewIterator() iterates over the wand view in parallel and calls % your get method for each scanline of the view. The pixel extent is % not confined to the image canvas-- that is you can include negative offsets % or widths or heights that exceed the image dimension. Any updates to % the pixels in your callback are ignored. % % The callback signature is: % % MagickBooleanType GetImageViewMethod(const WandView *source, % const ssize_t y,const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback get method that must be % executed by a single thread at a time. % % The format of the GetWandViewIterator method is: % % MagickBooleanType GetWandViewIterator(WandView *source, % GetWandViewMethod get,void *context) % % A description of each parameter follows: % % o source: the source wand view. % % o get: the get callback method. % % o context: the user defined context. % */ WandExport MagickBooleanType GetWandViewIterator(WandView *source, GetWandViewMethod get,void *context) { Image *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (WandView *) NULL); assert(source->signature == MagickWandSignature); if (get == (GetWandViewMethod) NULL) return(MagickFalse); source_image=source->wand->images; status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=source->extent.height-source->extent.y; #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(source_image,source_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); register const Quantum *pixels; register ssize_t x; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source->extent.width; x++) { PixelSetQuantumPixel(source->image,pixels,source->pixel_wands[id][x]); pixels+=GetPixelChannels(source->image); } if (get(source,y,id,context) == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickWand_GetWandViewIterator) #endif proceed=SetImageProgress(source_image,source->description,progress++, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t W a n d V i e w P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetWandViewPixels() returns the wand view pixel_wands. % % The format of the GetWandViewPixels method is: % % PixelWand *GetWandViewPixels(const WandView *wand_view) % % A description of each parameter follows: % % o wand_view: the wand view. % */ WandExport PixelWand **GetWandViewPixels(const WandView *wand_view) { const int id = GetOpenMPThreadId(); assert(wand_view != (WandView *) NULL); assert(wand_view->signature == MagickWandSignature); return(wand_view->pixel_wands[id]); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t W a n d V i e w W a n d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetWandViewWand() returns the magick wand associated with the wand view. % % The format of the GetWandViewWand method is: % % MagickWand *GetWandViewWand(const WandView *wand_view) % % A description of each parameter follows: % % o wand_view: the wand view. % */ WandExport MagickWand *GetWandViewWand(const WandView *wand_view) { assert(wand_view != (WandView *) NULL); assert(wand_view->signature == MagickWandSignature); return(wand_view->wand); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s W a n d V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsWandView() returns MagickTrue if the the parameter is verified as a wand % view object. % % The format of the IsWandView method is: % % MagickBooleanType IsWandView(const WandView *wand_view) % % A description of each parameter follows: % % o wand_view: the wand view. % */ WandExport MagickBooleanType IsWandView(const WandView *wand_view) { size_t length; if (wand_view == (const WandView *) NULL) return(MagickFalse); if (wand_view->signature != MagickWandSignature) return(MagickFalse); length=strlen(WandViewId); if (LocaleNCompare(wand_view->name,WandViewId,length) != 0) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w W a n d V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewWandView() returns a wand view required for all other methods in the % Wand View API. % % The format of the NewWandView method is: % % WandView *NewWandView(MagickWand *wand) % % A description of each parameter follows: % % o wand: the wand. % */ static PixelWand ***AcquirePixelsThreadSet(const size_t number_wands) { PixelWand ***pixel_wands; register ssize_t i; size_t number_threads; number_threads=GetOpenMPMaximumThreads(); pixel_wands=(PixelWand ***) AcquireQuantumMemory(number_threads, sizeof(*pixel_wands)); if (pixel_wands == (PixelWand ***) NULL) return((PixelWand ***) NULL); (void) ResetMagickMemory(pixel_wands,0,number_threads*sizeof(*pixel_wands)); for (i=0; i < (ssize_t) number_threads; i++) { pixel_wands[i]=NewPixelWands(number_wands); if (pixel_wands[i] == (PixelWand **) NULL) return(DestroyPixelsThreadSet(pixel_wands,number_wands)); } return(pixel_wands); } WandExport WandView *NewWandView(MagickWand *wand) { ExceptionInfo *exception; WandView *wand_view; assert(wand != (MagickWand *) NULL); assert(wand->signature == MagickWandSignature); wand_view=(WandView *) AcquireMagickMemory(sizeof(*wand_view)); if (wand_view == (WandView *) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", GetExceptionMessage(errno)); (void) ResetMagickMemory(wand_view,0,sizeof(*wand_view)); wand_view->id=AcquireWandId(); (void) FormatLocaleString(wand_view->name,MagickPathExtent,"%s-%.20g", WandViewId,(double) wand_view->id); wand_view->description=ConstantString("WandView"); wand_view->wand=wand; exception=AcquireExceptionInfo(); wand_view->view=AcquireVirtualCacheView(wand_view->wand->images,exception); wand_view->extent.width=wand->images->columns; wand_view->extent.height=wand->images->rows; wand_view->pixel_wands=AcquirePixelsThreadSet(wand_view->extent.width); wand_view->exception=exception; if (wand_view->pixel_wands == (PixelWand ***) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", GetExceptionMessage(errno)); wand_view->debug=IsEventLogging(); wand_view->signature=MagickWandSignature; return(wand_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w W a n d V i e w E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewWandViewExtent() returns a wand view required for all other methods % in the Wand View API. % % The format of the NewWandViewExtent method is: % % WandView *NewWandViewExtent(MagickWand *wand,const ssize_t x, % const ssize_t y,const size_t width,const size_t height) % % A description of each parameter follows: % % o wand: the magick wand. % % o x,y,columns,rows: These values define the perimeter of a extent of % pixel_wands view. % */ WandExport WandView *NewWandViewExtent(MagickWand *wand,const ssize_t x, const ssize_t y,const size_t width,const size_t height) { ExceptionInfo *exception; WandView *wand_view; assert(wand != (MagickWand *) NULL); assert(wand->signature == MagickWandSignature); wand_view=(WandView *) AcquireMagickMemory(sizeof(*wand_view)); if (wand_view == (WandView *) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", GetExceptionMessage(errno)); (void) ResetMagickMemory(wand_view,0,sizeof(*wand_view)); wand_view->id=AcquireWandId(); (void) FormatLocaleString(wand_view->name,MagickPathExtent,"%s-%.20g", WandViewId,(double) wand_view->id); wand_view->description=ConstantString("WandView"); exception=AcquireExceptionInfo(); wand_view->view=AcquireVirtualCacheView(wand_view->wand->images,exception); wand_view->wand=wand; wand_view->extent.width=width; wand_view->extent.height=height; wand_view->extent.x=x; wand_view->extent.y=y; wand_view->exception=exception; wand_view->pixel_wands=AcquirePixelsThreadSet(wand_view->extent.width); if (wand_view->pixel_wands == (PixelWand ***) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", GetExceptionMessage(errno)); wand_view->debug=IsEventLogging(); wand_view->signature=MagickWandSignature; return(wand_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t W a n d V i e w D e s c r i p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetWandViewDescription() associates a description with an image view. % % The format of the SetWandViewDescription method is: % % void SetWandViewDescription(WandView *image_view,const char *description) % % A description of each parameter follows: % % o wand_view: the wand view. % % o description: the wand view description. % */ MagickExport void SetWandViewDescription(WandView *wand_view, const char *description) { assert(wand_view != (WandView *) NULL); assert(wand_view->signature == MagickWandSignature); wand_view->description=ConstantString(description); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t W a n d V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetWandViewIterator() iterates over the wand view in parallel and calls % your set method for each scanline of the view. The pixel extent is % confined to the image canvas-- that is no negative offsets or widths or % heights that exceed the image dimension. The pixels are initiallly % undefined and any settings you make in the callback method are automagically % synced back to your image. % % The callback signature is: % % MagickBooleanType SetImageViewMethod(ImageView *destination, % const ssize_t y,const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback set method that must be % executed by a single thread at a time. % % The format of the SetWandViewIterator method is: % % MagickBooleanType SetWandViewIterator(WandView *destination, % SetWandViewMethod set,void *context) % % A description of each parameter follows: % % o destination: the wand view. % % o set: the set callback method. % % o context: the user defined context. % */ WandExport MagickBooleanType SetWandViewIterator(WandView *destination, SetWandViewMethod set,void *context) { Image *destination_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(destination != (WandView *) NULL); assert(destination->signature == MagickWandSignature); if (set == (SetWandViewMethod) NULL) return(MagickFalse); destination_image=destination->wand->images; status=SetImageStorageClass(destination_image,DirectClass, destination->exception); if (status == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=destination->extent.height-destination->extent.y; #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(destination_image,destination_image,height,1) #endif for (y=destination->extent.y; y < (ssize_t) destination->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register ssize_t x; register Quantum *magick_restrict pixels; if (status == MagickFalse) continue; pixels=GetCacheViewAuthenticPixels(destination->view,destination->extent.x, y,destination->extent.width,1,destination->exception); if (pixels == (Quantum *) NULL) { status=MagickFalse; continue; } if (set(destination,y,id,context) == MagickFalse) status=MagickFalse; for (x=0; x < (ssize_t) destination->extent.width; x++) { PixelGetQuantumPixel(destination->image,destination->pixel_wands[id][x], pixels); pixels+=GetPixelChannels(destination->image); } sync=SyncCacheViewAuthenticPixels(destination->view,destination->exception); if (sync == MagickFalse) status=MagickFalse; if (destination_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickWand_SetWandViewIterator) #endif proceed=SetImageProgress(destination_image,destination->description, progress++,destination->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s f e r W a n d V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransferWandViewIterator() iterates over two wand views in parallel and % calls your transfer method for each scanline of the view. The source pixel % extent is not confined to the image canvas-- that is you can include % negative offsets or widths or heights that exceed the image dimension. % However, the destination wand view is confined to the image canvas-- that % is no negative offsets or widths or heights that exceed the image dimension % are permitted. % % The callback signature is: % % MagickBooleanType TransferImageViewMethod(const WandView *source, % WandView *destination,const ssize_t y,const int thread_id, % void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback transfer method that must be % executed by a single thread at a time. % % The format of the TransferWandViewIterator method is: % % MagickBooleanType TransferWandViewIterator(WandView *source, % WandView *destination,TransferWandViewMethod transfer,void *context) % % A description of each parameter follows: % % o source: the source wand view. % % o destination: the destination wand view. % % o transfer: the transfer callback method. % % o context: the user defined context. % */ WandExport MagickBooleanType TransferWandViewIterator(WandView *source, WandView *destination,TransferWandViewMethod transfer,void *context) { Image *destination_image, *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (WandView *) NULL); assert(source->signature == MagickWandSignature); if (transfer == (TransferWandViewMethod) NULL) return(MagickFalse); source_image=source->wand->images; destination_image=destination->wand->images; status=SetImageStorageClass(destination_image,DirectClass, destination->exception); if (status == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=source->extent.height-source->extent.y; #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(source_image,destination_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register const Quantum *magick_restrict pixels; register ssize_t x; register Quantum *magick_restrict destination_pixels; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source->extent.width; x++) { PixelSetQuantumPixel(source->image,pixels,source->pixel_wands[id][x]); pixels+=GetPixelChannels(source->image); } destination_pixels=GetCacheViewAuthenticPixels(destination->view, destination->extent.x,y,destination->extent.width,1, destination->exception); if (destination_pixels == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) destination->extent.width; x++) { PixelSetQuantumPixel(destination->image,destination_pixels, destination->pixel_wands[id][x]); destination_pixels+=GetPixelChannels(destination->image); } if (transfer(source,destination,y,id,context) == MagickFalse) status=MagickFalse; destination_pixels=GetCacheViewAuthenticPixels(destination->view, destination->extent.x,y,destination->extent.width,1, destination->exception); for (x=0; x < (ssize_t) destination->extent.width; x++) { PixelGetQuantumPixel(destination->image,destination->pixel_wands[id][x], destination_pixels); destination_pixels+=GetPixelChannels(destination->image); } sync=SyncCacheViewAuthenticPixels(destination->view,destination->exception); if (sync == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickWand_TransferWandViewIterator) #endif proceed=SetImageProgress(source_image,source->description,progress++, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U p d a t e W a n d V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UpdateWandViewIterator() iterates over the wand view in parallel and calls % your update method for each scanline of the view. The pixel extent is % confined to the image canvas-- that is no negative offsets or widths or % heights that exceed the image dimension are permitted. Updates to pixels % in your callback are automagically synced back to the image. % % The callback signature is: % % MagickBooleanType UpdateImageViewMethod(WandView *source,const ssize_t y, % const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback update method that must be % executed by a single thread at a time. % % The format of the UpdateWandViewIterator method is: % % MagickBooleanType UpdateWandViewIterator(WandView *source, % UpdateWandViewMethod update,void *context) % % A description of each parameter follows: % % o source: the source wand view. % % o update: the update callback method. % % o context: the user defined context. % */ WandExport MagickBooleanType UpdateWandViewIterator(WandView *source, UpdateWandViewMethod update,void *context) { Image *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (WandView *) NULL); assert(source->signature == MagickWandSignature); if (update == (UpdateWandViewMethod) NULL) return(MagickFalse); source_image=source->wand->images; status=SetImageStorageClass(source_image,DirectClass,source->exception); if (status == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=source->extent.height-source->extent.y; #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(source_image,source_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register ssize_t x; register Quantum *magick_restrict pixels; if (status == MagickFalse) continue; pixels=GetCacheViewAuthenticPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source->extent.width; x++) { PixelSetQuantumPixel(source->image,pixels,source->pixel_wands[id][x]); pixels+=GetPixelChannels(source->image); } if (update(source,y,id,context) == MagickFalse) status=MagickFalse; for (x=0; x < (ssize_t) source->extent.width; x++) { PixelGetQuantumPixel(source->image,source->pixel_wands[id][x],pixels); pixels+=GetPixelChannels(source->image); } sync=SyncCacheViewAuthenticPixels(source->view,source->exception); if (sync == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickWand_UpdateWandViewIterator) #endif proceed=SetImageProgress(source_image,source->description,progress++, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); }
ellipticSchwarzSolverHex3D.c
extern "C" void preFDM(const dlong& Nelements, const pfloat* __restrict__ u, pfloat* __restrict__ work1) { #define getIdx(k,j,i,e) ((k)*p_Nq_e*p_Nq_e+(j)*p_Nq_e+(i)+(e)*p_Nq_e*p_Nq_e*p_Nq_e) #define getIdx2(k,j,i,e) ((k-1)*p_Nq*p_Nq+(j-1)*p_Nq+(i-1)+(e)*p_Nq*p_Nq*p_Nq) #define sWork1(k,j,i,e) (work1[(getIdx(k,j,i,e))]) #define uArr(k,j,i,e) (u[(getIdx2(k,j,i,e))]) #pragma omp parallel for for (dlong elem = 0; elem < Nelements; elem++) { #pragma unroll for(int k = 0; k < p_Nq_e; ++k){ #pragma unroll for(int j = 0; j < p_Nq_e; ++j){ #pragma unroll for(int i = 0; i < p_Nq_e; ++i){ const bool iBound = i>=1 && i <(p_Nq_e-1); const bool jBound = j>=1 && j <(p_Nq_e-1); const bool kBound = k>=1 && k <(p_Nq_e-1); if(iBound && jBound && kBound){ const dlong elem_offset = elem * p_Nq * p_Nq * p_Nq; const dlong idx = i + j * p_Nq + k * p_Nq * p_Nq + elem_offset; sWork1(k,j,i,elem) = uArr(k,j,i,elem); } else { sWork1(k,j,i,elem) = 0.0; } } } } #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 2; sWork1(l1,j,k,elem) = uArr(l2,j,k,elem); } } #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 2; sWork1(p_Nq_e - l1 - 1,j,k,elem) = uArr(p_Nq_e - l2 - 1,j,k,elem); } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 2; sWork1(i,l1,k,elem) = uArr(i,l2,k,elem); } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 2; sWork1(i,p_Nq_e - l1 - 1,k,elem) = uArr(i,p_Nq_e - l2 - 1,k,elem); } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ const int l1 = 0; const int l2 = 2; sWork1(i,j,l1,elem) = uArr(i,j,l2,elem); } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ const int l1 = 0; const int l2 = 2; sWork1(i,j,p_Nq_e - l1 - 1,elem) = uArr(i,j,p_Nq_e - l2 - 1,elem); } } } #undef getIdx #undef getIdx2 #undef sWork1 #undef uArr } extern "C" void postFDM(const dlong& Nelements, pfloat* __restrict__ my_work1, pfloat* __restrict__ my_work2, pfloat* __restrict__ Su, const pfloat* __restrict__ wts) { pfloat work1[p_Nq_e][p_Nq_e][p_Nq_e]; pfloat work2[p_Nq_e][p_Nq_e][p_Nq_e]; for (dlong elem = 0; elem < Nelements; ++elem) { #pragma unroll for(int k = 0; k < p_Nq_e; ++k){ #pragma unroll for(int j = 0; j < p_Nq_e; ++j){ #pragma unroll for(int i = 0; i < p_Nq_e; ++i) { const dlong elem_offset = elem * p_Nq_e * p_Nq_e * p_Nq_e; const dlong idx = i + j * p_Nq_e + k * p_Nq_e * p_Nq_e + elem_offset; work1[k][j][i] = my_work2[idx]; work2[k][j][i] = my_work1[idx]; } } } #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 0; work1[l1][j][k] = work1[l1][j][k] - work2[l2][j][k]; } } #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 0; work1[p_Nq_e - l1 - 1][j][k] = work1[p_Nq_e - l1 - 1][j][k] - work2[p_Nq_e - l2 - 1][j][k]; } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 0; work1[i][l1][k] = work1[i][l1][k] - work2[i][l2][k]; } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 0; work1[i][p_Nq_e - l1 - 1][k] = work1[i][p_Nq_e - l1 - 1][k] - work2[i][p_Nq_e - l2 - 1][k]; } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ const int l1 = 0; const int l2 = 0; work1[i][j][l1] = work1[i][j][l1] - work2[i][j][l2]; } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ const int l1 = 0; const int l2 = 0; work1[i][j][p_Nq_e - l1 - 1] = work1[i][j][p_Nq_e - l1 - 1] - work2[i][j][p_Nq_e - l2 - 1]; } } #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 2; const int l2 = 0; work1[l1][j][k] = work1[l1][j][k] + work1[l2][j][k]; } } #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 2; const int l2 = 0; work1[p_Nq_e - l1 - 1][j][k] = work1[p_Nq_e - l1 - 1][j][k] + work1[p_Nq_e - l2 - 1][j][k]; } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 2; const int l2 = 0; work1[i][l1][k] = work1[i][l1][k] + work1[i][l2][k]; } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 2; const int l2 = 0; work1[i][p_Nq_e - l1 - 1][k] = work1[i][p_Nq_e - l1 - 1][k] + work1[i][p_Nq_e - l2 - 1][k]; } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ const int l1 = 2; const int l2 = 0; work1[i][j][l1] = work1[i][j][l1] + work1[i][j][l2]; } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ const int l1 = 2; const int l2 = 0; work1[i][j][p_Nq_e - l1 - 1] = work1[i][j][p_Nq_e - l1 - 1] + work1[i][j][p_Nq_e - l2 - 1]; } } #pragma unroll for(int k = 0; k < p_Nq; ++k){ #pragma unroll for(int j = 0; j < p_Nq; ++j){ #pragma unroll for(int i = 0; i < p_Nq; ++i){ const dlong elem_offset = elem * p_Nq * p_Nq * p_Nq; const dlong idx = i + j * p_Nq + k * p_Nq * p_Nq + elem_offset; Su[idx] = work1[k + 1][j + 1][i + 1] * wts[idx]; } } } } } extern "C" void fusedFDM( const dlong& Nelements, const dlong& localNelements, const dlong* __restrict__ elementList, pfloat* __restrict__ Su, const pfloat* __restrict__ S_x, const pfloat* __restrict__ S_y, const pfloat* __restrict__ S_z, const pfloat* __restrict__ inv_L, #if p_restrict const dfloat* __restrict__ wts, #endif pfloat* __restrict__ u ) { #define getIdx(k,j,i,e) ((k)*p_Nq_e*p_Nq_e+(j)*p_Nq_e+(i)+(e)*p_Nq_e*p_Nq_e*p_Nq_e) #define work1(k,j,i,e) (u[(getIdx(k,j,i,e))]) pfloat S_x_e[p_Nq_e][p_Nq_e]; pfloat S_y_e[p_Nq_e][p_Nq_e]; pfloat S_z_e[p_Nq_e][p_Nq_e]; pfloat S_x_eT[p_Nq_e][p_Nq_e]; pfloat S_y_eT[p_Nq_e][p_Nq_e]; pfloat S_z_eT[p_Nq_e][p_Nq_e]; pfloat tmp[p_Nq_e][p_Nq_e][p_Nq_e]; pfloat work2[p_Nq_e][p_Nq_e][p_Nq_e]; for (dlong my_elem = 0; my_elem < Nelements; ++my_elem) { const dlong element = my_elem; const dlong elem = element; #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 2; work1(l1,j,k,elem) = work1(l1,j,k,elem) - work1(l2,j,k,elem); } } #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 2; work1(p_Nq_e - l1 - 1,j,k,elem) = work1(p_Nq_e - l1 - 1,j,k,elem) - work1(p_Nq_e - l2 - 1,j,k,elem); } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 2; work1(i,l1,k,elem) = work1(i,l1,k,elem) - work1(i,l2,k,elem); } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 2; work1(i,p_Nq_e - l1 - 1,k,elem) = work1(i,p_Nq_e - l1 - 1,k,elem) - work1(i,p_Nq_e - l2 - 1,k,elem); } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ const int l1 = 0; const int l2 = 2; work1(i,j,l1,elem) = work1(i,j,l1,elem) - work1(i,j,l2,elem); } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ const int l1 = 0; const int l2 = 2; work1(i,j,p_Nq_e - l1 - 1,elem) = work1(i,j,p_Nq_e - l1 - 1,elem) - work1(i,j,p_Nq_e - l2 - 1,elem); } } #pragma unroll for (int i = 0; i < p_Nq_e; i++){ #pragma unroll for (int j = 0; j < p_Nq_e; j++) { const int ij = j + i * p_Nq_e; S_x_e[i][j] = S_x[ij + element * p_Nq_e * p_Nq_e]; S_y_e[i][j] = S_y[ij + element * p_Nq_e * p_Nq_e]; S_z_e[i][j] = S_z[ij + element * p_Nq_e * p_Nq_e]; S_x_eT[j][i] = S_x_e[i][j]; S_y_eT[j][i] = S_y_e[i][j]; S_z_eT[j][i] = S_z_e[i][j]; } } #pragma unroll for (int k = 0; k < p_Nq_e; k++) { #pragma unroll for (int j = 0; j < p_Nq_e; j++) { #pragma unroll for (int i = 0; i < p_Nq_e; i++) { pfloat value = 0.0; #pragma unroll for (int l = 0; l < p_Nq_e; l++) value += S_x_e[l][j] * work1(k,i,l,elem); work2[k][i][j] = value; } } } #pragma unroll for (int k = 0; k < p_Nq_e; k++) { #pragma unroll for (int j = 0; j < p_Nq_e; j++) { #pragma unroll for (int i = 0; i < p_Nq_e; i++) { pfloat value = 0.0; #pragma unroll for (int l = 0; l < p_Nq_e; l++) value += S_y_e[l][j] * work2[k][l][i]; //work1(j,i,k,elem) = value; tmp[j][k][i] = value; } } } #pragma unroll for (int k = 0; k < p_Nq_e; k++) { #pragma unroll for (int j = 0; j < p_Nq_e; j++) { #pragma unroll for (int i = 0; i < p_Nq_e; i++) { const int v = i + j * p_Nq_e + k * p_Nq_e * p_Nq_e; pfloat value = 0.0; #pragma unroll for (int l = 0; l < p_Nq_e; l++) value += S_z_e[l][k] * tmp[j][l][i]; work2[k][i][j] = value * inv_L[v + element * p_Nq_e * p_Nq_e * p_Nq_e]; } } } #pragma unroll for (int k = 0; k < p_Nq_e; k++) { #pragma unroll for (int j = 0; j < p_Nq_e; j++) { #pragma unroll for (int i = 0; i < p_Nq_e; i++) { pfloat value = 0.0; #pragma unroll for (int l = 0; l < p_Nq_e; l++) value += S_x_eT[l][i] * work2[k][l][j]; tmp[k][j][i] = value; } } } #pragma unroll for (int k = 0; k < p_Nq_e; k++) { #pragma unroll for (int j = 0; j < p_Nq_e; j++) { #pragma unroll for (int i = 0; i < p_Nq_e; i++) { pfloat value = 0.0; #pragma unroll for (int l = 0; l < p_Nq_e; l++) value += S_y_eT[l][j] * tmp[k][l][i]; work2[j][k][i] = value; } } } #pragma unroll for (int k = 0; k < p_Nq_e; k++) { #pragma unroll for (int j = 0; j < p_Nq_e; j++) { #pragma unroll for (int i = 0; i < p_Nq_e; i++) { pfloat value = 0.0; #pragma unroll for (int l = 0; l < p_Nq_e; l++) value += S_z_eT[l][k] * work2[j][l][i]; #if (!p_restrict) const dlong elem_offset = element * p_Nq_e * p_Nq_e * p_Nq_e; const int v = i + j * p_Nq_e + k * p_Nq_e * p_Nq_e + elem_offset; Su[v] = value; #endif tmp[k][j][i] = value; } } } #if (!p_restrict) #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ const int l1 = 0; const int l2 = 0; work2[l1][j][k] = tmp[l2][j][k]; work2[p_Nq_e - l1 - 1][j][k] = tmp[p_Nq_e - l2 - 1][j][k]; } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 0; work2[i][l1][k] = tmp[i][l2][k]; } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 0; work2[i][p_Nq_e - l1 - 1][k] = tmp[i][p_Nq_e - l2 - 1][k]; } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ const int l1 = 0; const int l2 = 0; work2[i][j][l1] = tmp[i][j][l2]; } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ const int l1 = 0; const int l2 = 0; work2[i][j][p_Nq_e - l1 - 1] = tmp[i][j][p_Nq_e - l2 - 1]; } } #pragma unroll for(int k = 0; k < p_Nq_e; ++k){ #pragma unroll for(int j = 0; j < p_Nq_e; ++j){ #pragma unroll for(int i = 0; i < p_Nq_e; ++i) { const dlong elem_offset = element * p_Nq_e * p_Nq_e * p_Nq_e; const dlong idx = i + j * p_Nq_e + k * p_Nq_e * p_Nq_e + elem_offset; u[idx] = work2[k][j][i]; } } } #else /* if (!p_restrict) */ #pragma unroll for(int k = 0; k < p_Nq; ++k){ #pragma unroll for(int j = 0; j < p_Nq; ++j){ #pragma unroll for(int i = 0; i < p_Nq; ++i){ const dlong elem_offset = element * p_Nq * p_Nq * p_Nq; const dlong idx = i + j * p_Nq + k * p_Nq * p_Nq + elem_offset; Su[idx] = tmp[k + 1][j + 1][i + 1] * wts[idx]; } } } #endif } #undef getIdx #undef work1 }
tinyexr.h
#ifndef TINYEXR_H_ #define TINYEXR_H_ /* Copyright (c) 2014 - 2020, Syoyo Fujita and many contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Syoyo Fujita nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // TinyEXR contains some OpenEXR code, which is licensed under ------------ /////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// // End of OpenEXR license ------------------------------------------------- // // // Do this: // #define TINYEXR_IMPLEMENTATION // before you include this file in *one* C or C++ file to create the // implementation. // // // i.e. it should look like this: // #include ... // #include ... // #include ... // #define TINYEXR_IMPLEMENTATION // #include "tinyexr.h" // // #include <stddef.h> // for size_t #include <stdint.h> // guess stdint.h is available(C99) #ifdef __cplusplus extern "C" { #endif // Use embedded miniz or not to decode ZIP format pixel. Linking with zlib // required if this flas is 0. #ifndef TINYEXR_USE_MINIZ #define TINYEXR_USE_MINIZ (1) #endif // Disable PIZ comporession when applying cpplint. #ifndef TINYEXR_USE_PIZ #define TINYEXR_USE_PIZ (1) #endif #ifndef TINYEXR_USE_ZFP #define TINYEXR_USE_ZFP (0) // TinyEXR extension. // http://computation.llnl.gov/projects/floating-point-compression #endif #ifndef TINYEXR_USE_THREAD #define TINYEXR_USE_THREAD (0) // No threaded loading. // http://computation.llnl.gov/projects/floating-point-compression #endif #ifndef TINYEXR_USE_OPENMP #ifdef _OPENMP #define TINYEXR_USE_OPENMP (1) #else #define TINYEXR_USE_OPENMP (0) #endif #endif #define TINYEXR_SUCCESS (0) #define TINYEXR_ERROR_INVALID_MAGIC_NUMBER (-1) #define TINYEXR_ERROR_INVALID_EXR_VERSION (-2) #define TINYEXR_ERROR_INVALID_ARGUMENT (-3) #define TINYEXR_ERROR_INVALID_DATA (-4) #define TINYEXR_ERROR_INVALID_FILE (-5) #define TINYEXR_ERROR_INVALID_PARAMETER (-6) #define TINYEXR_ERROR_CANT_OPEN_FILE (-7) #define TINYEXR_ERROR_UNSUPPORTED_FORMAT (-8) #define TINYEXR_ERROR_INVALID_HEADER (-9) #define TINYEXR_ERROR_UNSUPPORTED_FEATURE (-10) #define TINYEXR_ERROR_CANT_WRITE_FILE (-11) #define TINYEXR_ERROR_SERIALZATION_FAILED (-12) #define TINYEXR_ERROR_LAYER_NOT_FOUND (-13) // @note { OpenEXR file format: http://www.openexr.com/openexrfilelayout.pdf } // pixel type: possible values are: UINT = 0 HALF = 1 FLOAT = 2 #define TINYEXR_PIXELTYPE_UINT (0) #define TINYEXR_PIXELTYPE_HALF (1) #define TINYEXR_PIXELTYPE_FLOAT (2) #define TINYEXR_MAX_HEADER_ATTRIBUTES (1024) #define TINYEXR_MAX_CUSTOM_ATTRIBUTES (128) #define TINYEXR_COMPRESSIONTYPE_NONE (0) #define TINYEXR_COMPRESSIONTYPE_RLE (1) #define TINYEXR_COMPRESSIONTYPE_ZIPS (2) #define TINYEXR_COMPRESSIONTYPE_ZIP (3) #define TINYEXR_COMPRESSIONTYPE_PIZ (4) #define TINYEXR_COMPRESSIONTYPE_ZFP (128) // TinyEXR extension #define TINYEXR_ZFP_COMPRESSIONTYPE_RATE (0) #define TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION (1) #define TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY (2) #define TINYEXR_TILE_ONE_LEVEL (0) #define TINYEXR_TILE_MIPMAP_LEVELS (1) #define TINYEXR_TILE_RIPMAP_LEVELS (2) #define TINYEXR_TILE_ROUND_DOWN (0) #define TINYEXR_TILE_ROUND_UP (1) typedef struct _EXRVersion { int version; // this must be 2 // tile format image; // not zero for only a single-part "normal" tiled file (according to spec.) int tiled; int long_name; // long name attribute // deep image(EXR 2.0); // for a multi-part file, indicates that at least one part is of type deep* (according to spec.) int non_image; int multipart; // multi-part(EXR 2.0) } EXRVersion; typedef struct _EXRAttribute { char name[256]; // name and type are up to 255 chars long. char type[256]; unsigned char *value; // uint8_t* int size; int pad0; } EXRAttribute; typedef struct _EXRChannelInfo { char name[256]; // less than 255 bytes long int pixel_type; int x_sampling; int y_sampling; unsigned char p_linear; unsigned char pad[3]; } EXRChannelInfo; typedef struct _EXRTile { int offset_x; int offset_y; int level_x; int level_y; int width; // actual width in a tile. int height; // actual height int a tile. unsigned char **images; // image[channels][pixels] } EXRTile; typedef struct _EXRBox2i { int min_x; int min_y; int max_x; int max_y; } EXRBox2i; typedef struct _EXRHeader { float pixel_aspect_ratio; int line_order; EXRBox2i data_window; EXRBox2i display_window; float screen_window_center[2]; float screen_window_width; int chunk_count; // Properties for tiled format(`tiledesc`). int tiled; int tile_size_x; int tile_size_y; int tile_level_mode; int tile_rounding_mode; int long_name; // for a single-part file, agree with the version field bit 11 // for a multi-part file, it is consistent with the type of part int non_image; int multipart; unsigned int header_len; // Custom attributes(exludes required attributes(e.g. `channels`, // `compression`, etc) int num_custom_attributes; EXRAttribute *custom_attributes; // array of EXRAttribute. size = // `num_custom_attributes`. EXRChannelInfo *channels; // [num_channels] int *pixel_types; // Loaded pixel type(TINYEXR_PIXELTYPE_*) of `images` for // each channel. This is overwritten with `requested_pixel_types` when // loading. int num_channels; int compression_type; // compression type(TINYEXR_COMPRESSIONTYPE_*) int *requested_pixel_types; // Filled initially by // ParseEXRHeaderFrom(Meomory|File), then users // can edit it(only valid for HALF pixel type // channel) // name attribute required for multipart files; // must be unique and non empty (according to spec.); // use EXRSetNameAttr for setting value; // max 255 character allowed - excluding terminating zero char name[256]; } EXRHeader; typedef struct _EXRMultiPartHeader { int num_headers; EXRHeader *headers; } EXRMultiPartHeader; typedef struct _EXRImage { EXRTile *tiles; // Tiled pixel data. The application must reconstruct image // from tiles manually. NULL if scanline format. struct _EXRImage* next_level; // NULL if scanline format or image is the last level. int level_x; // x level index int level_y; // y level index unsigned char **images; // image[channels][pixels]. NULL if tiled format. int width; int height; int num_channels; // Properties for tile format. int num_tiles; } EXRImage; typedef struct _EXRMultiPartImage { int num_images; EXRImage *images; } EXRMultiPartImage; typedef struct _DeepImage { const char **channel_names; float ***image; // image[channels][scanlines][samples] int **offset_table; // offset_table[scanline][offsets] int num_channels; int width; int height; int pad0; } DeepImage; // @deprecated { For backward compatibility. Not recommended to use. } // Loads single-frame OpenEXR image. Assume EXR image contains A(single channel // alpha) or RGB(A) channels. // Application must free image data as returned by `out_rgba` // Result image format is: float x RGBA x width x hight // Returns negative value and may set error string in `err` when there's an // error extern int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err); // Loads single-frame OpenEXR image by specifying layer name. Assume EXR image // contains A(single channel alpha) or RGB(A) channels. Application must free // image data as returned by `out_rgba` Result image format is: float x RGBA x // width x hight Returns negative value and may set error string in `err` when // there's an error When the specified layer name is not found in the EXR file, // the function will return `TINYEXR_ERROR_LAYER_NOT_FOUND`. extern int LoadEXRWithLayer(float **out_rgba, int *width, int *height, const char *filename, const char *layer_name, const char **err); // // Get layer infos from EXR file. // // @param[out] layer_names List of layer names. Application must free memory // after using this. // @param[out] num_layers The number of layers // @param[out] err Error string(will be filled when the function returns error // code). Free it using FreeEXRErrorMessage after using this value. // // @return TINYEXR_SUCCEES upon success. // extern int EXRLayers(const char *filename, const char **layer_names[], int *num_layers, const char **err); // @deprecated { to be removed. } // Simple wrapper API for ParseEXRHeaderFromFile. // checking given file is a EXR file(by just look up header) // @return TINYEXR_SUCCEES for EXR image, TINYEXR_ERROR_INVALID_HEADER for // others extern int IsEXR(const char *filename); // @deprecated { to be removed. } // Saves single-frame OpenEXR image. Assume EXR image contains RGB(A) channels. // components must be 1(Grayscale), 3(RGB) or 4(RGBA). // Input image format is: `float x width x height`, or `float x RGB(A) x width x // hight` // Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero // value. // Save image as fp32(FLOAT) format when `save_as_fp16` is 0. // Use ZIP compression by default. // Returns negative value and may set error string in `err` when there's an // error extern int SaveEXR(const float *data, const int width, const int height, const int components, const int save_as_fp16, const char *filename, const char **err); // Returns the number of resolution levels of the image (including the base) extern int EXRNumLevels(const EXRImage* exr_image); // Initialize EXRHeader struct extern void InitEXRHeader(EXRHeader *exr_header); // Set name attribute of EXRHeader struct (it makes a copy) extern void EXRSetNameAttr(EXRHeader *exr_header, const char* name); // Initialize EXRImage struct extern void InitEXRImage(EXRImage *exr_image); // Frees internal data of EXRHeader struct extern int FreeEXRHeader(EXRHeader *exr_header); // Frees internal data of EXRImage struct extern int FreeEXRImage(EXRImage *exr_image); // Frees error message extern void FreeEXRErrorMessage(const char *msg); // Parse EXR version header of a file. extern int ParseEXRVersionFromFile(EXRVersion *version, const char *filename); // Parse EXR version header from memory-mapped EXR data. extern int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory, size_t size); // Parse single-part OpenEXR header from a file and initialize `EXRHeader`. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRHeaderFromFile(EXRHeader *header, const EXRVersion *version, const char *filename, const char **err); // Parse single-part OpenEXR header from a memory and initialize `EXRHeader`. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRHeaderFromMemory(EXRHeader *header, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err); // Parse multi-part OpenEXR headers from a file and initialize `EXRHeader*` // array. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRMultipartHeaderFromFile(EXRHeader ***headers, int *num_headers, const EXRVersion *version, const char *filename, const char **err); // Parse multi-part OpenEXR headers from a memory and initialize `EXRHeader*` // array // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRMultipartHeaderFromMemory(EXRHeader ***headers, int *num_headers, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err); // Loads single-part OpenEXR image from a file. // Application must setup `ParseEXRHeaderFromFile` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRImageFromFile(EXRImage *image, const EXRHeader *header, const char *filename, const char **err); // Loads single-part OpenEXR image from a memory. // Application must setup `EXRHeader` with // `ParseEXRHeaderFromMemory` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRImageFromMemory(EXRImage *image, const EXRHeader *header, const unsigned char *memory, const size_t size, const char **err); // Loads multi-part OpenEXR image from a file. // Application must setup `ParseEXRMultipartHeaderFromFile` before calling this // function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRMultipartImageFromFile(EXRImage *images, const EXRHeader **headers, unsigned int num_parts, const char *filename, const char **err); // Loads multi-part OpenEXR image from a memory. // Application must setup `EXRHeader*` array with // `ParseEXRMultipartHeaderFromMemory` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRMultipartImageFromMemory(EXRImage *images, const EXRHeader **headers, unsigned int num_parts, const unsigned char *memory, const size_t size, const char **err); // Saves multi-channel, single-frame OpenEXR image to a file. // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int SaveEXRImageToFile(const EXRImage *image, const EXRHeader *exr_header, const char *filename, const char **err); // Saves multi-channel, single-frame OpenEXR image to a memory. // Image is compressed using EXRImage.compression value. // Return the number of bytes if success. // Return zero and will set error string in `err` when there's an // error. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern size_t SaveEXRImageToMemory(const EXRImage *image, const EXRHeader *exr_header, unsigned char **memory, const char **err); // Saves multi-channel, multi-frame OpenEXR image to a memory. // Image is compressed using EXRImage.compression value. // File global attributes (eg. display_window) must be set in the first header. // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int SaveEXRMultipartImageToFile(const EXRImage *images, const EXRHeader **exr_headers, unsigned int num_parts, const char *filename, const char **err); // Saves multi-channel, multi-frame OpenEXR image to a memory. // Image is compressed using EXRImage.compression value. // File global attributes (eg. display_window) must be set in the first header. // Return the number of bytes if success. // Return zero and will set error string in `err` when there's an // error. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern size_t SaveEXRMultipartImageToMemory(const EXRImage *images, const EXRHeader **exr_headers, unsigned int num_parts, unsigned char **memory, const char **err); // Loads single-frame OpenEXR deep image. // Application must free memory of variables in DeepImage(image, offset_table) // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadDeepEXR(DeepImage *out_image, const char *filename, const char **err); // NOT YET IMPLEMENTED: // Saves single-frame OpenEXR deep image. // Returns negative value and may set error string in `err` when there's an // error // extern int SaveDeepEXR(const DeepImage *in_image, const char *filename, // const char **err); // NOT YET IMPLEMENTED: // Loads multi-part OpenEXR deep image. // Application must free memory of variables in DeepImage(image, offset_table) // extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const // char *filename, // const char **err); // For emscripten. // Loads single-frame OpenEXR image from memory. Assume EXR image contains // RGB(A) channels. // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRFromMemory(float **out_rgba, int *width, int *height, const unsigned char *memory, size_t size, const char **err); #ifdef __cplusplus } #endif #endif // TINYEXR_H_ #ifdef TINYEXR_IMPLEMENTATION #ifndef TINYEXR_IMPLEMENTATION_DEFINED #define TINYEXR_IMPLEMENTATION_DEFINED #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef NOMINMAX #define NOMINMAX #endif #include <windows.h> // for UTF-8 #endif #include <algorithm> #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <sstream> // #include <iostream> // debug #include <limits> #include <string> #include <vector> #include <set> // https://stackoverflow.com/questions/5047971/how-do-i-check-for-c11-support #if __cplusplus > 199711L || (defined(_MSC_VER) && _MSC_VER >= 1900) #define TINYEXR_HAS_CXX11 (1) // C++11 #include <cstdint> #if TINYEXR_USE_THREAD #include <atomic> #include <thread> #endif #endif // __cplusplus > 199711L #if TINYEXR_USE_OPENMP #include <omp.h> #endif #if TINYEXR_USE_MINIZ #else // Issue #46. Please include your own zlib-compatible API header before // including `tinyexr.h` //#include "zlib.h" #endif #if TINYEXR_USE_ZFP #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Weverything" #endif #include "zfp.h" #ifdef __clang__ #pragma clang diagnostic pop #endif #endif namespace tinyexr { #if __cplusplus > 199711L // C++11 typedef uint64_t tinyexr_uint64; typedef int64_t tinyexr_int64; #else // Although `long long` is not a standard type pre C++11, assume it is defined // as a compiler's extension. #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #endif typedef unsigned long long tinyexr_uint64; typedef long long tinyexr_int64; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif #if TINYEXR_USE_MINIZ namespace miniz { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wc++11-extensions" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wunused-function" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #pragma clang diagnostic ignored "-Wundef" #if __has_warning("-Wcomma") #pragma clang diagnostic ignored "-Wcomma" #endif #if __has_warning("-Wmacro-redefined") #pragma clang diagnostic ignored "-Wmacro-redefined" #endif #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #if __has_warning("-Wtautological-constant-compare") #pragma clang diagnostic ignored "-Wtautological-constant-compare" #endif #if __has_warning("-Wextra-semi-stmt") #pragma clang diagnostic ignored "-Wextra-semi-stmt" #endif #endif /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing See "unlicense" statement at the end of this file. Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). * Change History 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!): - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug would only have occurred in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place() (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag). - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries. Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice). - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti - Merged MZ_FORCEINLINE fix from hdeanclark - Fix <time.h> include before config #ifdef, thanks emil.brink - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can set it to 1 for real-time compression). - Merged in some compiler fixes from paulharris's github repro. - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3. - Added example6.c, which dumps an image of the mandelbrot set to a PNG file. - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more. - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect). 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <bruced@valvesoftware.com> for the feedback/bug report. 5/28/11 v1.11 - Added statement from unlicense.org 5/27/11 v1.10 - Substantial compressor optimizations: - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. - Refactored the compression code for better readability and maintainability. - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large drop in throughput on some files). 5/15/11 v1.09 - Initial stable release. * Low-level Deflate/Inflate implementation notes: Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses approximately as well as zlib. Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory block large enough to hold the entire file. The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. * zlib-style API notes: miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in zlib replacement in many apps: The z_stream struct, optional memory allocation callbacks deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound inflateInit/inflateInit2/inflate/inflateEnd compress, compress2, compressBound, uncompress CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. Supports raw deflate streams or standard zlib streams with adler-32 checking. Limitations: The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but there are no guarantees that miniz.c pulls this off perfectly. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by Alex Evans. Supports 1-4 bytes/pixel images. * ZIP archive API notes: The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to get the job done with minimal fuss. There are simple API's to retrieve file information, read files from existing archives, create new archives, append new files to existing archives, or clone archive data from one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), or you can specify custom file read/write callbacks. - Archive reading: Just call this function to read a single file from a disk archive: void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); The locate operation can optionally check file comments too, which (as one example) can be used to identify multiple versions of the same file in an archive. This function uses a simple linear search through the central directory, so it's not very fast. Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and retrieve detailed info on each file by calling mz_zip_reader_file_stat(). - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data to disk and builds an exact image of the central directory in memory. The central directory image is written all at once at the end of the archive file when the archive is finalized. The archive writer can optionally align each file's local header and file data to any power of 2 alignment, which can be useful when the archive will be read from optical media. Also, the writer supports placing arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still readable by any ZIP tool. - Archive appending: The simple way to add a single file to an archive is to call this function: mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); The archive will be created if it doesn't already exist, otherwise it'll be appended to. Note the appending is done in-place and is not an atomic operation, so if something goes wrong during the operation it's possible the archive could be left without a central directory (although the local file headers and file data will be fine, so the archive will be recoverable). For more complex archive modification scenarios: 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and you're done. This is safe but requires a bunch of temporary disk space or heap memory. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), append new files as needed, then finalize the archive which will write an updated central directory to the original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a possibility that the archive's central directory could be lost with this method if anything goes wrong, though. - ZIP archive support limitations: No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. Requires streams capable of seeking. * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. * Important: For best perf. be sure to customize the below macros for your target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1 * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). */ #ifndef MINIZ_HEADER_INCLUDED #define MINIZ_HEADER_INCLUDED //#include <stdlib.h> // Defines to completely disable specific portions of miniz.c: // If all macros here are defined the only functionality remaining will be // CRC-32, adler-32, tinfl, and tdefl. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on // stdio for file I/O. //#define MINIZ_NO_STDIO // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able // to get the current time, or // get/set file times, and the C run-time funcs that get/set times won't be // called. // The current downside is the times written to your archives will be from 1979. #define MINIZ_NO_TIME // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. #define MINIZ_NO_ARCHIVE_APIS // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive // API's. //#define MINIZ_NO_ARCHIVE_WRITING_APIS // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression // API's. //#define MINIZ_NO_ZLIB_APIS // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent // conflicts against stock zlib. //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom // user alloc/free/realloc // callbacks to the zlib and archive API's, and a few stand-alone helper API's // which don't provide custom user // functions (such as tdefl_compress_mem_to_heap() and // tinfl_decompress_mem_to_heap()) won't work. //#define MINIZ_NO_MALLOC #if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc // on Linux #define MINIZ_NO_TIME #endif #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) //#include <time.h> #endif #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \ defined(__i386) || defined(__i486__) || defined(__i486) || \ defined(i386) || defined(__ia64__) || defined(__x86_64__) // MINIZ_X86_OR_X64_CPU is only used to help set the below macros. #define MINIZ_X86_OR_X64_CPU 1 #endif #if defined(__sparcv9) // Big endian #else #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #endif #if MINIZ_X86_OR_X64_CPU // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient // integer loads and stores from unaligned addresses. //#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES \ 0 // disable to suppress compiler warnings #endif #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \ defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \ defined(__x86_64__) // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are // reasonably fast (and don't involve compiler generated calls to helper // functions). #define MINIZ_HAS_64BIT_REGISTERS 1 #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API Definitions. // For more compatibility with zlib, miniz.c uses unsigned long for some // parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! typedef unsigned long mz_ulong; // mz_free() internally uses the MZ_FREE() macro (which by default calls free() // unless you've modified the MZ_MALLOC macro) to release a block allocated from // the heap. void mz_free(void *p); #define MZ_ADLER32_INIT (1) // mz_adler32() returns the initial adler-32 value to use when called with // ptr==NULL. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); #define MZ_CRC32_INIT (0) // mz_crc32() returns the initial CRC-32 value to use when called with // ptr==NULL. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); // Compression strategies. enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; // Method #define MZ_DEFLATED 8 #ifndef MINIZ_NO_ZLIB_APIS // Heap allocation callbacks. // Note that mz_alloc_func parameter types purpsosely differ from zlib's: // items/size is size_t, not unsigned long. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); typedef void (*mz_free_func)(void *opaque, void *address); typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); #define MZ_VERSION "9.1.15" #define MZ_VERNUM 0x91F0 #define MZ_VER_MAJOR 9 #define MZ_VER_MINOR 1 #define MZ_VER_REVISION 15 #define MZ_VER_SUBREVISION 0 // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The // other values are for advanced use (refer to the zlib docs). enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; // Return status codes. MZ_PARAM_ERROR is non-standard. enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; // Compression levels: 0-9 are the standard zlib-style levels, 10 is best // possible compression (not zlib compatible, and may be very slow), // MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; // Window bits #define MZ_DEFAULT_WINDOW_BITS 15 struct mz_internal_state; // Compression/decompression stream struct. typedef struct mz_stream_s { const unsigned char *next_in; // pointer to next byte to read unsigned int avail_in; // number of bytes available at next_in mz_ulong total_in; // total number of bytes consumed so far unsigned char *next_out; // pointer to next byte to write unsigned int avail_out; // number of bytes that can be written to next_out mz_ulong total_out; // total number of bytes produced so far char *msg; // error msg (unused) struct mz_internal_state *state; // internal state, allocated by zalloc/zfree mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) mz_free_func zfree; // optional heap free function (defaults to free) void *opaque; // heap alloc function user pointer int data_type; // data_type (unused) mz_ulong adler; // adler32 of the source or uncompressed data mz_ulong reserved; // not used } mz_stream; typedef mz_stream *mz_streamp; // Returns the version string of miniz.c. const char *mz_version(void); // mz_deflateInit() initializes a compressor with default options: // Parameters: // pStream must point to an initialized mz_stream struct. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. // level 1 enables a specially optimized compression function that's been // optimized purely for performance, not ratio. // (This special func. is currently only enabled when // MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if the input parameters are bogus. // MZ_MEM_ERROR on out of memory. int mz_deflateInit(mz_streamp pStream, int level); // mz_deflateInit2() is like mz_deflate(), except with more control: // Additional parameters: // method must be MZ_DEFLATED // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with // zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no // header or footer) // mem_level must be between [1, 9] (it's checked but ignored by miniz.c) int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); // Quickly resets a compressor without having to reallocate anything. Same as // calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). int mz_deflateReset(mz_streamp pStream); // mz_deflate() compresses the input to output, consuming as much of the input // and producing as much output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update // the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or // MZ_FINISH. // Return values: // MZ_OK on success (when flushing, or if more input is needed but not // available, and/or there's more output to be written but the output buffer // is full). // MZ_STREAM_END if all input has been consumed and all output bytes have been // written. Don't call mz_deflate() on the stream anymore. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input and/or // output buffers are empty. (Fill up the input buffer or free up some output // space and try again.) int mz_deflate(mz_streamp pStream, int flush); // mz_deflateEnd() deinitializes a compressor: // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. int mz_deflateEnd(mz_streamp pStream); // mz_deflateBound() returns a (very) conservative upper bound on the amount of // data that could be generated by deflate(), assuming flush is set to only // MZ_NO_FLUSH or MZ_FINISH. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); // Single-call compression functions mz_compress() and mz_compress2(): // Returns MZ_OK on success, or one of the error codes from mz_deflate() on // failure. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); // mz_compressBound() returns a (very) conservative upper bound on the amount of // data that could be generated by calling mz_compress(). mz_ulong mz_compressBound(mz_ulong source_len); // Initializes a decompressor. int mz_inflateInit(mz_streamp pStream); // mz_inflateInit2() is like mz_inflateInit() with an additional option that // controls the window size and whether or not the stream has been wrapped with // a zlib header/footer: // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or // -MZ_DEFAULT_WINDOW_BITS (raw deflate). int mz_inflateInit2(mz_streamp pStream, int window_bits); // Decompresses the input stream to the output, consuming only as much of the // input as needed, and writing as much to the output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update // the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. // On the first call, if flush is MZ_FINISH it's assumed the input and output // buffers are both sized large enough to decompress the entire stream in a // single call (this is slightly faster). // MZ_FINISH implies that there are no more source bytes available beside // what's already in the input buffer, and that the output buffer is large // enough to hold the rest of the decompressed data. // Return values: // MZ_OK on success. Either more input is needed but not available, and/or // there's more output to be written but the output buffer is full. // MZ_STREAM_END if all needed input has been consumed and all output bytes // have been written. For zlib streams, the adler-32 of the decompressed data // has also been verified. // MZ_STREAM_ERROR if the stream is bogus. // MZ_DATA_ERROR if the deflate stream is invalid. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input buffer is // empty but the inflater needs more input to continue, or if the output // buffer is not large enough. Call mz_inflate() again // with more input data, or with more room in the output buffer (except when // using single call decompression, described above). int mz_inflate(mz_streamp pStream, int flush); // Deinitializes a decompressor. int mz_inflateEnd(mz_streamp pStream); // Single-call decompression. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on // failure. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); // Returns a string description of the specified error code, or NULL if the // error code is invalid. const char *mz_error(int err); // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used // as a drop-in replacement for the subset of zlib that miniz.c supports. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you // use zlib in the same project. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES typedef unsigned char Byte; typedef unsigned int uInt; typedef mz_ulong uLong; typedef Byte Bytef; typedef uInt uIntf; typedef char charf; typedef int intf; typedef void *voidpf; typedef uLong uLongf; typedef void *voidp; typedef void *const voidpc; #define Z_NULL 0 #define Z_NO_FLUSH MZ_NO_FLUSH #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH #define Z_SYNC_FLUSH MZ_SYNC_FLUSH #define Z_FULL_FLUSH MZ_FULL_FLUSH #define Z_FINISH MZ_FINISH #define Z_BLOCK MZ_BLOCK #define Z_OK MZ_OK #define Z_STREAM_END MZ_STREAM_END #define Z_NEED_DICT MZ_NEED_DICT #define Z_ERRNO MZ_ERRNO #define Z_STREAM_ERROR MZ_STREAM_ERROR #define Z_DATA_ERROR MZ_DATA_ERROR #define Z_MEM_ERROR MZ_MEM_ERROR #define Z_BUF_ERROR MZ_BUF_ERROR #define Z_VERSION_ERROR MZ_VERSION_ERROR #define Z_PARAM_ERROR MZ_PARAM_ERROR #define Z_NO_COMPRESSION MZ_NO_COMPRESSION #define Z_BEST_SPEED MZ_BEST_SPEED #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY #define Z_FILTERED MZ_FILTERED #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY #define Z_RLE MZ_RLE #define Z_FIXED MZ_FIXED #define Z_DEFLATED MZ_DEFLATED #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS #define alloc_func mz_alloc_func #define free_func mz_free_func #define internal_state mz_internal_state #define z_stream mz_stream #define deflateInit mz_deflateInit #define deflateInit2 mz_deflateInit2 #define deflateReset mz_deflateReset #define deflate mz_deflate #define deflateEnd mz_deflateEnd #define deflateBound mz_deflateBound #define compress mz_compress #define compress2 mz_compress2 #define compressBound mz_compressBound #define inflateInit mz_inflateInit #define inflateInit2 mz_inflateInit2 #define inflate mz_inflate #define inflateEnd mz_inflateEnd #define uncompress mz_uncompress #define crc32 mz_crc32 #define adler32 mz_adler32 #define MAX_WBITS 15 #define MAX_MEM_LEVEL 9 #define zError mz_error #define ZLIB_VERSION MZ_VERSION #define ZLIB_VERNUM MZ_VERNUM #define ZLIB_VER_MAJOR MZ_VER_MAJOR #define ZLIB_VER_MINOR MZ_VER_MINOR #define ZLIB_VER_REVISION MZ_VER_REVISION #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION #define zlibVersion mz_version #define zlib_version mz_version() #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES #endif // MINIZ_NO_ZLIB_APIS // ------------------- Types and macros typedef unsigned char mz_uint8; typedef signed short mz_int16; typedef unsigned short mz_uint16; typedef unsigned int mz_uint32; typedef unsigned int mz_uint; typedef long long mz_int64; typedef unsigned long long mz_uint64; typedef int mz_bool; #define MZ_FALSE (0) #define MZ_TRUE (1) // An attempt to work around MSVC's spammy "warning C4127: conditional // expression is constant" message. #ifdef _MSC_VER #define MZ_MACRO_END while (0, 0) #else #define MZ_MACRO_END while (0) #endif // ------------------- ZIP archive reading/writing #ifndef MINIZ_NO_ARCHIVE_APIS enum { MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 }; typedef struct { mz_uint32 m_file_index; mz_uint32 m_central_dir_ofs; mz_uint16 m_version_made_by; mz_uint16 m_version_needed; mz_uint16 m_bit_flag; mz_uint16 m_method; #ifndef MINIZ_NO_TIME time_t m_time; #endif mz_uint32 m_crc32; mz_uint64 m_comp_size; mz_uint64 m_uncomp_size; mz_uint16 m_internal_attr; mz_uint32 m_external_attr; mz_uint64 m_local_header_ofs; mz_uint32 m_comment_size; char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; } mz_zip_archive_file_stat; typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); struct mz_zip_internal_state_tag; typedef struct mz_zip_internal_state_tag mz_zip_internal_state; typedef enum { MZ_ZIP_MODE_INVALID = 0, MZ_ZIP_MODE_READING = 1, MZ_ZIP_MODE_WRITING = 2, MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 } mz_zip_mode; typedef struct mz_zip_archive_tag { mz_uint64 m_archive_size; mz_uint64 m_central_directory_file_ofs; mz_uint m_total_files; mz_zip_mode m_zip_mode; mz_uint m_file_offset_alignment; mz_alloc_func m_pAlloc; mz_free_func m_pFree; mz_realloc_func m_pRealloc; void *m_pAlloc_opaque; mz_file_read_func m_pRead; mz_file_write_func m_pWrite; void *m_pIO_opaque; mz_zip_internal_state *m_pState; } mz_zip_archive; typedef enum { MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 } mz_zip_flags; // ZIP archive reading // Inits a ZIP archive reader. // These functions read and validate the archive's central directory. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); #endif // Returns the total number of files in the archive. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); // Returns detailed information about an archive file entry. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); // Determines if an archive file entry is a directory entry. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); // Retrieves the filename of an archive file entry. // Returns the number of bytes written to pFilename, or if filename_buf_size is // 0 this function returns the number of bytes needed to fully store the // filename. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); // Attempts to locates a file in the archive's central directory. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH // Returns -1 if the file cannot be found. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); // Extracts a archive file to a memory buffer using no memory allocation. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); // Extracts a archive file to a memory buffer. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); // Extracts a archive file to a dynamically allocated heap buffer. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); // Extracts a archive file using a callback function to output the file's data. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); #ifndef MINIZ_NO_STDIO // Extracts a archive file to a disk file and sets its last accessed and // modified times. // This function only extracts files, not archive directory records. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); #endif // Ends archive reading, freeing all allocations, and closing the input archive // file if mz_zip_reader_init_file() was used. mz_bool mz_zip_reader_end(mz_zip_archive *pZip); // ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS // Inits a ZIP archive writer. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); #endif // Converts a ZIP archive reader object into a writer object, to allow efficient // in-place file appends to occur on an existing archive. // For archives opened using mz_zip_reader_init_file, pFilename must be the // archive's filename so it can be reopened for writing. If the file can't be // reopened, mz_zip_reader_end() will be called. // For archives opened using mz_zip_reader_init_mem, the memory block must be // growable using the realloc callback (which defaults to realloc unless you've // overridden it). // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's // user provided m_pWrite function cannot be NULL. // Note: In-place archive modification is not recommended unless you know what // you're doing, because if execution stops or something goes wrong before // the archive is finalized the file's central directory will be hosed. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); // Adds the contents of a memory buffer to an archive. These functions record // the current local time into the archive. // To add a directory entry, call this method with an archive name ending in a // forwardslash with empty buffer. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); #ifndef MINIZ_NO_STDIO // Adds the contents of a disk file to an archive. This function also records // the disk file's modified time into the archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); #endif // Adds a file to an archive by fully cloning the data from another archive. // This function fully clones the source file's compressed data (no // recompression), along with its full filename, extra data, and comment fields. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); // Finalizes the archive by writing the central directory records followed by // the end of central directory record. // After an archive is finalized, the only valid call on the mz_zip_archive // struct is mz_zip_writer_end(). // An archive must be manually finalized by calling this function for it to be // valid. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); // Ends archive writing, freeing all allocations, and closing the output file if // mz_zip_writer_init_file() was used. // Note for the archive to be valid, it must have been finalized before ending. mz_bool mz_zip_writer_end(mz_zip_archive *pZip); // Misc. high-level helper functions: // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) // appends a memory blob to a ZIP archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_add_mem_to_archive_file_in_place( const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); // Reads a single file from an archive into a heap block. // Returns NULL on failure. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS // ------------------- Low-level Decompression API Definitions // Decompression flags used by tinfl_decompress(). // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and // ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the // input is a raw deflate stream. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available // beyond the end of the supplied input buffer. If clear, the input buffer // contains all remaining input. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large // enough to hold the entire decompressed stream. If clear, the output buffer is // at least the size of the dictionary (typically 32KB). // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the // decompressed bytes. enum { TINFL_FLAG_PARSE_ZLIB_HEADER = 1, TINFL_FLAG_HAS_MORE_INPUT = 2, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, TINFL_FLAG_COMPUTE_ADLER32 = 8 }; // High level decompression functions: // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block // allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data // to decompress. // On return: // Function returns a pointer to the decompressed data, or NULL on failure. // *pOut_len will be set to the decompressed data's size, which could be larger // than src_buf_len on uncompressible data. // The caller must call mz_free() on the returned block when it's no longer // needed. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block // in memory. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes // written on success. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // tinfl_decompress_mem_to_callback() decompresses a block in memory to an // internal 32KB buffer, and a user provided callback function will be called to // flush the buffer. // Returns 1 on success or 0 on failure. typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; // Max size of LZ dictionary. #define TINFL_LZ_DICT_SIZE 32768 // Return status. typedef enum { TINFL_STATUS_BAD_PARAM = -3, TINFL_STATUS_ADLER32_MISMATCH = -2, TINFL_STATUS_FAILED = -1, TINFL_STATUS_DONE = 0, TINFL_STATUS_NEEDS_MORE_INPUT = 1, TINFL_STATUS_HAS_MORE_OUTPUT = 2 } tinfl_status; // Initializes the decompressor to its initial state. #define tinfl_init(r) \ do { \ (r)->m_state = 0; \ } \ MZ_MACRO_END #define tinfl_get_adler32(r) (r)->m_check_adler32 // Main low-level decompressor coroutine function. This is the only function // actually needed for decompression. All the other functions are just // high-level helpers for improved usability. // This is a universal API, i.e. it can be used as a building block to build any // desired higher level decompression API. In the limit case, it can be called // once per every byte input or output. tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); // Internal/private bits follow. enum { TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS }; typedef struct { mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; } tinfl_huff_table; #if MINIZ_HAS_64BIT_REGISTERS #define TINFL_USE_64BIT_BITBUF 1 #endif #if TINFL_USE_64BIT_BITBUF typedef mz_uint64 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (64) #else typedef mz_uint32 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (32) #endif struct tinfl_decompressor_tag { mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; tinfl_bit_buf_t m_bit_buf; size_t m_dist_from_out_buf_start; tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; }; // ------------------- Low-level Compression API Definitions // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly // slower, and raw/dynamic blocks will be output more frequently). #define TDEFL_LESS_MEMORY 0 // tdefl_init() compression flags logically OR'd together (low 12 bits contain // the max. number of probes per dictionary search): // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes // per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap // compression), 4095=Huffman+LZ (slowest/best compression). enum { TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF }; // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before // the deflate data, and the Adler-32 of the source data at the end. Otherwise, // you'll get raw deflate data. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even // when not writing zlib headers). // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more // efficient lazy parsing. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's // initialization time to the minimum, but the output may vary from run to run // given the same input (depending on the contents of memory). // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. // The low 12 bits are reserved to control the max # of hash probes per // dictionary lookup (see TDEFL_MAX_PROBES_MASK). enum { TDEFL_WRITE_ZLIB_HEADER = 0x01000, TDEFL_COMPUTE_ADLER32 = 0x02000, TDEFL_GREEDY_PARSING_FLAG = 0x04000, TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, TDEFL_RLE_MATCHES = 0x10000, TDEFL_FILTER_MATCHES = 0x20000, TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 }; // High level compression functions: // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block // allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of source block to compress. // flags: The max match finder probes (default is 128) logically OR'd against // the above flags. Higher probes are slower but improve compression. // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pOut_len will be set to the compressed data's size, which could be larger // than src_buf_len on uncompressible data. // The caller must free() the returned block when it's no longer needed. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tdefl_compress_mem_to_mem() compresses a block in memory to another block in // memory. // Returns 0 on failure. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // Compresses an image to a compressed PNG file in memory. // On entry: // pImage, w, h, and num_chans describe the image to compress. num_chans may be // 1, 2, 3, or 4. // The image pitch in bytes per scanline will be w*num_chans. The leftmost // pixel on the top scanline is stored first in memory. // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL // If flip is true, the image will be flipped on the Y axis (useful for OpenGL // apps). // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pLen_out will be set to the size of the PNG image file. // The caller must mz_free() the returned heap block (which will typically be // larger than *pLen_out) when it's no longer needed. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); // Output stream interface. The compressor uses this interface to write // compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); // tdefl_compress_mem_to_output() compresses a block to an output stream. The // above helpers use this function internally. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed // output block (using static/fixed Huffman codes). #if TDEFL_LESS_MEMORY enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #else enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #endif // The low-level tdefl functions below may be used directly if the above helper // functions aren't flexible enough. The low-level functions don't make any heap // allocations, unlike the above helper functions. typedef enum { TDEFL_STATUS_BAD_PARAM = -2, TDEFL_STATUS_PUT_BUF_FAILED = -1, TDEFL_STATUS_OKAY = 0, TDEFL_STATUS_DONE = 1 } tdefl_status; // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums typedef enum { TDEFL_NO_FLUSH = 0, TDEFL_SYNC_FLUSH = 2, TDEFL_FULL_FLUSH = 3, TDEFL_FINISH = 4 } tdefl_flush; // tdefl's compression state structure. typedef struct { tdefl_put_buf_func_ptr m_pPut_buf_func; void *m_pPut_buf_user; mz_uint m_flags, m_max_probes[2]; int m_greedy_parsing; mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; tdefl_status m_prev_return_status; const void *m_pIn_buf; void *m_pOut_buf; size_t *m_pIn_buf_size, *m_pOut_buf_size; tdefl_flush m_flush; const mz_uint8 *m_pSrc; size_t m_src_buf_left, m_out_buf_ofs; mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; } tdefl_compressor; // Initializes the compressor. // There is no corresponding deinit() function because the tdefl API's do not // dynamically allocate memory. // pBut_buf_func: If NULL, output data will be supplied to the specified // callback. In this case, the user should call the tdefl_compress_buffer() API // for compression. // If pBut_buf_func is NULL the user should always call the tdefl_compress() // API. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, // etc.) tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); // Compresses a block of data, consuming as much of the specified input buffer // as possible, and writing as much compressed data to the specified output // buffer as possible. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a // non-NULL tdefl_put_buf_func_ptr. // tdefl_compress_buffer() always consumes the entire input buffer. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); mz_uint32 tdefl_get_adler32(tdefl_compressor *d); // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't // defined, because it uses some of its macros. #ifndef MINIZ_NO_ZLIB_APIS // Create tdefl_compress() flags given zlib-style compression parameters. // level may range from [0,10] (where 10 is absolute max compression, but may be // much slower on some files) // window_bits may be -15 (raw deflate) or 15 (zlib) // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, // MZ_RLE, or MZ_FIXED mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); #endif // #ifndef MINIZ_NO_ZLIB_APIS #ifdef __cplusplus } #endif #endif // MINIZ_HEADER_INCLUDED // ------------------- End of Header: Implementation follows. (If you only want // the header, define MINIZ_HEADER_FILE_ONLY.) #ifndef MINIZ_HEADER_FILE_ONLY typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; //#include <assert.h> //#include <string.h> #define MZ_ASSERT(x) assert(x) #ifdef MINIZ_NO_MALLOC #define MZ_MALLOC(x) NULL #define MZ_FREE(x) (void)x, ((void)0) #define MZ_REALLOC(p, x) NULL #else #define MZ_MALLOC(x) malloc(x) #define MZ_FREE(x) free(x) #define MZ_REALLOC(p, x) realloc(p, x) #endif #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) #else #define MZ_READ_LE16(p) \ ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) #define MZ_READ_LE32(p) \ ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \ ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \ ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) #endif #ifdef _MSC_VER #define MZ_FORCEINLINE __forceinline #elif defined(__GNUC__) #define MZ_FORCEINLINE inline __attribute__((__always_inline__)) #else #define MZ_FORCEINLINE inline #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API's mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) { mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; if (!ptr) return MZ_ADLER32_INIT; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } return (s2 << 16) + s1; } // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C // implementation that balances processor cache usage against speed": // http://www.geocities.com/malbrain/ mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c}; mz_uint32 crcu32 = (mz_uint32)crc; if (!ptr) return MZ_CRC32_INIT; crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } return ~crcu32; } void mz_free(void *p) { MZ_FREE(p); } #ifndef MINIZ_NO_ZLIB_APIS static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } // static void *def_realloc_func(void *opaque, void *address, size_t items, // size_t size) { // (void)opaque, (void)address, (void)items, (void)size; // return MZ_REALLOC(address, items * size); //} const char *mz_version(void) { return MZ_VERSION; } int mz_deflateInit(mz_streamp pStream, int level) { return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); } int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) { tdefl_compressor *pComp; mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); if (!pStream) return MZ_STREAM_ERROR; if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = MZ_ADLER32_INIT; pStream->msg = NULL; pStream->reserved = 0; pStream->total_in = 0; pStream->total_out = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); if (!pComp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pComp; if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) { mz_deflateEnd(pStream); return MZ_PARAM_ERROR; } return MZ_OK; } int mz_deflateReset(mz_streamp pStream) { if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; pStream->total_in = pStream->total_out = 0; tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); return MZ_OK; } int mz_deflate(mz_streamp pStream, int flush) { size_t in_bytes, out_bytes; mz_ulong orig_total_in, orig_total_out; int mz_status = MZ_OK; if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; if (!pStream->avail_out) return MZ_BUF_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; for (;;) { tdefl_status defl_status; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (defl_status < 0) { mz_status = MZ_STREAM_ERROR; break; } else if (defl_status == TDEFL_STATUS_DONE) { mz_status = MZ_STREAM_END; break; } else if (!pStream->avail_out) break; else if ((!pStream->avail_in) && (flush != MZ_FINISH)) { if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) break; return MZ_BUF_ERROR; // Can't make forward progress without some input. } } return mz_status; } int mz_deflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) { (void)pStream; // This is really over conservative. (And lame, but it's actually pretty // tricky to compute a true upper bound given the way tdefl's blocking works.) return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); } int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) { int status; mz_stream stream; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_deflateInit(&stream, level); if (status != MZ_OK) return status; status = mz_deflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_deflateEnd(&stream); return (status == MZ_OK) ? MZ_BUF_ERROR : status; } *pDest_len = stream.total_out; return mz_deflateEnd(&stream); } int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); } mz_ulong mz_compressBound(mz_ulong source_len) { return mz_deflateBound(NULL, source_len); } typedef struct { tinfl_decompressor m_decomp; mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; tinfl_status m_last_status; } inflate_state; int mz_inflateInit2(mz_streamp pStream, int window_bits) { inflate_state *pDecomp; if (!pStream) return MZ_STREAM_ERROR; if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = 0; pStream->msg = NULL; pStream->total_in = 0; pStream->total_out = 0; pStream->reserved = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); if (!pDecomp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pDecomp; tinfl_init(&pDecomp->m_decomp); pDecomp->m_dict_ofs = 0; pDecomp->m_dict_avail = 0; pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; pDecomp->m_first_call = 1; pDecomp->m_has_flushed = 0; pDecomp->m_window_bits = window_bits; return MZ_OK; } int mz_inflateInit(mz_streamp pStream) { return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); } int mz_inflate(mz_streamp pStream, int flush) { inflate_state *pState; mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; size_t in_bytes, out_bytes, orig_avail_in; tinfl_status status; if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState = (inflate_state *)pStream->state; if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; orig_avail_in = pStream->avail_in; first_call = pState->m_first_call; pState->m_first_call = 0; if (pState->m_last_status < 0) return MZ_DATA_ERROR; if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState->m_has_flushed |= (flush == MZ_FINISH); if ((flush == MZ_FINISH) && (first_call)) { // MZ_FINISH on the first call implies that the input and output buffers are // large enough to hold the entire compressed/decompressed file. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (status < 0) return MZ_DATA_ERROR; else if (status != TINFL_STATUS_DONE) { pState->m_last_status = TINFL_STATUS_FAILED; return MZ_BUF_ERROR; } return MZ_STREAM_END; } // flush != MZ_FINISH then we must assume there's more input. if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; if (pState->m_dict_avail) { n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } for (;;) { in_bytes = pStream->avail_in; out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; status = tinfl_decompress( &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pState->m_dict_avail = (mz_uint)out_bytes; n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); if (status < 0) return MZ_DATA_ERROR; // Stream is corrupted (there could be some // uncompressed data left in the output dictionary - // oh well). else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) return MZ_BUF_ERROR; // Signal caller that we can't make forward progress // without supplying more input or by setting flush // to MZ_FINISH. else if (flush == MZ_FINISH) { // The output buffer MUST be large to hold the remaining uncompressed data // when flush==MZ_FINISH. if (status == TINFL_STATUS_DONE) return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's // at least 1 more byte on the way. If there's no more room left in the // output buffer then something is wrong. else if (!pStream->avail_out) return MZ_BUF_ERROR; } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) break; } return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } int mz_inflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { mz_stream stream; int status; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_inflateInit(&stream); if (status != MZ_OK) return status; status = mz_inflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_inflateEnd(&stream); return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; } *pDest_len = stream.total_out; return mz_inflateEnd(&stream); } const char *mz_error(int err) { static struct { int m_err; const char *m_pDesc; } s_error_descs[] = {{MZ_OK, ""}, {MZ_STREAM_END, "stream end"}, {MZ_NEED_DICT, "need dictionary"}, {MZ_ERRNO, "file error"}, {MZ_STREAM_ERROR, "stream error"}, {MZ_DATA_ERROR, "data error"}, {MZ_MEM_ERROR, "out of memory"}, {MZ_BUF_ERROR, "buf error"}, {MZ_VERSION_ERROR, "version error"}, {MZ_PARAM_ERROR, "parameter error"}}; mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; return NULL; } #endif // MINIZ_NO_ZLIB_APIS // ------------------- Low-level Decompression (completely independent from all // compression API's) #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) #define TINFL_MEMSET(p, c, l) memset(p, c, l) #define TINFL_CR_BEGIN \ switch (r->m_state) { \ case 0: #define TINFL_CR_RETURN(state_index, result) \ do { \ status = result; \ r->m_state = state_index; \ goto common_exit; \ case state_index:; \ } \ MZ_MACRO_END #define TINFL_CR_RETURN_FOREVER(state_index, result) \ do { \ for (;;) { \ TINFL_CR_RETURN(state_index, result); \ } \ } \ MZ_MACRO_END #define TINFL_CR_FINISH } // TODO: If the caller has indicated that there's no more input, and we attempt // to read beyond the input buf, then something is wrong with the input because // the inflator never // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of // the stream with 0's in this scenario. #define TINFL_GET_BYTE(state_index, c) \ do { \ if (pIn_buf_cur >= pIn_buf_end) { \ for (;;) { \ if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ if (pIn_buf_cur < pIn_buf_end) { \ c = *pIn_buf_cur++; \ break; \ } \ } else { \ c = 0; \ break; \ } \ } \ } else \ c = *pIn_buf_cur++; \ } \ MZ_MACRO_END #define TINFL_NEED_BITS(state_index, n) \ do { \ mz_uint c; \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < (mz_uint)(n)) #define TINFL_SKIP_BITS(state_index, n) \ do { \ if (num_bits < (mz_uint)(n)) { \ TINFL_NEED_BITS(state_index, n); \ } \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END #define TINFL_GET_BITS(state_index, b, n) \ do { \ if (num_bits < (mz_uint)(n)) { \ TINFL_NEED_BITS(state_index, n); \ } \ b = bit_buf & ((1 << (n)) - 1); \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes // remaining in the input buffer falls below 2. // It reads just enough bytes from the input stream that are needed to decode // the next Huffman code (and absolutely no more). It works by trying to fully // decode a // Huffman code by using whatever bits are currently present in the bit buffer. // If this fails, it reads another byte, and tries again until it succeeds or // until the // bit buffer contains >=15 bits (deflate's max. Huffman code size). #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ do { \ temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ if (temp >= 0) { \ code_len = temp >> 9; \ if ((code_len) && (num_bits >= code_len)) break; \ } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while ((temp < 0) && (num_bits >= (code_len + 1))); \ if (temp >= 0) break; \ } \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < 15); // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex // than you would initially expect because the zlib API expects the decompressor // to never read // beyond the final byte of the deflate stream. (In other words, when this macro // wants to read another byte from the input, it REALLY needs another byte in // order to fully // decode the next Huffman code.) Handling this properly is particularly // important on raw deflate (non-zlib) streams, which aren't followed by a byte // aligned adler-32. // The slow path is only executed at the very end of the input buffer. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) \ do { \ int temp; \ mz_uint code_len, c; \ if (num_bits < 15) { \ if ((pIn_buf_end - pIn_buf_cur) < 2) { \ TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ } else { \ bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \ (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ pIn_buf_cur += 2; \ num_bits += 16; \ } \ } \ if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \ 0) \ code_len = temp >> 9, temp &= 511; \ else { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while (temp < 0); \ } \ sym = temp; \ bit_buf >>= code_len; \ num_bits -= code_len; \ } \ MZ_MACRO_END tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) { static const int s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0}; static const int s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static const int s_min_table_sizes[3] = {257, 1, 4}; tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; // Ensure the output buffer's size is a power of 2, unless the output buffer // is large enough to hold the entire output file (in which case it doesn't // matter). if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; TINFL_CR_BEGIN bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1ULL << (8U + (r->m_zhdr0 >> 4))))); if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } } do { TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; if (r->m_type == 0) { TINFL_SKIP_BITS(5, num_bits & 7); for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } while ((counter) && (num_bits)) { TINFL_GET_BITS(51, dist, 8); while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)dist; counter--; } while (counter) { size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } while (pIn_buf_cur >= pIn_buf_end) { if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); } else { TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); } } n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; } } else if (r->m_type == 3) { TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); } else { if (r->m_type == 1) { mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; } else { for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } r->m_table_sizes[2] = 19; } for (; (int)r->m_type >= 0; r->m_type--) { int tree_next, tree_cur; tinfl_huff_table *pTable; mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } if ((65536 != total) && (used_syms > 1)) { TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); } for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { tree_cur -= ((rev_code >>= 1) & 1); if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; } tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; } if (r->m_type == 2) { for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) { mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } if ((dist == 16) && (!counter)) { TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); } num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; } if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); } TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); } } for (;;) { mz_uint8 *pSrc; for (;;) { if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) { TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); if (counter >= 256) break; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)counter; } else { int sym2; mz_uint code_len; #if TINFL_USE_64BIT_BITBUF if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } #else if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0] .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0] .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } counter = sym2; bit_buf >>= code_len; num_bits -= code_len; if (counter & 256) break; #if !TINFL_USE_64BIT_BITBUF if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0] .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0] .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } bit_buf >>= code_len; num_bits -= code_len; pOut_buf_cur[0] = (mz_uint8)counter; if (sym2 & 256) { pOut_buf_cur++; counter = sym2; break; } pOut_buf_cur[1] = (mz_uint8)sym2; pOut_buf_cur += 2; } } if ((counter &= 511) == 256) break; num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); } pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { while (counter--) { while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; } continue; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES else if ((counter >= 9) && (counter <= dist)) { const mz_uint8 *pSrc_end = pSrc + (counter & ~7); do { ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; pOut_buf_cur += 8; } while ((pSrc += 8) < pSrc_end); if ((counter &= 7) < 3) { if (counter) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } continue; } } #endif do { pOut_buf_cur[0] = pSrc[0]; pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur[2] = pSrc[2]; pOut_buf_cur += 3; pSrc += 3; } while ((int)(counter -= 3) > 2); if ((int)counter > 0) { pOut_buf_cur[0] = pSrc[0]; if ((int)counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } } } } while (!(r->m_final & 1)); if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } } TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); TINFL_CR_FINISH common_exit: r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) { const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; } return status; } // Higher level helper functions. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; *pOut_len = 0; tinfl_init(&decomp); for (;;) { size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; tinfl_status status = tinfl_decompress( &decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } src_buf_ofs += src_buf_size; *pOut_len += dst_buf_size; if (status == TINFL_STATUS_DONE) break; new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); if (!pNew_buf) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; } return pBuf; } size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; } int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { int result = 0; tinfl_decompressor decomp; mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; if (!pDict) return TINFL_STATUS_FAILED; tinfl_init(&decomp); for (;;) { size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); in_buf_ofs += in_buf_size; if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) break; if (status != TINFL_STATUS_HAS_MORE_OUTPUT) { result = (status == TINFL_STATUS_DONE); break; } dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); } MZ_FREE(pDict); *pIn_buf_size = in_buf_ofs; return result; } // ------------------- Low-level Compression (independent from all decompression // API's) // Purposely making these tables static for faster init and thread safety. static const mz_uint16 s_tdefl_len_sym[256] = { 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285}; static const mz_uint8 s_tdefl_len_extra[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0}; static const mz_uint8 s_tdefl_small_dist_sym[512] = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17}; static const mz_uint8 s_tdefl_small_dist_extra[512] = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}; static const mz_uint8 s_tdefl_large_dist_sym[128] = { 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29}; static const mz_uint8 s_tdefl_large_dist_extra[128] = { 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13}; // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted // values. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1) { mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { const mz_uint32 *pHist = &hist[pass << 8]; mz_uint offsets[256], cur_ofs = 0; for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; { tdefl_sym_freq *t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } } return pCur_syms; } // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, // alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) { int root, leaf, next, avbl, used, dpth; if (n == 0) return; else if (n == 1) { A[0].m_key = 1; return; } A[0].m_key += A[1].m_key; root = 0; leaf = 2; for (next = 1; next < n - 1; next++) { if (leaf >= n || A[root].m_key < A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key; if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); } A[n - 2].m_key = 0; for (next = n - 3; next >= 0; next--) A[next].m_key = A[A[next].m_key].m_key + 1; avbl = 1; used = dpth = 0; root = n - 2; next = n - 1; while (avbl > 0) { while (root >= 0 && (int)A[root].m_key == dpth) { used++; root--; } while (avbl > used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } avbl = 2 * used; dpth++; used = 0; } } // Limits canonical Huffman code table's max code size. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) { int i; mz_uint32 total = 0; if (code_list_len <= 1) return; for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); while (total != (1UL << max_code_size)) { pNum_codes[max_code_size]--; for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } total--; } } static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) { int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); if (static_table) { for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; } else { tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; int num_used_syms = 0; const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); for (i = 1, j = num_used_syms; i <= code_size_limit; i++) for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); } next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); for (i = 0; i < table_len; i++) { mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; } } #define TDEFL_PUT_BITS(b, l) \ do { \ mz_uint bits = b; \ mz_uint len = l; \ MZ_ASSERT(bits <= ((1U << len) - 1U)); \ d->m_bit_buffer |= (bits << d->m_bits_in); \ d->m_bits_in += len; \ while (d->m_bits_in >= 8) { \ if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ d->m_bit_buffer >>= 8; \ d->m_bits_in -= 8; \ } \ } \ MZ_MACRO_END #define TDEFL_RLE_PREV_CODE_SIZE() \ { \ if (rle_repeat_count) { \ if (rle_repeat_count < 3) { \ d->m_huff_count[2][prev_code_size] = (mz_uint16)( \ d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ while (rle_repeat_count--) \ packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ } else { \ d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 16; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_repeat_count - 3); \ } \ rle_repeat_count = 0; \ } \ } #define TDEFL_RLE_ZERO_CODE_SIZE() \ { \ if (rle_z_count) { \ if (rle_z_count < 3) { \ d->m_huff_count[2][0] = \ (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ } else if (rle_z_count <= 10) { \ d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 17; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_z_count - 3); \ } else { \ d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 18; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_z_count - 11); \ } \ rle_z_count = 0; \ } \ } static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static void tdefl_start_dynamic_block(tdefl_compressor *d) { int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; d->m_huff_count[0][256] = 1; tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); for (i = 0; i < total_code_sizes_to_pack; i++) { mz_uint8 code_size = code_sizes_to_pack[i]; if (!code_size) { TDEFL_RLE_PREV_CODE_SIZE(); if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } } else { TDEFL_RLE_ZERO_CODE_SIZE(); if (code_size != prev_code_size) { TDEFL_RLE_PREV_CODE_SIZE(); d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; } else if (++rle_repeat_count == 6) { TDEFL_RLE_PREV_CODE_SIZE(); } } prev_code_size = code_size; } if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); TDEFL_PUT_BITS(2, 2); TDEFL_PUT_BITS(num_lit_codes - 257, 5); TDEFL_PUT_BITS(num_dist_codes - 1, 5); for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes [2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS( d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) { mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); } } static void tdefl_start_static_block(tdefl_compressor *d) { mz_uint i; mz_uint8 *p = &d->m_huff_code_sizes[0][0]; for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; memset(d->m_huff_code_sizes[1], 5, 32); tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); TDEFL_PUT_BITS(1, 2); } static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF}; #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \ MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; mz_uint8 *pOutput_buf = d->m_pOutput_buf; mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; mz_uint64 bit_buffer = d->m_bit_buffer; mz_uint bits_in = d->m_bits_in; #define TDEFL_PUT_BITS_FAST(b, l) \ { \ bit_buffer |= (((mz_uint64)(b)) << bits_in); \ bits_in += (l); \ } flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint s0, s1, n0, n1, sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); // This sequence coaxes MSVC into using cmov's vs. jmp's. s0 = s_tdefl_small_dist_sym[match_dist & 511]; n0 = s_tdefl_small_dist_extra[match_dist & 511]; s1 = s_tdefl_large_dist_sym[match_dist >> 8]; n1 = s_tdefl_large_dist_extra[match_dist >> 8]; sym = (match_dist < 512) ? s0 : s1; num_extra_bits = (match_dist < 512) ? n0 : n1; MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } } if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE; *(mz_uint64 *)pOutput_buf = bit_buffer; pOutput_buf += (bits_in >> 3); bit_buffer >>= (bits_in & ~7); bits_in &= 7; } #undef TDEFL_PUT_BITS_FAST d->m_pOutput_buf = pOutput_buf; d->m_bits_in = 0; d->m_bit_buffer = 0; while (bits_in) { mz_uint32 n = MZ_MIN(bits_in, 16); TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); bit_buffer >>= n; bits_in -= n; } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #else static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); if (match_dist < 512) { sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; } else { sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; } MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && // MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) { if (static_block) tdefl_start_static_block(d); else tdefl_start_dynamic_block(d); return tdefl_compress_lz_codes(d); } static int tdefl_flush_block(tdefl_compressor *d, int flush) { mz_uint saved_bit_buf, saved_bits_in; mz_uint8 *pSaved_output_buf; mz_bool comp_block_succeeded = MZ_FALSE; int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; d->m_pOutput_buf = pOutput_buf_start; d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; MZ_ASSERT(!d->m_output_flush_remaining); d->m_output_flush_ofs = 0; d->m_output_flush_remaining = 0; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) { TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); } TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; if (!use_raw_block) comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); // If the block gets expanded, forget the current contents of the output // buffer and send a raw block instead. if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) { mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; TDEFL_PUT_BITS(0, 2); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); } for (i = 0; i < d->m_total_lz_bytes; ++i) { TDEFL_PUT_BITS( d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); } } // Check for the extremely unlikely (if not impossible) case of the compressed // block not fitting into the output buffer when using dynamic codes. else if (!comp_block_succeeded) { d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; tdefl_compress_block(d, MZ_TRUE); } if (flush) { if (flush == TDEFL_FINISH) { if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } } else { mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } } } MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { if (d->m_pPut_buf_func) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); } else if (pOutput_buf_start == d->m_output_buf) { int bytes_to_copy = (int)MZ_MIN( (size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); d->m_out_buf_ofs += bytes_to_copy; if ((n -= bytes_to_copy) != 0) { d->m_output_flush_ofs = bytes_to_copy; d->m_output_flush_remaining = n; } } else { d->m_out_buf_ofs += n; } } return d->m_output_flush_remaining; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for (;;) { for (;;) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || \ ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; q = (const mz_uint16 *)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32; do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); if (!probe_len) { *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; } else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); } } } #else static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint8 *s = d->m_dict + pos, *p, *q; mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for (;;) { for (;;) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || \ ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if ((d->m_dict[probe_pos + match_len] == c0) && \ (d->m_dict[probe_pos + match_len - 1] == c1)) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break; if (probe_len > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; } } } #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static mz_bool tdefl_compress_fast(tdefl_compressor *d) { // Faster, minimally featured LZRW1-style match+parse loop with better // register utilization. Intended for applications where raw throughput is // valued more highly than ratio. mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); d->m_src_buf_left -= num_bytes_to_process; lookahead_size += num_bytes_to_process; while (num_bytes_to_process) { mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); memcpy(d->m_dict + dst_pos, d->m_pSrc, n); if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); d->m_pSrc += n; dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; num_bytes_to_process -= n; } dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; while (lookahead_size >= 4) { mz_uint cur_match_dist, cur_match_len = 1; mz_uint8 *pCur_dict = d->m_dict + cur_pos; mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; mz_uint probe_pos = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)lookahead_pos; if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) { const mz_uint16 *p = (const mz_uint16 *)pCur_dict; const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); mz_uint32 probe_len = 32; do { } while ((TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); if (!probe_len) cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) { cur_match_len = 1; *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } else { mz_uint32 s0, s1; cur_match_len = MZ_MIN(cur_match_len, lookahead_size); MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); cur_match_dist--; pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; pLZ_code_buf += 3; *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; } } else { *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } total_lz_bytes += cur_match_len; lookahead_pos += cur_match_len; dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; MZ_ASSERT(lookahead_size >= cur_match_len); lookahead_size -= cur_match_len; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } while (lookahead_size) { mz_uint8 lit = d->m_dict[cur_pos]; total_lz_bytes++; *pLZ_code_buf++ = lit; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } d->m_huff_count[0][lit]++; lookahead_pos++; dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; lookahead_size--; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } } d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; return MZ_TRUE; } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) { d->m_total_lz_bytes++; *d->m_pLZ_code_buf++ = lit; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } d->m_huff_count[0][lit]++; } static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) { mz_uint32 s0, s1; MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); d->m_total_lz_bytes += match_len; d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); match_dist -= 1; d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; } static mz_bool tdefl_compress_normal(tdefl_compressor *d) { const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; tdefl_flush flush = d->m_flush; while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) { mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; // Update dictionary and hash chains. Keeps the lookahead size equal to // TDEFL_MAX_MATCH_LEN. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) { mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; src_buf_left -= num_bytes_to_process; d->m_lookahead_size += num_bytes_to_process; while (pSrc != pSrc_end) { mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; } } else { while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { mz_uint8 c = *pSrc++; mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; src_buf_left--; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) { mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); } } } d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break; // Simple lazy/greedy parsing state machine. len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) { if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) { mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; } } else { tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); } if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) { cur_match_dist = cur_match_len = 0; } if (d->m_saved_match_len) { if (cur_match_len > d->m_saved_match_len) { tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); if (cur_match_len >= 128) { tdefl_record_match(d, cur_match_len, cur_match_dist); d->m_saved_match_len = 0; len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } } else { tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; } } else if (!cur_match_dist) tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) { tdefl_record_match(d, cur_match_len, cur_match_dist); len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } // Move the lookahead forward by len_to_move bytes. d->m_lookahead_pos += len_to_move; MZ_ASSERT(d->m_lookahead_size >= len_to_move); d->m_lookahead_size -= len_to_move; d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); // Check if it's time to flush the current LZ codes to the internal output // buffer. if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) { int n; d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; } } d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; return MZ_TRUE; } static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) { if (d->m_pIn_buf_size) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; } if (d->m_pOut_buf_size) { size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); d->m_output_flush_ofs += (mz_uint)n; d->m_output_flush_remaining -= (mz_uint)n; d->m_out_buf_ofs += n; *d->m_pOut_buf_size = d->m_out_buf_ofs; } return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; } tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) { if (!d) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return TDEFL_STATUS_BAD_PARAM; } d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; d->m_out_buf_ofs = 0; d->m_flush = flush; if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); } d->m_wants_to_finish |= (flush == TDEFL_FINISH); if ((d->m_output_flush_remaining) || (d->m_finished)) return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) { if (!tdefl_compress_fast(d)) return d->m_prev_return_status; } else #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN { if (!tdefl_compress_normal(d)) return d->m_prev_return_status; } if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) { if (tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status; d->m_finished = (flush == TDEFL_FINISH); if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } } return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); } tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) { MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); } tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); return TDEFL_STATUS_OKAY; } tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) { return d->m_prev_return_status; } mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; } mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); MZ_FREE(pComp); return succeeded; } typedef struct { size_t m_size, m_capacity; mz_uint8 *m_pBuf; mz_bool m_expandable; } tdefl_output_buffer; static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) { tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; size_t new_size = p->m_size + len; if (new_size > p->m_capacity) { size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE; do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE; p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; } memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; return MZ_TRUE; } void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_len) return MZ_FALSE; else *pOut_len = 0; out_buf.m_expandable = MZ_TRUE; if (!tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; *pOut_len = out_buf.m_size; return out_buf.m_pBuf; } size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_buf) return 0; out_buf.m_pBuf = (mz_uint8 *)pOut_buf; out_buf.m_capacity = out_buf_len; if (!tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; return out_buf.m_size; } #ifndef MINIZ_NO_ZLIB_APIS static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500}; // level may actually range from [0,10] (10 is a "hidden" max level, where we // want a bit more compression and it's fine if throughput to fall off a cliff // on some files). mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) { mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; return comp_flags; } #endif // MINIZ_NO_ZLIB_APIS #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4204) // nonstandard extension used : non-constant // aggregate initializer (also supported by GNU // C and C99, so no big deal) #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is // deprecated. Instead, use the ISO C and C++ // conformant name: _strdup. #endif // Simple PNG writer function by Alex Evans, 2011. Released into the public // domain: https://gist.github.com/908299, more context at // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. // This is actually a modification of Alex's original code so PNG files // generated by this function pass pngcheck. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) { // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was // defined. static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500}; tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; if (!pComp) return NULL; MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } // write dummy header for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); // compress image data tdefl_init( pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); } if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } // write real header *pLen_out = out_buf.m_size - 41; { static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06}; mz_uint8 pnghdr[41] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0, 0, (mz_uint8)(w >> 8), (mz_uint8)w, 0, 0, (mz_uint8)(h >> 8), (mz_uint8)h, 8, chans[num_chans], 0, 0, 0, 0, 0, 0, 0, (mz_uint8)(*pLen_out >> 24), (mz_uint8)(*pLen_out >> 16), (mz_uint8)(*pLen_out >> 8), (mz_uint8)*pLen_out, 0x49, 0x44, 0x41, 0x54}; c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); for (i = 0; i < 4; ++i, c <<= 8) ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); memcpy(out_buf.m_pBuf, pnghdr, 41); } // write footer (IDAT CRC-32, followed by IEND chunk) if (!tdefl_output_buffer_putter( "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); for (i = 0; i < 4; ++i, c <<= 8) (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); // compute final size of file, grab compressed data buffer and return *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; } void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) { // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we // can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's // where #defined out) return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); } // ------------------- .ZIP archive reading #ifndef MINIZ_NO_ARCHIVE_APIS #error "No arvhive APIs" #ifdef MINIZ_NO_STDIO #define MZ_FILE void * #else #include <stdio.h> #include <sys/stat.h> #if defined(_MSC_VER) || defined(__MINGW64__) static FILE *mz_fopen(const char *pFilename, const char *pMode) { FILE *pFile = NULL; fopen_s(&pFile, pFilename, pMode); return pFile; } static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) { FILE *pFile = NULL; if (freopen_s(&pFile, pPath, pMode, pStream)) return NULL; return pFile; } #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN mz_fopen #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 _ftelli64 #define MZ_FSEEK64 _fseeki64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN mz_freopen #define MZ_DELETE_FILE remove #elif defined(__MINGW32__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__TINYC__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftell #define MZ_FSEEK64 fseek #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__GNUC__) && defined(_LARGEFILE64_SOURCE) && _LARGEFILE64_SOURCE #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen64(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT stat64 #define MZ_FILE_STAT stat64 #define MZ_FFLUSH fflush #define MZ_FREOPEN(p, m, s) freopen64(p, m, s) #define MZ_DELETE_FILE remove #else #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello #define MZ_FSEEK64 fseeko #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #endif // #ifdef _MSC_VER #endif // #ifdef MINIZ_NO_STDIO #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) // Various ZIP archive enums. To completely avoid cross platform compiler // alignment and platform endian issues, miniz.c doesn't use structs for any of // this stuff. enum { // ZIP archive identifiers and record sizes MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, // Central directory header record offsets MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, // Local directory header offsets MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, // End of central directory offsets MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, }; typedef struct { void *m_p; size_t m_size, m_capacity; mz_uint m_element_size; } mz_zip_array; struct mz_zip_internal_state_tag { mz_zip_array m_central_dir; mz_zip_array m_central_dir_offsets; mz_zip_array m_sorted_central_dir_offsets; MZ_FILE *m_pFile; void *m_pMem; size_t m_mem_size; size_t m_mem_capacity; }; #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \ (array_ptr)->m_element_size = element_size #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \ ((element_type *)((array_ptr)->m_p))[index] static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) { pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); memset(pArray, 0, sizeof(mz_zip_array)); } static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) { void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) { if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) { if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } pArray->m_size = new_size; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) { return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); } static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) { size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); return MZ_TRUE; } #ifndef MINIZ_NO_TIME static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) { struct tm tm; memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; return mktime(&tm); } static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef _MSC_VER struct tm tm_struct; struct tm *tm = &tm_struct; errno_t err = localtime_s(tm, &time); if (err) { *pDOS_date = 0; *pDOS_time = 0; return; } #else struct tm *tm = localtime(&time); #endif *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); } #endif #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef MINIZ_NO_TIME (void)pFilename; *pDOS_date = *pDOS_time = 0; #else struct MZ_FILE_STAT_STRUCT file_stat; // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 // bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE; mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date); #endif // #ifdef MINIZ_NO_TIME return MZ_TRUE; } #ifndef MINIZ_NO_TIME static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) { struct utimbuf t; t.actime = access_time; t.modtime = modified_time; return !utime(pFilename, &t); } #endif // #ifndef MINIZ_NO_TIME #endif // #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags) { (void)flags; if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_READING; pZip->m_archive_size = 0; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (l_len < r_len) : (l < r); } #define MZ_SWAP_UINT32(a, b) \ do { \ mz_uint32 t = a; \ a = b; \ b = t; \ } \ MZ_MACRO_END // Heap sort of lowercased filenames, used to help accelerate plain central // directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), // but it could allocate memory.) static void mz_zip_reader_sort_central_dir_offsets_by_filename( mz_zip_archive *pZip) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( &pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; int start = (size - 2) >> 1, end; while (start >= 0) { int child, root = start; for (;;) { if ((child = (root << 1) + 1) >= size) break; child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]))); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } start--; } end = size - 1; while (end > 0) { int child, root = 0; MZ_SWAP_UINT32(pIndices[end], pIndices[0]); for (;;) { if ((child = (root << 1) + 1) >= end) break; child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } end--; } } static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags) { mz_uint cdir_size, num_this_disk, cdir_disk_index; mz_uint64 cdir_ofs; mz_int64 cur_file_ofs; const mz_uint8 *p; mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); // Basic sanity checks - reject files which are too small, and check the first // 4 bytes of the file to make sure a local header is there. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; // Find the end of central directory record by scanning the file from the end // towards the beginning. cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); for (;;) { int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) return MZ_FALSE; for (i = n - 4; i >= 0; --i) if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) break; if (i >= 0) { cur_file_ofs += i; break; } if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) return MZ_FALSE; cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); } // Read and verify the end of central directory record. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) return MZ_FALSE; num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) return MZ_FALSE; if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) return MZ_FALSE; pZip->m_central_directory_file_ofs = cdir_ofs; if (pZip->m_total_files) { mz_uint i, n; // Read the entire central directory into a heap block, and allocate another // heap block to hold the unsorted central dir file record offsets, and // another to hold the sorted indices. if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) return MZ_FALSE; if (sort_central_dir) { if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) return MZ_FALSE; } if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) return MZ_FALSE; // Now create an index into the central directory file records, do some // basic sanity checking on each record, and check for zip64 entries (which // are not yet supported). p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) { mz_uint total_header_size, comp_size, decomp_size, disk_index; if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) return MZ_FALSE; MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); if (sort_central_dir) MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) return MZ_FALSE; disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); if ((disk_index != num_this_disk) && (disk_index != 1)) return MZ_FALSE; if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) return MZ_FALSE; n -= total_header_size; p += total_header_size; } } if (sort_central_dir) mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); return MZ_TRUE; } mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags) { if ((!pZip) || (!pZip->m_pRead)) return MZ_FALSE; if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); return s; } mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags) { if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; pZip->m_pRead = mz_zip_mem_read_func; pZip->m_pIO_opaque = pZip; #ifdef __cplusplus pZip->m_pState->m_pMem = const_cast<void *>(pMem); #else pZip->m_pState->m_pMem = (void *)pMem; #endif pZip->m_pState->m_mem_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) { mz_uint64 file_size; MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); if (!pFile) return MZ_FALSE; if (MZ_FSEEK64(pFile, 0, SEEK_END)) { MZ_FCLOSE(pFile); return MZ_FALSE; } file_size = MZ_FTELL64(pFile); if (!mz_zip_reader_init_internal(pZip, flags)) { MZ_FCLOSE(pFile); return MZ_FALSE; } pZip->m_pRead = mz_zip_file_read_func; pZip->m_pIO_opaque = pZip; pZip->m_pState->m_pFile = pFile; pZip->m_archive_size = file_size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) { return pZip ? pZip->m_total_files : 0; } static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh( mz_zip_archive *pZip, mz_uint file_index) { if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return NULL; return &MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); } mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) { mz_uint m_bit_flag; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); return (m_bit_flag & 1); } mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) { mz_uint filename_len, external_attr; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; // First see if the filename ends with a '/' character. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_len) { if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') return MZ_TRUE; } // Bugfix: This code was also checking if the internal attribute was non-zero, // which wasn't correct. // Most/all zip writers (hopefully) set DOS file/directory attributes in the // low 16-bits, so check for the DOS directory flag and ignore the source OS // ID in the created by field. // FIXME: Remove this check? Is it necessary - we already check the filename. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); if ((external_attr & 0x10) != 0) return MZ_TRUE; return MZ_FALSE; } mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if ((!p) || (!pStat)) return MZ_FALSE; // Unpack the central directory record. pStat->m_file_index = file_index; pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); #ifndef MINIZ_NO_TIME pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); #endif pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); // Copy as much of the filename and comment as possible. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); pStat->m_comment_size = n; memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; return MZ_TRUE; } mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; } n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_buf_size) { n = MZ_MIN(n, filename_buf_size - 1); memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pFilename[n] = '\0'; } return n + 1; } static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) { mz_uint i; if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len); for (i = 0; i < len; ++i) if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) return MZ_FALSE; return MZ_TRUE; } static MZ_FORCEINLINE int mz_zip_reader_filename_compare( const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (int)(l_len - r_len) : (l - r); } static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( &pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; const mz_uint filename_len = (mz_uint)strlen(pFilename); int l = 0, h = size - 1; while (l <= h) { int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); if (!comp) return file_index; else if (comp < 0) l = m + 1; else h = m - 1; } return -1; } int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) { mz_uint file_index; size_t name_len, comment_len; if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return -1; if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) return mz_zip_reader_locate_file_binary_search(pZip, pName); name_len = strlen(pName); if (name_len > 0xFFFF) return -1; comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1; for (file_index = 0; file_index < pZip->m_total_files; file_index++) { const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; if (filename_len < name_len) continue; if (comment_len) { mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); const char *pFile_comment = pFilename + filename_len + file_extra_len; if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags))) continue; } if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) { int ofs = filename_len - 1; do { if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) break; } while (--ofs >= 0); ofs++; pFilename += ofs; filename_len -= ofs; } if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) return file_index; } return -1; } mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int status = TINFL_STATUS_DONE; mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; mz_zip_archive_file_stat file_stat; void *pRead_buf; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; tinfl_decompressor inflator; if ((buf_size) && (!pBuf)) return MZ_FALSE; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips // with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have // compressed deflate data which inflates to 0 bytes, but these entries claim // to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Ensure supplied output buffer is large enough. needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; if (buf_size < needed_size) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) return MZ_FALSE; return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); } // Decompress the file either directly from memory or from a file input // buffer. tinfl_init(&inflator); if (pZip->m_pState->m_pMem) { // Read directly from the archive in memory. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else if (pUser_read_buf) { // Use a user provided read buffer. if (!user_read_buf_size) return MZ_FALSE; pRead_buf = (mz_uint8 *)pUser_read_buf; read_buf_size = user_read_buf_size; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } else { // Temporarily allocate a read buffer. read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #endif return MZ_FALSE; if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } do { size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress( &inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; out_buf_ofs += out_buf_size; } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); if (status == TINFL_STATUS_DONE) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); } mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); } mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); } void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) { mz_uint64 comp_size, uncomp_size, alloc_size; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); void *pBuf; if (pSize) *pSize = 0; if (!p) return NULL; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #endif return NULL; if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) return NULL; if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return NULL; } if (pSize) *pSize = (size_t)alloc_size; return pBuf; } void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) { if (pSize) *pSize = 0; return MZ_FALSE; } return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); } mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; mz_zip_archive_file_stat file_stat; void *pRead_buf = NULL; void *pWrite_buf = NULL; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips // with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have // compressed deflate data which inflates to 0 bytes, but these entries claim // to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; // Decompress the file either directly from memory or from a file input // buffer. if (pZip->m_pState->m_pMem) { pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else { read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pState->m_pMem) { #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #endif return MZ_FALSE; if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) status = TINFL_STATUS_FAILED; else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); cur_file_ofs += file_stat.m_comp_size; out_buf_ofs += file_stat.m_comp_size; comp_remaining = 0; } else { while (comp_remaining) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32( file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; out_buf_ofs += read_buf_avail; comp_remaining -= read_buf_avail; } } } else { tinfl_decompressor inflator; tinfl_init(&inflator); if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) status = TINFL_STATUS_FAILED; else { do { mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress( &inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; if (out_buf_size) { if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) { status = TINFL_STATUS_FAILED; break; } file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) { status = TINFL_STATUS_FAILED; break; } } } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); } } if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if (!pZip->m_pState->m_pMem) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); if (pWrite_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) { (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); } mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) { mz_bool status; mz_zip_archive_file_stat file_stat; MZ_FILE *pFile; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; pFile = MZ_FOPEN(pDst_filename, "wb"); if (!pFile) return MZ_FALSE; status = mz_zip_reader_extract_to_callback( pZip, file_index, mz_zip_file_write_callback, pFile, flags); if (MZ_FCLOSE(pFile) == EOF) return MZ_FALSE; #ifndef MINIZ_NO_TIME if (status) mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); #endif return status; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_end(mz_zip_archive *pZip) { if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; if (pZip->m_pState) { mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO pZip->m_pFree(pZip->m_pAlloc_opaque, pState); } pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); } #endif // ------------------- .ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) { if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (pZip->m_file_offset_alignment) { // Ensure user specified file offset alignment is a power of 2. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) return MZ_FALSE; } if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_archive_size = existing_size; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_zip_internal_state *pState = pZip->m_pState; mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); #ifdef _MSC_VER if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #else if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #endif return 0; if (new_size > pState->m_mem_capacity) { void *pNew_block; size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2; if (NULL == (pNew_block = pZip->m_pRealloc( pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) return 0; pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; } memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); pState->m_mem_size = (size_t)new_size; return n; } mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) { pZip->m_pWrite = mz_zip_heap_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) { if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, initial_allocation_size))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_mem_capacity = initial_allocation_size; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) { MZ_FILE *pFile; pZip->m_pWrite = mz_zip_file_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_pFile = pFile; if (size_to_reserve_at_beginning) { mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); do { size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) { mz_zip_writer_end(pZip); return MZ_FALSE; } cur_ofs += n; size_to_reserve_at_beginning -= n; } while (size_to_reserve_at_beginning); } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; // No sense in trying to write to an archive that's already at the support max // size if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; pState = pZip->m_pState; if (pState->m_pFile) { #ifdef MINIZ_NO_STDIO pFilename; return MZ_FALSE; #else // Archive is being read from stdio - try to reopen as writable. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; if (!pFilename) return MZ_FALSE; pZip->m_pWrite = mz_zip_file_write_func; if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) { // The mz_zip_archive is now in a bogus state because pState->m_pFile is // NULL, so just close it. mz_zip_reader_end(pZip); return MZ_FALSE; } #endif // #ifdef MINIZ_NO_STDIO } else if (pState->m_pMem) { // Archive lives in a memory block. Assume it's from the heap that we can // resize using the realloc callback. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; pState->m_mem_capacity = pState->m_mem_size; pZip->m_pWrite = mz_zip_heap_write_func; } // Archive is being read via a user provided read function - make sure the // user has specified a write function too. else if (!pZip->m_pWrite) return MZ_FALSE; // Start writing new files at the archive's current central directory // location. pZip->m_archive_size = pZip->m_central_directory_file_ofs; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_central_directory_file_ofs = 0; return MZ_TRUE; } mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) { return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); } typedef struct { mz_zip_archive *m_pZip; mz_uint64 m_cur_archive_file_ofs; mz_uint64 m_comp_size; } mz_zip_writer_add_state; static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) { mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) return MZ_FALSE; pState->m_cur_archive_file_ofs += len; pState->m_comp_size += len; return MZ_TRUE; } static mz_bool mz_zip_writer_create_local_dir_header( mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) { (void)pZip; memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); return MZ_TRUE; } static mz_bool mz_zip_writer_create_central_dir_header( mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { (void)pZip; memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); return MZ_TRUE; } static mz_bool mz_zip_writer_add_to_central_dir( mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { mz_zip_internal_state *pState = pZip->m_pState; mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; size_t orig_central_dir_size = pState->m_central_dir.m_size; mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; // No zip64 support yet if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_central_dir_header( pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) return MZ_FALSE; if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &central_dir_ofs, 1))) { // Try to push the central directory array back into its original state. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } return MZ_TRUE; } static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) { // Basic ZIP archive filename validity checks: Valid filenames cannot start // with a forward slash, cannot contain a drive letter, and cannot use // DOS-style backward slashes. if (*pArchive_name == '/') return MZ_FALSE; while (*pArchive_name) { if ((*pArchive_name == '\\') || (*pArchive_name == ':')) return MZ_FALSE; pArchive_name++; } return MZ_TRUE; } static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment( mz_zip_archive *pZip) { mz_uint32 n; if (!pZip->m_file_offset_alignment) return 0; n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1); } static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) { char buf[4096]; memset(buf, 0, MZ_MIN(sizeof(buf), n)); while (n) { mz_uint32 s = MZ_MIN(sizeof(buf), n); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) return MZ_FALSE; cur_file_ofs += s; n -= s; } return MZ_TRUE; } mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) { mz_uint16 method = 0, dos_time = 0, dos_date = 0; mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; tdefl_compressor *pComp = NULL; mz_bool store_data_uncompressed; mz_zip_internal_state *pState; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; pState = pZip->m_pState; if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) return MZ_FALSE; // No zip64 support yet if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; #ifndef MINIZ_NO_TIME { time_t cur_time; time(&cur_time); mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date); } #endif // #ifndef MINIZ_NO_TIME archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) { // Set DOS Subdirectory attribute bit. ext_attributes |= 0x10; // Subdirectories cannot contain data. if ((buf_size) || (uncomp_size)) return MZ_FALSE; } // Try to do any allocations before writing to the archive, so if an // allocation fails the file remains unmodified. (A good idea if we're doing // an in-place modification.) if ((!mz_zip_array_ensure_room( pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) return MZ_FALSE; if ((!store_data_uncompressed) && (buf_size)) { if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) return MZ_FALSE; } if (!mz_zip_writer_write_zeros( pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); uncomp_size = buf_size; if (uncomp_size <= 3) { level = 0; store_data_uncompressed = MZ_TRUE; } } if (store_data_uncompressed) { if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += buf_size; comp_size = buf_size; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) method = MZ_DEFLATED; } else if (buf_size) { mz_zip_writer_add_state state; state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params( level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pComp = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header( pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir( pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; MZ_FILE *pSrc_file = NULL; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date)) return MZ_FALSE; pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); if (!pSrc_file) return MZ_FALSE; MZ_FSEEK64(pSrc_file, 0, SEEK_END); uncomp_size = MZ_FTELL64(pSrc_file); MZ_FSEEK64(pSrc_file, 0, SEEK_SET); if (uncomp_size > 0xFFFFFFFF) { // No zip64 support yet MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (uncomp_size <= 3) level = 0; if (!mz_zip_writer_write_zeros( pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (uncomp_size) { mz_uint64 uncomp_remaining = uncomp_size; void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); if (!pRead_buf) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (!level) { while (uncomp_remaining) { mz_uint n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); uncomp_remaining -= n; cur_archive_file_ofs += n; } comp_size = uncomp_size; } else { mz_bool result = MZ_FALSE; mz_zip_writer_add_state state; tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); if (!pComp) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params( level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } for (;;) { size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); tdefl_status status; if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) break; uncomp_crc32 = (mz_uint32)mz_crc32( uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); uncomp_remaining -= in_buf_size; status = tdefl_compress_buffer( pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); if (status == TDEFL_STATUS_DONE) { result = MZ_TRUE; break; } else if (status != TDEFL_STATUS_OKAY) break; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); if (!result) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); } MZ_FCLOSE(pSrc_file); pSrc_file = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header( pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir( pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index) { mz_uint n, bit_flags, num_alignment_padding_bytes; mz_uint64 comp_bytes_remaining, local_dir_header_ofs; mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; size_t orig_central_dir_size; mz_zip_internal_state *pState; void *pBuf; const mz_uint8 *pSrc_central_header; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) return MZ_FALSE; pState = pZip->m_pState; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); cur_dst_file_ofs = pZip->m_archive_size; if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) return MZ_FALSE; cur_dst_file_ofs += num_alignment_padding_bytes; local_dir_header_ofs = cur_dst_file_ofs; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); if (NULL == (pBuf = pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining))))) return MZ_FALSE; while (comp_bytes_remaining) { n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_dst_file_ofs += n; comp_bytes_remaining -= n; } bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); if (bit_flags & 8) { // Copy data descriptor if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; cur_dst_file_ofs += n; } pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); // no zip64 support yet if (cur_dst_file_ofs > 0xFFFFFFFF) return MZ_FALSE; orig_central_dir_size = pState->m_central_dir.m_size; memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) return MZ_FALSE; n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); if (!mz_zip_array_push_back( pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } if (pState->m_central_dir.m_size > 0xFFFFFFFF) return MZ_FALSE; n = (mz_uint32)orig_central_dir_size; if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } pZip->m_total_files++; pZip->m_archive_size = cur_dst_file_ofs; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_uint64 central_dir_ofs, central_dir_size; mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; pState = pZip->m_pState; // no zip64 support yet if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; central_dir_ofs = 0; central_dir_size = 0; if (pZip->m_total_files) { // Write central directory central_dir_ofs = pZip->m_archive_size; central_dir_size = pState->m_central_dir.m_size; pZip->m_central_directory_file_ofs = central_dir_ofs; if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) return MZ_FALSE; pZip->m_archive_size += central_dir_size; } // Write end of central directory record MZ_CLEAR_OBJ(hdr); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr)) return MZ_FALSE; #ifndef MINIZ_NO_STDIO if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) return MZ_FALSE; #endif // #ifndef MINIZ_NO_STDIO pZip->m_archive_size += sizeof(hdr); pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize) { if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) return MZ_FALSE; if (pZip->m_pWrite != mz_zip_heap_write_func) return MZ_FALSE; if (!mz_zip_writer_finalize_archive(pZip)) return MZ_FALSE; *pBuf = pZip->m_pState->m_pMem; *pSize = pZip->m_pState->m_mem_size; pZip->m_pState->m_pMem = NULL; pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; return MZ_TRUE; } mz_bool mz_zip_writer_end(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_bool status = MZ_TRUE; if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) return MZ_FALSE; pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); pState->m_pMem = NULL; } pZip->m_pFree(pZip->m_pAlloc_opaque, pState); pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return status; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_add_mem_to_archive_file_in_place( const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_bool status, created_new_archive = MZ_FALSE; mz_zip_archive zip_archive; struct MZ_FILE_STAT_STRUCT file_stat; MZ_CLEAR_OBJ(zip_archive); if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) { // Create a new archive. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0)) return MZ_FALSE; created_new_archive = MZ_TRUE; } else { // Append to an existing archive. if (!mz_zip_reader_init_file( &zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return MZ_FALSE; if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) { mz_zip_reader_end(&zip_archive); return MZ_FALSE; } } status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); // Always finalize, even if adding failed for some reason, so we have a valid // central directory. (This may not always succeed, but we can try.) if (!mz_zip_writer_finalize_archive(&zip_archive)) status = MZ_FALSE; if (!mz_zip_writer_end(&zip_archive)) status = MZ_FALSE; if ((!status) && (created_new_archive)) { // It's a new archive and something went wrong, so just delete it. int ignoredStatus = MZ_DELETE_FILE(pZip_filename); (void)ignoredStatus; } return status; } void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) { int file_index; mz_zip_archive zip_archive; void *p = NULL; if (pSize) *pSize = 0; if ((!pZip_filename) || (!pArchive_name)) return NULL; MZ_CLEAR_OBJ(zip_archive); if (!mz_zip_reader_init_file( &zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return NULL; if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0) p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); mz_zip_reader_end(&zip_archive); return p; } #endif // #ifndef MINIZ_NO_STDIO #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef __cplusplus } #endif #ifdef _MSC_VER #pragma warning(pop) #endif #endif // MINIZ_HEADER_FILE_ONLY /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org/> */ // ---------------------- end of miniz ---------------------------------------- #ifdef __clang__ #pragma clang diagnostic pop #endif } // namespace miniz #else // Reuse MINIZ_LITTE_ENDIAN macro #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \ defined(__i386) || defined(__i486__) || defined(__i486) || \ defined(i386) || defined(__ia64__) || defined(__x86_64__) // MINIZ_X86_OR_X64_CPU is only used to help set the below macros. #define MINIZ_X86_OR_X64_CPU 1 #endif #if defined(__sparcv9) // Big endian #else #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #endif #endif // TINYEXR_USE_MINIZ // static bool IsBigEndian(void) { // union { // unsigned int i; // char c[4]; // } bint = {0x01020304}; // // return bint.c[0] == 1; //} static void SetErrorMessage(const std::string &msg, const char **err) { if (err) { #ifdef _WIN32 (*err) = _strdup(msg.c_str()); #else (*err) = strdup(msg.c_str()); #endif } } static const int kEXRVersionSize = 8; static void cpy2(unsigned short *dst_val, const unsigned short *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; } static void swap2(unsigned short *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else unsigned short tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[1]; dst[1] = src[0]; #endif } #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #endif #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #endif static void cpy4(int *dst_val, const int *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } static void cpy4(unsigned int *dst_val, const unsigned int *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } static void cpy4(float *dst_val, const float *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __GNUC__ #pragma GCC diagnostic pop #endif static void swap4(unsigned int *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else unsigned int tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; #endif } static void swap4(int *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else int tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; #endif } static void swap4(float *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else float tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; #endif } #if 0 static void cpy8(tinyexr::tinyexr_uint64 *dst_val, const tinyexr::tinyexr_uint64 *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; dst[4] = src[4]; dst[5] = src[5]; dst[6] = src[6]; dst[7] = src[7]; } #endif static void swap8(tinyexr::tinyexr_uint64 *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else tinyexr::tinyexr_uint64 tmp = (*val); unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[7]; dst[1] = src[6]; dst[2] = src[5]; dst[3] = src[4]; dst[4] = src[3]; dst[5] = src[2]; dst[6] = src[1]; dst[7] = src[0]; #endif } // https://gist.github.com/rygorous/2156668 // Reuse MINIZ_LITTLE_ENDIAN flag from miniz. union FP32 { unsigned int u; float f; struct { #if MINIZ_LITTLE_ENDIAN unsigned int Mantissa : 23; unsigned int Exponent : 8; unsigned int Sign : 1; #else unsigned int Sign : 1; unsigned int Exponent : 8; unsigned int Mantissa : 23; #endif } s; }; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif union FP16 { unsigned short u; struct { #if MINIZ_LITTLE_ENDIAN unsigned int Mantissa : 10; unsigned int Exponent : 5; unsigned int Sign : 1; #else unsigned int Sign : 1; unsigned int Exponent : 5; unsigned int Mantissa : 10; #endif } s; }; #ifdef __clang__ #pragma clang diagnostic pop #endif static FP32 half_to_float(FP16 h) { static const FP32 magic = {113 << 23}; static const unsigned int shifted_exp = 0x7c00 << 13; // exponent mask after shift FP32 o; o.u = (h.u & 0x7fffU) << 13U; // exponent/mantissa bits unsigned int exp_ = shifted_exp & o.u; // just the exponent o.u += (127 - 15) << 23; // exponent adjust // handle exponent special cases if (exp_ == shifted_exp) // Inf/NaN? o.u += (128 - 16) << 23; // extra exp adjust else if (exp_ == 0) // Zero/Denormal? { o.u += 1 << 23; // extra exp adjust o.f -= magic.f; // renormalize } o.u |= (h.u & 0x8000U) << 16U; // sign bit return o; } static FP16 float_to_half_full(FP32 f) { FP16 o = {0}; // Based on ISPC reference code (with minor modifications) if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow) o.s.Exponent = 0; else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set) { o.s.Exponent = 31; o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf } else // Normalized number { // Exponent unbias the single, then bias the halfp int newexp = f.s.Exponent - 127 + 15; if (newexp >= 31) // Overflow, return signed infinity o.s.Exponent = 31; else if (newexp <= 0) // Underflow { if ((14 - newexp) <= 24) // Mantissa might be non-zero { unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit o.s.Mantissa = mant >> (14 - newexp); if ((mant >> (13 - newexp)) & 1) // Check for rounding o.u++; // Round, might overflow into exp bit, but this is OK } } else { o.s.Exponent = static_cast<unsigned int>(newexp); o.s.Mantissa = f.s.Mantissa >> 13; if (f.s.Mantissa & 0x1000) // Check for rounding o.u++; // Round, might overflow to inf, this is OK } } o.s.Sign = f.s.Sign; return o; } // NOTE: From OpenEXR code // #define IMF_INCREASING_Y 0 // #define IMF_DECREASING_Y 1 // #define IMF_RAMDOM_Y 2 // // #define IMF_NO_COMPRESSION 0 // #define IMF_RLE_COMPRESSION 1 // #define IMF_ZIPS_COMPRESSION 2 // #define IMF_ZIP_COMPRESSION 3 // #define IMF_PIZ_COMPRESSION 4 // #define IMF_PXR24_COMPRESSION 5 // #define IMF_B44_COMPRESSION 6 // #define IMF_B44A_COMPRESSION 7 #ifdef __clang__ #pragma clang diagnostic push #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #endif static const char *ReadString(std::string *s, const char *ptr, size_t len) { // Read untile NULL(\0). const char *p = ptr; const char *q = ptr; while ((size_t(q - ptr) < len) && (*q) != 0) { q++; } if (size_t(q - ptr) >= len) { (*s) = std::string(); return NULL; } (*s) = std::string(p, q); return q + 1; // skip '\0' } static bool ReadAttribute(std::string *name, std::string *type, std::vector<unsigned char> *data, size_t *marker_size, const char *marker, size_t size) { size_t name_len = strnlen(marker, size); if (name_len == size) { // String does not have a terminating character. return false; } *name = std::string(marker, name_len); marker += name_len + 1; size -= name_len + 1; size_t type_len = strnlen(marker, size); if (type_len == size) { return false; } *type = std::string(marker, type_len); marker += type_len + 1; size -= type_len + 1; if (size < sizeof(uint32_t)) { return false; } uint32_t data_len; memcpy(&data_len, marker, sizeof(uint32_t)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (data_len == 0) { if ((*type).compare("string") == 0) { // Accept empty string attribute. marker += sizeof(uint32_t); size -= sizeof(uint32_t); *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t); data->resize(1); (*data)[0] = '\0'; return true; } else { return false; } } marker += sizeof(uint32_t); size -= sizeof(uint32_t); if (size < data_len) { return false; } data->resize(static_cast<size_t>(data_len)); memcpy(&data->at(0), marker, static_cast<size_t>(data_len)); *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t) + data_len; return true; } static void WriteAttributeToMemory(std::vector<unsigned char> *out, const char *name, const char *type, const unsigned char *data, int len) { out->insert(out->end(), name, name + strlen(name) + 1); out->insert(out->end(), type, type + strlen(type) + 1); int outLen = len; tinyexr::swap4(&outLen); out->insert(out->end(), reinterpret_cast<unsigned char *>(&outLen), reinterpret_cast<unsigned char *>(&outLen) + sizeof(int)); out->insert(out->end(), data, data + len); } typedef struct { std::string name; // less than 255 bytes long int pixel_type; int x_sampling; int y_sampling; unsigned char p_linear; unsigned char pad[3]; } ChannelInfo; typedef struct { int min_x; int min_y; int max_x; int max_y; } Box2iInfo; struct HeaderInfo { std::vector<tinyexr::ChannelInfo> channels; std::vector<EXRAttribute> attributes; Box2iInfo data_window; int line_order; Box2iInfo display_window; float screen_window_center[2]; float screen_window_width; float pixel_aspect_ratio; int chunk_count; // Tiled format int tiled; // Non-zero if the part is tiled. int tile_size_x; int tile_size_y; int tile_level_mode; int tile_rounding_mode; unsigned int header_len; int compression_type; // required for multi-part or non-image files std::string name; // required for multi-part or non-image files std::string type; void clear() { channels.clear(); attributes.clear(); data_window.min_x = 0; data_window.min_y = 0; data_window.max_x = 0; data_window.max_y = 0; line_order = 0; display_window.min_x = 0; display_window.min_y = 0; display_window.max_x = 0; display_window.max_y = 0; screen_window_center[0] = 0.0f; screen_window_center[1] = 0.0f; screen_window_width = 0.0f; pixel_aspect_ratio = 0.0f; chunk_count = 0; // Tiled format tiled = 0; tile_size_x = 0; tile_size_y = 0; tile_level_mode = 0; tile_rounding_mode = 0; header_len = 0; compression_type = 0; name.clear(); type.clear(); } }; static bool ReadChannelInfo(std::vector<ChannelInfo> &channels, const std::vector<unsigned char> &data) { const char *p = reinterpret_cast<const char *>(&data.at(0)); for (;;) { if ((*p) == 0) { break; } ChannelInfo info; tinyexr_int64 data_len = static_cast<tinyexr_int64>(data.size()) - (p - reinterpret_cast<const char *>(data.data())); if (data_len < 0) { return false; } p = ReadString(&info.name, p, size_t(data_len)); if ((p == NULL) && (info.name.empty())) { // Buffer overrun. Issue #51. return false; } const unsigned char *data_end = reinterpret_cast<const unsigned char *>(p) + 16; if (data_end >= (data.data() + data.size())) { return false; } memcpy(&info.pixel_type, p, sizeof(int)); p += 4; info.p_linear = static_cast<unsigned char>(p[0]); // uchar p += 1 + 3; // reserved: uchar[3] memcpy(&info.x_sampling, p, sizeof(int)); // int p += 4; memcpy(&info.y_sampling, p, sizeof(int)); // int p += 4; tinyexr::swap4(&info.pixel_type); tinyexr::swap4(&info.x_sampling); tinyexr::swap4(&info.y_sampling); channels.push_back(info); } return true; } static void WriteChannelInfo(std::vector<unsigned char> &data, const std::vector<ChannelInfo> &channels) { size_t sz = 0; // Calculate total size. for (size_t c = 0; c < channels.size(); c++) { sz += strlen(channels[c].name.c_str()) + 1; // +1 for \0 sz += 16; // 4 * int } data.resize(sz + 1); unsigned char *p = &data.at(0); for (size_t c = 0; c < channels.size(); c++) { memcpy(p, channels[c].name.c_str(), strlen(channels[c].name.c_str())); p += strlen(channels[c].name.c_str()); (*p) = '\0'; p++; int pixel_type = channels[c].pixel_type; int x_sampling = channels[c].x_sampling; int y_sampling = channels[c].y_sampling; tinyexr::swap4(&pixel_type); tinyexr::swap4(&x_sampling); tinyexr::swap4(&y_sampling); memcpy(p, &pixel_type, sizeof(int)); p += sizeof(int); (*p) = channels[c].p_linear; p += 4; memcpy(p, &x_sampling, sizeof(int)); p += sizeof(int); memcpy(p, &y_sampling, sizeof(int)); p += sizeof(int); } (*p) = '\0'; } static void CompressZip(unsigned char *dst, tinyexr::tinyexr_uint64 &compressedSize, const unsigned char *src, unsigned long src_size) { std::vector<unsigned char> tmpBuf(src_size); // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfZipCompressor.cpp // // // Reorder the pixel data. // const char *srcPtr = reinterpret_cast<const char *>(src); { char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0)); char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2; const char *stop = srcPtr + src_size; for (;;) { if (srcPtr < stop) *(t1++) = *(srcPtr++); else break; if (srcPtr < stop) *(t2++) = *(srcPtr++); else break; } } // // Predictor. // { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + src_size; int p = t[-1]; while (t < stop) { int d = int(t[0]) - p + (128 + 256); p = t[0]; t[0] = static_cast<unsigned char>(d); ++t; } } #if TINYEXR_USE_MINIZ // // Compress the data using miniz // miniz::mz_ulong outSize = miniz::mz_compressBound(src_size); int ret = miniz::mz_compress( dst, &outSize, static_cast<const unsigned char *>(&tmpBuf.at(0)), src_size); assert(ret == miniz::MZ_OK); (void)ret; compressedSize = outSize; #else uLong outSize = compressBound(static_cast<uLong>(src_size)); int ret = compress(dst, &outSize, static_cast<const Bytef *>(&tmpBuf.at(0)), src_size); assert(ret == Z_OK); compressedSize = outSize; #endif // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if (compressedSize >= src_size) { compressedSize = src_size; memcpy(dst, src, src_size); } } static bool DecompressZip(unsigned char *dst, unsigned long *uncompressed_size /* inout */, const unsigned char *src, unsigned long src_size) { if ((*uncompressed_size) == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); return true; } std::vector<unsigned char> tmpBuf(*uncompressed_size); #if TINYEXR_USE_MINIZ int ret = miniz::mz_uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size); if (miniz::MZ_OK != ret) { return false; } #else int ret = uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size); if (Z_OK != ret) { return false; } #endif // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfZipCompressor.cpp // // Predictor. { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + (*uncompressed_size); while (t < stop) { int d = int(t[-1]) + int(t[0]) - 128; t[0] = static_cast<unsigned char>(d); ++t; } } // Reorder the pixel data. { const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0)); const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) + (*uncompressed_size + 1) / 2; char *s = reinterpret_cast<char *>(dst); char *stop = s + (*uncompressed_size); for (;;) { if (s < stop) *(s++) = *(t1++); else break; if (s < stop) *(s++) = *(t2++); else break; } } return true; } // RLE code from OpenEXR -------------------------------------- #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wsign-conversion" #if __has_warning("-Wextra-semi-stmt") #pragma clang diagnostic ignored "-Wextra-semi-stmt" #endif #endif #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4204) // nonstandard extension used : non-constant // aggregate initializer (also supported by GNU // C and C99, so no big deal) #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is // deprecated. Instead, use the ISO C and C++ // conformant name: _strdup. #endif const int MIN_RUN_LENGTH = 3; const int MAX_RUN_LENGTH = 127; // // Compress an array of bytes, using run-length encoding, // and return the length of the compressed data. // static int rleCompress(int inLength, const char in[], signed char out[]) { const char *inEnd = in + inLength; const char *runStart = in; const char *runEnd = in + 1; signed char *outWrite = out; while (runStart < inEnd) { while (runEnd < inEnd && *runStart == *runEnd && runEnd - runStart - 1 < MAX_RUN_LENGTH) { ++runEnd; } if (runEnd - runStart >= MIN_RUN_LENGTH) { // // Compressible run // *outWrite++ = static_cast<char>(runEnd - runStart) - 1; *outWrite++ = *(reinterpret_cast<const signed char *>(runStart)); runStart = runEnd; } else { // // Uncompressable run // while (runEnd < inEnd && ((runEnd + 1 >= inEnd || *runEnd != *(runEnd + 1)) || (runEnd + 2 >= inEnd || *(runEnd + 1) != *(runEnd + 2))) && runEnd - runStart < MAX_RUN_LENGTH) { ++runEnd; } *outWrite++ = static_cast<char>(runStart - runEnd); while (runStart < runEnd) { *outWrite++ = *(reinterpret_cast<const signed char *>(runStart++)); } } ++runEnd; } return static_cast<int>(outWrite - out); } // // Uncompress an array of bytes compressed with rleCompress(). // Returns the length of the oncompressed data, or 0 if the // length of the uncompressed data would be more than maxLength. // static int rleUncompress(int inLength, int maxLength, const signed char in[], char out[]) { char *outStart = out; while (inLength > 0) { if (*in < 0) { int count = -(static_cast<int>(*in++)); inLength -= count + 1; // Fixes #116: Add bounds check to in buffer. if ((0 > (maxLength -= count)) || (inLength < 0)) return 0; memcpy(out, in, count); out += count; in += count; } else { int count = *in++; inLength -= 2; if (0 > (maxLength -= count + 1)) return 0; memset(out, *reinterpret_cast<const char *>(in), count + 1); out += count + 1; in++; } } return static_cast<int>(out - outStart); } #ifdef __clang__ #pragma clang diagnostic pop #endif // End of RLE code from OpenEXR ----------------------------------- static void CompressRle(unsigned char *dst, tinyexr::tinyexr_uint64 &compressedSize, const unsigned char *src, unsigned long src_size) { std::vector<unsigned char> tmpBuf(src_size); // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfRleCompressor.cpp // // // Reorder the pixel data. // const char *srcPtr = reinterpret_cast<const char *>(src); { char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0)); char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2; const char *stop = srcPtr + src_size; for (;;) { if (srcPtr < stop) *(t1++) = *(srcPtr++); else break; if (srcPtr < stop) *(t2++) = *(srcPtr++); else break; } } // // Predictor. // { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + src_size; int p = t[-1]; while (t < stop) { int d = int(t[0]) - p + (128 + 256); p = t[0]; t[0] = static_cast<unsigned char>(d); ++t; } } // outSize will be (srcSiz * 3) / 2 at max. int outSize = rleCompress(static_cast<int>(src_size), reinterpret_cast<const char *>(&tmpBuf.at(0)), reinterpret_cast<signed char *>(dst)); assert(outSize > 0); compressedSize = static_cast<tinyexr::tinyexr_uint64>(outSize); // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if (compressedSize >= src_size) { compressedSize = src_size; memcpy(dst, src, src_size); } } static bool DecompressRle(unsigned char *dst, const unsigned long uncompressed_size, const unsigned char *src, unsigned long src_size) { if (uncompressed_size == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); return true; } // Workaround for issue #112. // TODO(syoyo): Add more robust out-of-bounds check in `rleUncompress`. if (src_size <= 2) { return false; } std::vector<unsigned char> tmpBuf(uncompressed_size); int ret = rleUncompress(static_cast<int>(src_size), static_cast<int>(uncompressed_size), reinterpret_cast<const signed char *>(src), reinterpret_cast<char *>(&tmpBuf.at(0))); if (ret != static_cast<int>(uncompressed_size)) { return false; } // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfRleCompressor.cpp // // Predictor. { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + uncompressed_size; while (t < stop) { int d = int(t[-1]) + int(t[0]) - 128; t[0] = static_cast<unsigned char>(d); ++t; } } // Reorder the pixel data. { const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0)); const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) + (uncompressed_size + 1) / 2; char *s = reinterpret_cast<char *>(dst); char *stop = s + uncompressed_size; for (;;) { if (s < stop) *(s++) = *(t1++); else break; if (s < stop) *(s++) = *(t2++); else break; } } return true; } #if TINYEXR_USE_PIZ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wc++11-extensions" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #if __has_warning("-Wextra-semi-stmt") #pragma clang diagnostic ignored "-Wextra-semi-stmt" #endif #endif // // PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp // // ----------------------------------------------------------------- // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC) // (3 clause BSD license) // struct PIZChannelData { unsigned short *start; unsigned short *end; int nx; int ny; int ys; int size; }; //----------------------------------------------------------------------------- // // 16-bit Haar Wavelet encoding and decoding // // The source code in this file is derived from the encoding // and decoding routines written by Christian Rouet for his // PIZ image file format. // //----------------------------------------------------------------------------- // // Wavelet basis functions without modulo arithmetic; they produce // the best compression ratios when the wavelet-transformed data are // Huffman-encoded, but the wavelet transform works only for 14-bit // data (untransformed data values must be less than (1 << 14)). // inline void wenc14(unsigned short a, unsigned short b, unsigned short &l, unsigned short &h) { short as = static_cast<short>(a); short bs = static_cast<short>(b); short ms = (as + bs) >> 1; short ds = as - bs; l = static_cast<unsigned short>(ms); h = static_cast<unsigned short>(ds); } inline void wdec14(unsigned short l, unsigned short h, unsigned short &a, unsigned short &b) { short ls = static_cast<short>(l); short hs = static_cast<short>(h); int hi = hs; int ai = ls + (hi & 1) + (hi >> 1); short as = static_cast<short>(ai); short bs = static_cast<short>(ai - hi); a = static_cast<unsigned short>(as); b = static_cast<unsigned short>(bs); } // // Wavelet basis functions with modulo arithmetic; they work with full // 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't // compress the data quite as well. // const int NBITS = 16; const int A_OFFSET = 1 << (NBITS - 1); const int M_OFFSET = 1 << (NBITS - 1); const int MOD_MASK = (1 << NBITS) - 1; inline void wenc16(unsigned short a, unsigned short b, unsigned short &l, unsigned short &h) { int ao = (a + A_OFFSET) & MOD_MASK; int m = ((ao + b) >> 1); int d = ao - b; if (d < 0) m = (m + M_OFFSET) & MOD_MASK; d &= MOD_MASK; l = static_cast<unsigned short>(m); h = static_cast<unsigned short>(d); } inline void wdec16(unsigned short l, unsigned short h, unsigned short &a, unsigned short &b) { int m = l; int d = h; int bb = (m - (d >> 1)) & MOD_MASK; int aa = (d + bb - A_OFFSET) & MOD_MASK; b = static_cast<unsigned short>(bb); a = static_cast<unsigned short>(aa); } // // 2D Wavelet encoding: // static void wav2Encode( unsigned short *in, // io: values are transformed in place int nx, // i : x size int ox, // i : x offset int ny, // i : y size int oy, // i : y offset unsigned short mx) // i : maximum in[x][y] value { bool w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; // == 1 << level int p2 = 2; // == 1 << (level+1) // // Hierarchical loop on smaller dimension n // while (p2 <= n) { unsigned short *py = in; unsigned short *ey = in + oy * (ny - p2); int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; unsigned short i00, i01, i10, i11; // // Y loop // for (; py <= ey; py += oy2) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); // // X loop // for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; unsigned short *p10 = px + oy1; unsigned short *p11 = p10 + ox1; // // 2D wavelet encoding // if (w14) { wenc14(*px, *p01, i00, i01); wenc14(*p10, *p11, i10, i11); wenc14(i00, i10, *px, *p10); wenc14(i01, i11, *p01, *p11); } else { wenc16(*px, *p01, i00, i01); wenc16(*p10, *p11, i10, i11); wenc16(i00, i10, *px, *p10); wenc16(i01, i11, *p01, *p11); } } // // Encode (1D) odd column (still in Y loop) // if (nx & p) { unsigned short *p10 = px + oy1; if (w14) wenc14(*px, *p10, i00, *p10); else wenc16(*px, *p10, i00, *p10); *px = i00; } } // // Encode (1D) odd line (must loop in X) // if (ny & p) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; if (w14) wenc14(*px, *p01, i00, *p01); else wenc16(*px, *p01, i00, *p01); *px = i00; } } // // Next level // p = p2; p2 <<= 1; } } // // 2D Wavelet decoding: // static void wav2Decode( unsigned short *in, // io: values are transformed in place int nx, // i : x size int ox, // i : x offset int ny, // i : y size int oy, // i : y offset unsigned short mx) // i : maximum in[x][y] value { bool w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; int p2; // // Search max level // while (p <= n) p <<= 1; p >>= 1; p2 = p; p >>= 1; // // Hierarchical loop on smaller dimension n // while (p >= 1) { unsigned short *py = in; unsigned short *ey = in + oy * (ny - p2); int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; unsigned short i00, i01, i10, i11; // // Y loop // for (; py <= ey; py += oy2) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); // // X loop // for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; unsigned short *p10 = px + oy1; unsigned short *p11 = p10 + ox1; // // 2D wavelet decoding // if (w14) { wdec14(*px, *p10, i00, i10); wdec14(*p01, *p11, i01, i11); wdec14(i00, i01, *px, *p01); wdec14(i10, i11, *p10, *p11); } else { wdec16(*px, *p10, i00, i10); wdec16(*p01, *p11, i01, i11); wdec16(i00, i01, *px, *p01); wdec16(i10, i11, *p10, *p11); } } // // Decode (1D) odd column (still in Y loop) // if (nx & p) { unsigned short *p10 = px + oy1; if (w14) wdec14(*px, *p10, i00, *p10); else wdec16(*px, *p10, i00, *p10); *px = i00; } } // // Decode (1D) odd line (must loop in X) // if (ny & p) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; if (w14) wdec14(*px, *p01, i00, *p01); else wdec16(*px, *p01, i00, *p01); *px = i00; } } // // Next level // p2 = p; p >>= 1; } } //----------------------------------------------------------------------------- // // 16-bit Huffman compression and decompression. // // The source code in this file is derived from the 8-bit // Huffman compression and decompression routines written // by Christian Rouet for his PIZ image file format. // //----------------------------------------------------------------------------- // Adds some modification for tinyexr. const int HUF_ENCBITS = 16; // literal (value) bit length const int HUF_DECBITS = 14; // decoding bit size (>= 8) const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size const int HUF_DECMASK = HUF_DECSIZE - 1; struct HufDec { // short code long code //------------------------------- unsigned int len : 8; // code length 0 unsigned int lit : 24; // lit p size unsigned int *p; // 0 lits }; inline long long hufLength(long long code) { return code & 63; } inline long long hufCode(long long code) { return code >> 6; } inline void outputBits(int nBits, long long bits, long long &c, int &lc, char *&out) { c <<= nBits; lc += nBits; c |= bits; while (lc >= 8) *out++ = static_cast<char>((c >> (lc -= 8))); } inline long long getBits(int nBits, long long &c, int &lc, const char *&in) { while (lc < nBits) { c = (c << 8) | *(reinterpret_cast<const unsigned char *>(in++)); lc += 8; } lc -= nBits; return (c >> lc) & ((1 << nBits) - 1); } // // ENCODING TABLE BUILDING & (UN)PACKING // // // Build a "canonical" Huffman code table: // - for each (uncompressed) symbol, hcode contains the length // of the corresponding code (in the compressed data) // - canonical codes are computed and stored in hcode // - the rules for constructing canonical codes are as follows: // * shorter codes (if filled with zeroes to the right) // have a numerically higher value than longer codes // * for codes with the same length, numerical values // increase with numerical symbol values // - because the canonical code table can be constructed from // symbol lengths alone, the code table can be transmitted // without sending the actual code values // - see http://www.compressconsult.com/huffman/ // static void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) { long long n[59]; // // For each i from 0 through 58, count the // number of different codes of length i, and // store the count in n[i]. // for (int i = 0; i <= 58; ++i) n[i] = 0; for (int i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1; // // For each i from 58 through 1, compute the // numerically lowest code with length i, and // store that code in n[i]. // long long c = 0; for (int i = 58; i > 0; --i) { long long nc = ((c + n[i]) >> 1); n[i] = c; c = nc; } // // hcode[i] contains the length, l, of the // code for symbol i. Assign the next available // code of length l to the symbol and store both // l and the code in hcode[i]. // for (int i = 0; i < HUF_ENCSIZE; ++i) { int l = static_cast<int>(hcode[i]); if (l > 0) hcode[i] = l | (n[l]++ << 6); } } // // Compute Huffman codes (based on frq input) and store them in frq: // - code structure is : [63:lsb - 6:msb] | [5-0: bit length]; // - max code length is 58 bits; // - codes outside the range [im-iM] have a null length (unused values); // - original frequencies are destroyed; // - encoding tables are used by hufEncode() and hufBuildDecTable(); // struct FHeapCompare { bool operator()(long long *a, long long *b) { return *a > *b; } }; static void hufBuildEncTable( long long *frq, // io: input frequencies [HUF_ENCSIZE], output table int *im, // o: min frq index int *iM) // o: max frq index { // // This function assumes that when it is called, array frq // indicates the frequency of all possible symbols in the data // that are to be Huffman-encoded. (frq[i] contains the number // of occurrences of symbol i in the data.) // // The loop below does three things: // // 1) Finds the minimum and maximum indices that point // to non-zero entries in frq: // // frq[im] != 0, and frq[i] == 0 for all i < im // frq[iM] != 0, and frq[i] == 0 for all i > iM // // 2) Fills array fHeap with pointers to all non-zero // entries in frq. // // 3) Initializes array hlink such that hlink[i] == i // for all array entries. // std::vector<int> hlink(HUF_ENCSIZE); std::vector<long long *> fHeap(HUF_ENCSIZE); *im = 0; while (!frq[*im]) (*im)++; int nf = 0; for (int i = *im; i < HUF_ENCSIZE; i++) { hlink[i] = i; if (frq[i]) { fHeap[nf] = &frq[i]; nf++; *iM = i; } } // // Add a pseudo-symbol, with a frequency count of 1, to frq; // adjust the fHeap and hlink array accordingly. Function // hufEncode() uses the pseudo-symbol for run-length encoding. // (*iM)++; frq[*iM] = 1; fHeap[nf] = &frq[*iM]; nf++; // // Build an array, scode, such that scode[i] contains the number // of bits assigned to symbol i. Conceptually this is done by // constructing a tree whose leaves are the symbols with non-zero // frequency: // // Make a heap that contains all symbols with a non-zero frequency, // with the least frequent symbol on top. // // Repeat until only one symbol is left on the heap: // // Take the two least frequent symbols off the top of the heap. // Create a new node that has first two nodes as children, and // whose frequency is the sum of the frequencies of the first // two nodes. Put the new node back into the heap. // // The last node left on the heap is the root of the tree. For each // leaf node, the distance between the root and the leaf is the length // of the code for the corresponding symbol. // // The loop below doesn't actually build the tree; instead we compute // the distances of the leaves from the root on the fly. When a new // node is added to the heap, then that node's descendants are linked // into a single linear list that starts at the new node, and the code // lengths of the descendants (that is, their distance from the root // of the tree) are incremented by one. // std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); std::vector<long long> scode(HUF_ENCSIZE); memset(scode.data(), 0, sizeof(long long) * HUF_ENCSIZE); while (nf > 1) { // // Find the indices, mm and m, of the two smallest non-zero frq // values in fHeap, add the smallest frq to the second-smallest // frq, and remove the smallest frq value from fHeap. // int mm = fHeap[0] - frq; std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); --nf; int m = fHeap[0] - frq; std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); frq[m] += frq[mm]; std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); // // The entries in scode are linked into lists with the // entries in hlink serving as "next" pointers and with // the end of a list marked by hlink[j] == j. // // Traverse the lists that start at scode[m] and scode[mm]. // For each element visited, increment the length of the // corresponding code by one bit. (If we visit scode[j] // during the traversal, then the code for symbol j becomes // one bit longer.) // // Merge the lists that start at scode[m] and scode[mm] // into a single list that starts at scode[m]. // // // Add a bit to all codes in the first list. // for (int j = m;; j = hlink[j]) { scode[j]++; assert(scode[j] <= 58); if (hlink[j] == j) { // // Merge the two lists. // hlink[j] = mm; break; } } // // Add a bit to all codes in the second list // for (int j = mm;; j = hlink[j]) { scode[j]++; assert(scode[j] <= 58); if (hlink[j] == j) break; } } // // Build a canonical Huffman code table, replacing the code // lengths in scode with (code, code length) pairs. Copy the // code table from scode into frq. // hufCanonicalCodeTable(scode.data()); memcpy(frq, scode.data(), sizeof(long long) * HUF_ENCSIZE); } // // Pack an encoding table: // - only code lengths, not actual codes, are stored // - runs of zeroes are compressed as follows: // // unpacked packed // -------------------------------- // 1 zero 0 (6 bits) // 2 zeroes 59 // 3 zeroes 60 // 4 zeroes 61 // 5 zeroes 62 // n zeroes (6 or more) 63 n-6 (6 + 8 bits) // const int SHORT_ZEROCODE_RUN = 59; const int LONG_ZEROCODE_RUN = 63; const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN; const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN; static void hufPackEncTable( const long long *hcode, // i : encoding table [HUF_ENCSIZE] int im, // i : min hcode index int iM, // i : max hcode index char **pcode) // o: ptr to packed table (updated) { char *p = *pcode; long long c = 0; int lc = 0; for (; im <= iM; im++) { int l = hufLength(hcode[im]); if (l == 0) { int zerun = 1; while ((im < iM) && (zerun < LONGEST_LONG_RUN)) { if (hufLength(hcode[im + 1]) > 0) break; im++; zerun++; } if (zerun >= 2) { if (zerun >= SHORTEST_LONG_RUN) { outputBits(6, LONG_ZEROCODE_RUN, c, lc, p); outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p); } else { outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p); } continue; } } outputBits(6, l, c, lc, p); } if (lc > 0) *p++ = uint8_t(c << (8 - lc)); *pcode = p; } // // Unpack an encoding table packed by hufPackEncTable(): // static bool hufUnpackEncTable( const char **pcode, // io: ptr to packed table (updated) int ni, // i : input size (in bytes) int im, // i : min hcode index int iM, // i : max hcode index long long *hcode) // o: encoding table [HUF_ENCSIZE] { memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE); const char *p = *pcode; long long c = 0; int lc = 0; for (; im <= iM; im++) { if (p - *pcode >= ni) { return false; } long long l = hcode[im] = getBits(6, c, lc, p); // code length if (l == static_cast<long long>(LONG_ZEROCODE_RUN)) { if (p - *pcode > ni) { return false; } int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN; if (im + zerun > iM + 1) { return false; } while (zerun--) hcode[im++] = 0; im--; } else if (l >= static_cast<long long>(SHORT_ZEROCODE_RUN)) { int zerun = l - SHORT_ZEROCODE_RUN + 2; if (im + zerun > iM + 1) { return false; } while (zerun--) hcode[im++] = 0; im--; } } *pcode = const_cast<char *>(p); hufCanonicalCodeTable(hcode); return true; } // // DECODING TABLE BUILDING // // // Clear a newly allocated decoding table so that it contains only zeroes. // static void hufClearDecTable(HufDec *hdecod) // io: (allocated by caller) // decoding table [HUF_DECSIZE] { for (int i = 0; i < HUF_DECSIZE; i++) { hdecod[i].len = 0; hdecod[i].lit = 0; hdecod[i].p = NULL; } // memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE); } // // Build a decoding hash table based on the encoding table hcode: // - short codes (<= HUF_DECBITS) are resolved with a single table access; // - long code entry allocations are not optimized, because long codes are // unfrequent; // - decoding tables are used by hufDecode(); // static bool hufBuildDecTable(const long long *hcode, // i : encoding table int im, // i : min index in hcode int iM, // i : max index in hcode HufDec *hdecod) // o: (allocated by caller) // decoding table [HUF_DECSIZE] { // // Init hashtable & loop on all codes. // Assumes that hufClearDecTable(hdecod) has already been called. // for (; im <= iM; im++) { long long c = hufCode(hcode[im]); int l = hufLength(hcode[im]); if (c >> l) { // // Error: c is supposed to be an l-bit code, // but c contains a value that is greater // than the largest l-bit number. // // invalidTableEntry(); return false; } if (l > HUF_DECBITS) { // // Long code: add a secondary entry // HufDec *pl = hdecod + (c >> (l - HUF_DECBITS)); if (pl->len) { // // Error: a short code has already // been stored in table entry *pl. // // invalidTableEntry(); return false; } pl->lit++; if (pl->p) { unsigned int *p = pl->p; pl->p = new unsigned int[pl->lit]; for (int i = 0; i < pl->lit - 1; ++i) pl->p[i] = p[i]; delete[] p; } else { pl->p = new unsigned int[1]; } pl->p[pl->lit - 1] = im; } else if (l) { // // Short code: init all primary entries // HufDec *pl = hdecod + (c << (HUF_DECBITS - l)); for (long long i = 1ULL << (HUF_DECBITS - l); i > 0; i--, pl++) { if (pl->len || pl->p) { // // Error: a short code or a long code has // already been stored in table entry *pl. // // invalidTableEntry(); return false; } pl->len = l; pl->lit = im; } } } return true; } // // Free the long code entries of a decoding table built by hufBuildDecTable() // static void hufFreeDecTable(HufDec *hdecod) // io: Decoding table { for (int i = 0; i < HUF_DECSIZE; i++) { if (hdecod[i].p) { delete[] hdecod[i].p; hdecod[i].p = 0; } } } // // ENCODING // inline void outputCode(long long code, long long &c, int &lc, char *&out) { outputBits(hufLength(code), hufCode(code), c, lc, out); } inline void sendCode(long long sCode, int runCount, long long runCode, long long &c, int &lc, char *&out) { // // Output a run of runCount instances of the symbol sCount. // Output the symbols explicitly, or if that is shorter, output // the sCode symbol once followed by a runCode symbol and runCount // expressed as an 8-bit number. // if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) { outputCode(sCode, c, lc, out); outputCode(runCode, c, lc, out); outputBits(8, runCount, c, lc, out); } else { while (runCount-- >= 0) outputCode(sCode, c, lc, out); } } // // Encode (compress) ni values based on the Huffman encoding table hcode: // static int hufEncode // return: output size (in bits) (const long long *hcode, // i : encoding table const unsigned short *in, // i : uncompressed input buffer const int ni, // i : input buffer size (in bytes) int rlc, // i : rl code char *out) // o: compressed output buffer { char *outStart = out; long long c = 0; // bits not yet written to out int lc = 0; // number of valid bits in c (LSB) int s = in[0]; int cs = 0; // // Loop on input values // for (int i = 1; i < ni; i++) { // // Count same values or send code // if (s == in[i] && cs < 255) { cs++; } else { sendCode(hcode[s], cs, hcode[rlc], c, lc, out); cs = 0; } s = in[i]; } // // Send remaining code // sendCode(hcode[s], cs, hcode[rlc], c, lc, out); if (lc) *out = (c << (8 - lc)) & 0xff; return (out - outStart) * 8 + lc; } // // DECODING // // // In order to force the compiler to inline them, // getChar() and getCode() are implemented as macros // instead of "inline" functions. // #define getChar(c, lc, in) \ { \ c = (c << 8) | *reinterpret_cast<const unsigned char *>(in++); \ lc += 8; \ } #if 0 #define getCode(po, rlc, c, lc, in, out, ob, oe) \ { \ if (po == rlc) { \ if (lc < 8) getChar(c, lc, in); \ \ lc -= 8; \ \ unsigned char cs = (c >> lc); \ \ if (out + cs > oe) return false; \ \ /* TinyEXR issue 78 */ \ unsigned short s = out[-1]; \ \ while (cs-- > 0) *out++ = s; \ } else if (out < oe) { \ *out++ = po; \ } else { \ return false; \ } \ } #else static bool getCode(int po, int rlc, long long &c, int &lc, const char *&in, const char *in_end, unsigned short *&out, const unsigned short *ob, const unsigned short *oe) { (void)ob; if (po == rlc) { if (lc < 8) { /* TinyEXR issue 78 */ if ((in + 1) >= in_end) { return false; } getChar(c, lc, in); } lc -= 8; unsigned char cs = (c >> lc); if (out + cs > oe) return false; // Bounds check for safety // Issue 100. if ((out - 1) < ob) return false; unsigned short s = out[-1]; while (cs-- > 0) *out++ = s; } else if (out < oe) { *out++ = po; } else { return false; } return true; } #endif // // Decode (uncompress) ni bits based on encoding & decoding tables: // static bool hufDecode(const long long *hcode, // i : encoding table const HufDec *hdecod, // i : decoding table const char *in, // i : compressed input buffer int ni, // i : input size (in bits) int rlc, // i : run-length code int no, // i : expected output size (in bytes) unsigned short *out) // o: uncompressed output buffer { long long c = 0; int lc = 0; unsigned short *outb = out; // begin unsigned short *oe = out + no; // end const char *ie = in + (ni + 7) / 8; // input byte size // // Loop on input bytes // while (in < ie) { getChar(c, lc, in); // // Access decoding table // while (lc >= HUF_DECBITS) { const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK]; if (pl.len) { // // Get short code // lc -= pl.len; // std::cout << "lit = " << pl.lit << std::endl; // std::cout << "rlc = " << rlc << std::endl; // std::cout << "c = " << c << std::endl; // std::cout << "lc = " << lc << std::endl; // std::cout << "in = " << in << std::endl; // std::cout << "out = " << out << std::endl; // std::cout << "oe = " << oe << std::endl; if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) { return false; } } else { if (!pl.p) { return false; } // invalidCode(); // wrong code // // Search long code // int j; for (j = 0; j < pl.lit; j++) { int l = hufLength(hcode[pl.p[j]]); while (lc < l && in < ie) // get more bits getChar(c, lc, in); if (lc >= l) { if (hufCode(hcode[pl.p[j]]) == ((c >> (lc - l)) & ((1ll << l) - 1))) { // // Found : get long code // lc -= l; if (!getCode(pl.p[j], rlc, c, lc, in, ie, out, outb, oe)) { return false; } break; } } } if (j == pl.lit) { return false; // invalidCode(); // Not found } } } } // // Get remaining (short) codes // int i = (8 - ni) & 7; c >>= i; lc -= i; while (lc > 0) { const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK]; if (pl.len) { lc -= pl.len; if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) { return false; } } else { return false; // invalidCode(); // wrong (long) code } } if (out - outb != no) { return false; } // notEnoughData (); return true; } static void countFrequencies(std::vector<long long> &freq, const unsigned short data[/*n*/], int n) { for (int i = 0; i < HUF_ENCSIZE; ++i) freq[i] = 0; for (int i = 0; i < n; ++i) ++freq[data[i]]; } static void writeUInt(char buf[4], unsigned int i) { unsigned char *b = reinterpret_cast<unsigned char *>(buf); b[0] = i; b[1] = i >> 8; b[2] = i >> 16; b[3] = i >> 24; } static unsigned int readUInt(const char buf[4]) { const unsigned char *b = reinterpret_cast<const unsigned char *>(buf); return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) | ((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000); } // // EXTERNAL INTERFACE // static int hufCompress(const unsigned short raw[], int nRaw, char compressed[]) { if (nRaw == 0) return 0; std::vector<long long> freq(HUF_ENCSIZE); countFrequencies(freq, raw, nRaw); int im = 0; int iM = 0; hufBuildEncTable(freq.data(), &im, &iM); char *tableStart = compressed + 20; char *tableEnd = tableStart; hufPackEncTable(freq.data(), im, iM, &tableEnd); int tableLength = tableEnd - tableStart; char *dataStart = tableEnd; int nBits = hufEncode(freq.data(), raw, nRaw, iM, dataStart); int data_length = (nBits + 7) / 8; writeUInt(compressed, im); writeUInt(compressed + 4, iM); writeUInt(compressed + 8, tableLength); writeUInt(compressed + 12, nBits); writeUInt(compressed + 16, 0); // room for future extensions return dataStart + data_length - compressed; } static bool hufUncompress(const char compressed[], int nCompressed, std::vector<unsigned short> *raw) { if (nCompressed == 0) { if (raw->size() != 0) return false; return false; } int im = readUInt(compressed); int iM = readUInt(compressed + 4); // int tableLength = readUInt (compressed + 8); int nBits = readUInt(compressed + 12); if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) return false; const char *ptr = compressed + 20; // // Fast decoder needs at least 2x64-bits of compressed data, and // needs to be run-able on this platform. Otherwise, fall back // to the original decoder // // if (FastHufDecoder::enabled() && nBits > 128) //{ // FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM); // fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw); //} // else { std::vector<long long> freq(HUF_ENCSIZE); std::vector<HufDec> hdec(HUF_DECSIZE); hufClearDecTable(&hdec.at(0)); hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM, &freq.at(0)); { if (nBits > 8 * (nCompressed - (ptr - compressed))) { return false; } hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0)); hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, raw->size(), raw->data()); } // catch (...) //{ // hufFreeDecTable (hdec); // throw; //} hufFreeDecTable(&hdec.at(0)); } return true; } // // Functions to compress the range of values in the pixel data // const int USHORT_RANGE = (1 << 16); const int BITMAP_SIZE = (USHORT_RANGE >> 3); static void bitmapFromData(const unsigned short data[/*nData*/], int nData, unsigned char bitmap[BITMAP_SIZE], unsigned short &minNonZero, unsigned short &maxNonZero) { for (int i = 0; i < BITMAP_SIZE; ++i) bitmap[i] = 0; for (int i = 0; i < nData; ++i) bitmap[data[i] >> 3] |= (1 << (data[i] & 7)); bitmap[0] &= ~1; // zero is not explicitly stored in // the bitmap; we assume that the // data always contain zeroes minNonZero = BITMAP_SIZE - 1; maxNonZero = 0; for (int i = 0; i < BITMAP_SIZE; ++i) { if (bitmap[i]) { if (minNonZero > i) minNonZero = i; if (maxNonZero < i) maxNonZero = i; } } } static unsigned short forwardLutFromBitmap( const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) { int k = 0; for (int i = 0; i < USHORT_RANGE; ++i) { if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[i] = k++; else lut[i] = 0; } return k - 1; // maximum value stored in lut[], } // i.e. number of ones in bitmap minus 1 static unsigned short reverseLutFromBitmap( const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) { int k = 0; for (int i = 0; i < USHORT_RANGE; ++i) { if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[k++] = i; } int n = k - 1; while (k < USHORT_RANGE) lut[k++] = 0; return n; // maximum k where lut[k] is non-zero, } // i.e. number of ones in bitmap minus 1 static void applyLut(const unsigned short lut[USHORT_RANGE], unsigned short data[/*nData*/], int nData) { for (int i = 0; i < nData; ++i) data[i] = lut[data[i]]; } #ifdef __clang__ #pragma clang diagnostic pop #endif // __clang__ #ifdef _MSC_VER #pragma warning(pop) #endif static bool CompressPiz(unsigned char *outPtr, unsigned int *outSize, const unsigned char *inPtr, size_t inSize, const std::vector<ChannelInfo> &channelInfo, int data_width, int num_lines) { std::vector<unsigned char> bitmap(BITMAP_SIZE); unsigned short minNonZero; unsigned short maxNonZero; #if !MINIZ_LITTLE_ENDIAN // @todo { PIZ compression on BigEndian architecture. } assert(0); return false; #endif // Assume `inSize` is multiple of 2 or 4. std::vector<unsigned short> tmpBuffer(inSize / sizeof(unsigned short)); std::vector<PIZChannelData> channelData(channelInfo.size()); unsigned short *tmpBufferEnd = &tmpBuffer.at(0); for (size_t c = 0; c < channelData.size(); c++) { PIZChannelData &cd = channelData[c]; cd.start = tmpBufferEnd; cd.end = cd.start; cd.nx = data_width; cd.ny = num_lines; // cd.ys = c.channel().ySampling; size_t pixelSize = sizeof(int); // UINT and FLOAT if (channelInfo[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { pixelSize = sizeof(short); } cd.size = static_cast<int>(pixelSize / sizeof(short)); tmpBufferEnd += cd.nx * cd.ny * cd.size; } const unsigned char *ptr = inPtr; for (int y = 0; y < num_lines; ++y) { for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; // if (modp (y, cd.ys) != 0) // continue; size_t n = static_cast<size_t>(cd.nx * cd.size); memcpy(cd.end, ptr, n * sizeof(unsigned short)); ptr += n * sizeof(unsigned short); cd.end += n; } } bitmapFromData(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), bitmap.data(), minNonZero, maxNonZero); std::vector<unsigned short> lut(USHORT_RANGE); unsigned short maxValue = forwardLutFromBitmap(bitmap.data(), lut.data()); applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBuffer.size())); // // Store range compression info in _outBuffer // char *buf = reinterpret_cast<char *>(outPtr); memcpy(buf, &minNonZero, sizeof(unsigned short)); buf += sizeof(unsigned short); memcpy(buf, &maxNonZero, sizeof(unsigned short)); buf += sizeof(unsigned short); if (minNonZero <= maxNonZero) { memcpy(buf, reinterpret_cast<char *>(&bitmap[0] + minNonZero), maxNonZero - minNonZero + 1); buf += maxNonZero - minNonZero + 1; } // // Apply wavelet encoding // for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; for (int j = 0; j < cd.size; ++j) { wav2Encode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } // // Apply Huffman encoding; append the result to _outBuffer // // length header(4byte), then huff data. Initialize length header with zero, // then later fill it by `length`. char *lengthPtr = buf; int zero = 0; memcpy(buf, &zero, sizeof(int)); buf += sizeof(int); int length = hufCompress(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), buf); memcpy(lengthPtr, &length, sizeof(int)); (*outSize) = static_cast<unsigned int>( (reinterpret_cast<unsigned char *>(buf) - outPtr) + static_cast<unsigned int>(length)); // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if ((*outSize) >= inSize) { (*outSize) = static_cast<unsigned int>(inSize); memcpy(outPtr, inPtr, inSize); } return true; } static bool DecompressPiz(unsigned char *outPtr, const unsigned char *inPtr, size_t tmpBufSize, size_t inLen, int num_channels, const EXRChannelInfo *channels, int data_width, int num_lines) { if (inLen == tmpBufSize) { // Data is not compressed(Issue 40). memcpy(outPtr, inPtr, inLen); return true; } std::vector<unsigned char> bitmap(BITMAP_SIZE); unsigned short minNonZero; unsigned short maxNonZero; #if !MINIZ_LITTLE_ENDIAN // @todo { PIZ compression on BigEndian architecture. } assert(0); return false; #endif memset(bitmap.data(), 0, BITMAP_SIZE); const unsigned char *ptr = inPtr; // minNonZero = *(reinterpret_cast<const unsigned short *>(ptr)); tinyexr::cpy2(&minNonZero, reinterpret_cast<const unsigned short *>(ptr)); // maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2)); tinyexr::cpy2(&maxNonZero, reinterpret_cast<const unsigned short *>(ptr + 2)); ptr += 4; if (maxNonZero >= BITMAP_SIZE) { return false; } if (minNonZero <= maxNonZero) { memcpy(reinterpret_cast<char *>(&bitmap[0] + minNonZero), ptr, maxNonZero - minNonZero + 1); ptr += maxNonZero - minNonZero + 1; } std::vector<unsigned short> lut(USHORT_RANGE); memset(lut.data(), 0, sizeof(unsigned short) * USHORT_RANGE); unsigned short maxValue = reverseLutFromBitmap(bitmap.data(), lut.data()); // // Huffman decoding // int length; // length = *(reinterpret_cast<const int *>(ptr)); tinyexr::cpy4(&length, reinterpret_cast<const int *>(ptr)); ptr += sizeof(int); if (size_t((ptr - inPtr) + length) > inLen) { return false; } std::vector<unsigned short> tmpBuffer(tmpBufSize); hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer); // // Wavelet decoding // std::vector<PIZChannelData> channelData(static_cast<size_t>(num_channels)); unsigned short *tmpBufferEnd = &tmpBuffer.at(0); for (size_t i = 0; i < static_cast<size_t>(num_channels); ++i) { const EXRChannelInfo &chan = channels[i]; size_t pixelSize = sizeof(int); // UINT and FLOAT if (chan.pixel_type == TINYEXR_PIXELTYPE_HALF) { pixelSize = sizeof(short); } channelData[i].start = tmpBufferEnd; channelData[i].end = channelData[i].start; channelData[i].nx = data_width; channelData[i].ny = num_lines; // channelData[i].ys = 1; channelData[i].size = static_cast<int>(pixelSize / sizeof(short)); tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size; } for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; for (int j = 0; j < cd.size; ++j) { wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } // // Expand the pixel data to their original range // applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBufSize)); for (int y = 0; y < num_lines; y++) { for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; // if (modp (y, cd.ys) != 0) // continue; size_t n = static_cast<size_t>(cd.nx * cd.size); memcpy(outPtr, cd.end, static_cast<size_t>(n * sizeof(unsigned short))); outPtr += n * sizeof(unsigned short); cd.end += n; } } return true; } #endif // TINYEXR_USE_PIZ #if TINYEXR_USE_ZFP struct ZFPCompressionParam { double rate; unsigned int precision; unsigned int __pad0; double tolerance; int type; // TINYEXR_ZFP_COMPRESSIONTYPE_* unsigned int __pad1; ZFPCompressionParam() { type = TINYEXR_ZFP_COMPRESSIONTYPE_RATE; rate = 2.0; precision = 0; tolerance = 0.0; } }; static bool FindZFPCompressionParam(ZFPCompressionParam *param, const EXRAttribute *attributes, int num_attributes, std::string *err) { bool foundType = false; for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionType") == 0)) { if (attributes[i].size == 1) { param->type = static_cast<int>(attributes[i].value[0]); foundType = true; break; } else { if (err) { (*err) += "zfpCompressionType attribute must be uchar(1 byte) type.\n"; } return false; } } } if (!foundType) { if (err) { (*err) += "`zfpCompressionType` attribute not found.\n"; } return false; } if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionRate") == 0) && (attributes[i].size == 8)) { param->rate = *(reinterpret_cast<double *>(attributes[i].value)); return true; } } if (err) { (*err) += "`zfpCompressionRate` attribute not found.\n"; } } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionPrecision") == 0) && (attributes[i].size == 4)) { param->rate = *(reinterpret_cast<int *>(attributes[i].value)); return true; } } if (err) { (*err) += "`zfpCompressionPrecision` attribute not found.\n"; } } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionTolerance") == 0) && (attributes[i].size == 8)) { param->tolerance = *(reinterpret_cast<double *>(attributes[i].value)); return true; } } if (err) { (*err) += "`zfpCompressionTolerance` attribute not found.\n"; } } else { if (err) { (*err) += "Unknown value specified for `zfpCompressionType`.\n"; } } return false; } // Assume pixel format is FLOAT for all channels. static bool DecompressZfp(float *dst, int dst_width, int dst_num_lines, size_t num_channels, const unsigned char *src, unsigned long src_size, const ZFPCompressionParam &param) { size_t uncompressed_size = size_t(dst_width) * size_t(dst_num_lines) * num_channels; if (uncompressed_size == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); } zfp_stream *zfp = NULL; zfp_field *field = NULL; assert((dst_width % 4) == 0); assert((dst_num_lines % 4) == 0); if ((size_t(dst_width) & 3U) || (size_t(dst_num_lines) & 3U)) { return false; } field = zfp_field_2d(reinterpret_cast<void *>(const_cast<unsigned char *>(src)), zfp_type_float, static_cast<unsigned int>(dst_width), static_cast<unsigned int>(dst_num_lines) * static_cast<unsigned int>(num_channels)); zfp = zfp_stream_open(NULL); if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { zfp_stream_set_rate(zfp, param.rate, zfp_type_float, /* dimension */ 2, /* write random access */ 0); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { zfp_stream_set_precision(zfp, param.precision); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { zfp_stream_set_accuracy(zfp, param.tolerance); } else { assert(0); } size_t buf_size = zfp_stream_maximum_size(zfp, field); std::vector<unsigned char> buf(buf_size); memcpy(&buf.at(0), src, src_size); bitstream *stream = stream_open(&buf.at(0), buf_size); zfp_stream_set_bit_stream(zfp, stream); zfp_stream_rewind(zfp); size_t image_size = size_t(dst_width) * size_t(dst_num_lines); for (size_t c = 0; c < size_t(num_channels); c++) { // decompress 4x4 pixel block. for (size_t y = 0; y < size_t(dst_num_lines); y += 4) { for (size_t x = 0; x < size_t(dst_width); x += 4) { float fblock[16]; zfp_decode_block_float_2(zfp, fblock); for (size_t j = 0; j < 4; j++) { for (size_t i = 0; i < 4; i++) { dst[c * image_size + ((y + j) * size_t(dst_width) + (x + i))] = fblock[j * 4 + i]; } } } } } zfp_field_free(field); zfp_stream_close(zfp); stream_close(stream); return true; } // Assume pixel format is FLOAT for all channels. static bool CompressZfp(std::vector<unsigned char> *outBuf, unsigned int *outSize, const float *inPtr, int width, int num_lines, int num_channels, const ZFPCompressionParam &param) { zfp_stream *zfp = NULL; zfp_field *field = NULL; assert((width % 4) == 0); assert((num_lines % 4) == 0); if ((size_t(width) & 3U) || (size_t(num_lines) & 3U)) { return false; } // create input array. field = zfp_field_2d(reinterpret_cast<void *>(const_cast<float *>(inPtr)), zfp_type_float, static_cast<unsigned int>(width), static_cast<unsigned int>(num_lines * num_channels)); zfp = zfp_stream_open(NULL); if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { zfp_stream_set_rate(zfp, param.rate, zfp_type_float, 2, 0); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { zfp_stream_set_precision(zfp, param.precision); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { zfp_stream_set_accuracy(zfp, param.tolerance); } else { assert(0); } size_t buf_size = zfp_stream_maximum_size(zfp, field); outBuf->resize(buf_size); bitstream *stream = stream_open(&outBuf->at(0), buf_size); zfp_stream_set_bit_stream(zfp, stream); zfp_field_free(field); size_t image_size = size_t(width) * size_t(num_lines); for (size_t c = 0; c < size_t(num_channels); c++) { // compress 4x4 pixel block. for (size_t y = 0; y < size_t(num_lines); y += 4) { for (size_t x = 0; x < size_t(width); x += 4) { float fblock[16]; for (size_t j = 0; j < 4; j++) { for (size_t i = 0; i < 4; i++) { fblock[j * 4 + i] = inPtr[c * image_size + ((y + j) * size_t(width) + (x + i))]; } } zfp_encode_block_float_2(zfp, fblock); } } } zfp_stream_flush(zfp); (*outSize) = static_cast<unsigned int>(zfp_stream_compressed_size(zfp)); zfp_stream_close(zfp); return true; } #endif // // ----------------------------------------------------------------- // // heuristics #define TINYEXR_DIMENSION_THRESHOLD (1024 * 8192) // TODO(syoyo): Refactor function arguments. static bool DecodePixelData(/* out */ unsigned char **out_images, const int *requested_pixel_types, const unsigned char *data_ptr, size_t data_len, int compression_type, int line_order, int width, int height, int x_stride, int y, int line_no, int num_lines, size_t pixel_data_size, size_t num_attributes, const EXRAttribute *attributes, size_t num_channels, const EXRChannelInfo *channels, const std::vector<size_t> &channel_offset_list) { if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { // PIZ #if TINYEXR_USE_PIZ if ((width == 0) || (num_lines == 0) || (pixel_data_size == 0)) { // Invalid input #90 return false; } // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>( static_cast<size_t>(width * num_lines) * pixel_data_size)); size_t tmpBufLen = outBuf.size(); bool ret = tinyexr::DecompressPiz( reinterpret_cast<unsigned char *>(&outBuf.at(0)), data_ptr, tmpBufLen, data_len, static_cast<int>(num_channels), channels, width, num_lines); if (!ret) { return false; } // For PIZ_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { FP16 hf; // hf.u = line_ptr[u]; // use `cpy` to avoid unaligned memory access when compiler's // optimization is on. tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; size_t offset = 0; if (line_order == 0) { offset = (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { offset = static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } image += offset; *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>(&outBuf.at( v * pixel_data_size * static_cast<size_t>(x_stride) + channel_offset_list[c] * static_cast<size_t>(x_stride))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); } } #else assert(0 && "PIZ is enabled in this build"); return false; #endif } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS || compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = static_cast<unsigned long>(outBuf.size()); assert(dstLen > 0); if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&outBuf.at(0)), &dstLen, data_ptr, static_cast<unsigned long>(data_len))) { return false; } // For ZIP_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT tinyexr::FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; size_t offset = 0; if (line_order == 0) { offset = (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { offset = (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } image += offset; *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) { // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = static_cast<unsigned long>(outBuf.size()); if (dstLen == 0) { return false; } if (!tinyexr::DecompressRle( reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen, data_ptr, static_cast<unsigned long>(data_len))) { return false; } // For RLE_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT tinyexr::FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; std::string e; if (!tinyexr::FindZFPCompressionParam(&zfp_compression_param, attributes, int(num_attributes), &e)) { // This code path should not be reachable. assert(0); return false; } // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = outBuf.size(); assert(dstLen > 0); tinyexr::DecompressZfp(reinterpret_cast<float *>(&outBuf.at(0)), width, num_lines, num_channels, data_ptr, static_cast<unsigned long>(data_len), zfp_compression_param); // For ZFP_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { assert(channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } #else (void)attributes; (void)num_attributes; (void)num_channels; assert(0); return false; #endif } else if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) { for (size_t c = 0; c < num_channels; c++) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { const unsigned short *line_ptr = reinterpret_cast<const unsigned short *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *outLine = reinterpret_cast<unsigned short *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); outLine[u] = hf.u; } } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { float *outLine = reinterpret_cast<float *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } if (reinterpret_cast<const unsigned char *>(line_ptr + width) > (data_ptr + data_len)) { // Insufficient data size return false; } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; // address may not be aliged. use byte-wise copy for safety.#76 // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); tinyexr::FP32 f32 = half_to_float(hf); outLine[u] = f32.f; } } else { assert(0); return false; } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { const float *line_ptr = reinterpret_cast<const float *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); float *outLine = reinterpret_cast<float *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } if (reinterpret_cast<const unsigned char *>(line_ptr + width) > (data_ptr + data_len)) { // Insufficient data size return false; } for (int u = 0; u < width; u++) { float val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); outLine[u] = val; } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { const unsigned int *line_ptr = reinterpret_cast<const unsigned int *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); unsigned int *outLine = reinterpret_cast<unsigned int *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } for (int u = 0; u < width; u++) { if (reinterpret_cast<const unsigned char *>(line_ptr + u) >= (data_ptr + data_len)) { // Corrupsed data? return false; } unsigned int val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); outLine[u] = val; } } } } } return true; } static bool DecodeTiledPixelData( unsigned char **out_images, int *width, int *height, const int *requested_pixel_types, const unsigned char *data_ptr, size_t data_len, int compression_type, int line_order, int data_width, int data_height, int tile_offset_x, int tile_offset_y, int tile_size_x, int tile_size_y, size_t pixel_data_size, size_t num_attributes, const EXRAttribute *attributes, size_t num_channels, const EXRChannelInfo *channels, const std::vector<size_t> &channel_offset_list) { // Here, data_width and data_height are the dimensions of the current (sub)level. if (tile_size_x * tile_offset_x > data_width || tile_size_y * tile_offset_y > data_height) { return false; } // Compute actual image size in a tile. if ((tile_offset_x + 1) * tile_size_x >= data_width) { (*width) = data_width - (tile_offset_x * tile_size_x); } else { (*width) = tile_size_x; } if ((tile_offset_y + 1) * tile_size_y >= data_height) { (*height) = data_height - (tile_offset_y * tile_size_y); } else { (*height) = tile_size_y; } // Image size = tile size. return DecodePixelData(out_images, requested_pixel_types, data_ptr, data_len, compression_type, line_order, (*width), tile_size_y, /* stride */ tile_size_x, /* y */ 0, /* line_no */ 0, (*height), pixel_data_size, num_attributes, attributes, num_channels, channels, channel_offset_list); } static bool ComputeChannelLayout(std::vector<size_t> *channel_offset_list, int *pixel_data_size, size_t *channel_offset, int num_channels, const EXRChannelInfo *channels) { channel_offset_list->resize(static_cast<size_t>(num_channels)); (*pixel_data_size) = 0; (*channel_offset) = 0; for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { (*channel_offset_list)[c] = (*channel_offset); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { (*pixel_data_size) += sizeof(unsigned short); (*channel_offset) += sizeof(unsigned short); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { (*pixel_data_size) += sizeof(float); (*channel_offset) += sizeof(float); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { (*pixel_data_size) += sizeof(unsigned int); (*channel_offset) += sizeof(unsigned int); } else { // ??? return false; } } return true; } static unsigned char **AllocateImage(int num_channels, const EXRChannelInfo *channels, const int *requested_pixel_types, int data_width, int data_height) { unsigned char **images = reinterpret_cast<unsigned char **>(static_cast<float **>( malloc(sizeof(float *) * static_cast<size_t>(num_channels)))); for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { size_t data_len = static_cast<size_t>(data_width) * static_cast<size_t>(data_height); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { // pixel_data_size += sizeof(unsigned short); // channel_offset += sizeof(unsigned short); // Alloc internal image for half type. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { images[c] = reinterpret_cast<unsigned char *>(static_cast<unsigned short *>( malloc(sizeof(unsigned short) * data_len))); } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { images[c] = reinterpret_cast<unsigned char *>( static_cast<float *>(malloc(sizeof(float) * data_len))); } else { assert(0); } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { // pixel_data_size += sizeof(float); // channel_offset += sizeof(float); images[c] = reinterpret_cast<unsigned char *>( static_cast<float *>(malloc(sizeof(float) * data_len))); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { // pixel_data_size += sizeof(unsigned int); // channel_offset += sizeof(unsigned int); images[c] = reinterpret_cast<unsigned char *>( static_cast<unsigned int *>(malloc(sizeof(unsigned int) * data_len))); } else { assert(0); } } return images; } #ifdef _WIN32 static inline std::wstring UTF8ToWchar(const std::string &str) { int wstr_size = MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), NULL, 0); std::wstring wstr(wstr_size, 0); MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), &wstr[0], (int)wstr.size()); return wstr; } #endif static int ParseEXRHeader(HeaderInfo *info, bool *empty_header, const EXRVersion *version, std::string *err, const unsigned char *buf, size_t size) { const char *marker = reinterpret_cast<const char *>(&buf[0]); if (empty_header) { (*empty_header) = false; } if (version->multipart) { if (size > 0 && marker[0] == '\0') { // End of header list. if (empty_header) { (*empty_header) = true; } return TINYEXR_SUCCESS; } } // According to the spec, the header of every OpenEXR file must contain at // least the following attributes: // // channels chlist // compression compression // dataWindow box2i // displayWindow box2i // lineOrder lineOrder // pixelAspectRatio float // screenWindowCenter v2f // screenWindowWidth float bool has_channels = false; bool has_compression = false; bool has_data_window = false; bool has_display_window = false; bool has_line_order = false; bool has_pixel_aspect_ratio = false; bool has_screen_window_center = false; bool has_screen_window_width = false; bool has_name = false; bool has_type = false; info->name.clear(); info->type.clear(); info->data_window.min_x = 0; info->data_window.min_y = 0; info->data_window.max_x = 0; info->data_window.max_y = 0; info->line_order = 0; // @fixme info->display_window.min_x = 0; info->display_window.min_y = 0; info->display_window.max_x = 0; info->display_window.max_y = 0; info->screen_window_center[0] = 0.0f; info->screen_window_center[1] = 0.0f; info->screen_window_width = -1.0f; info->pixel_aspect_ratio = -1.0f; info->tiled = 0; info->tile_size_x = -1; info->tile_size_y = -1; info->tile_level_mode = -1; info->tile_rounding_mode = -1; info->attributes.clear(); // Read attributes size_t orig_size = size; for (size_t nattr = 0; nattr < TINYEXR_MAX_HEADER_ATTRIBUTES; nattr++) { if (0 == size) { if (err) { (*err) += "Insufficient data size for attributes.\n"; } return TINYEXR_ERROR_INVALID_DATA; } else if (marker[0] == '\0') { size--; break; } std::string attr_name; std::string attr_type; std::vector<unsigned char> data; size_t marker_size; if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size, marker, size)) { if (err) { (*err) += "Failed to read attribute.\n"; } return TINYEXR_ERROR_INVALID_DATA; } marker += marker_size; size -= marker_size; // For a multipart file, the version field 9th bit is 0. if ((version->tiled || version->multipart || version->non_image) && attr_name.compare("tiles") == 0) { unsigned int x_size, y_size; unsigned char tile_mode; assert(data.size() == 9); memcpy(&x_size, &data.at(0), sizeof(int)); memcpy(&y_size, &data.at(4), sizeof(int)); tile_mode = data[8]; tinyexr::swap4(&x_size); tinyexr::swap4(&y_size); if (x_size > static_cast<unsigned int>(std::numeric_limits<int>::max()) || y_size > static_cast<unsigned int>(std::numeric_limits<int>::max())) { if (err) { (*err) = "Tile sizes were invalid."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } info->tile_size_x = static_cast<int>(x_size); info->tile_size_y = static_cast<int>(y_size); // mode = levelMode + roundingMode * 16 info->tile_level_mode = tile_mode & 0x3; info->tile_rounding_mode = (tile_mode >> 4) & 0x1; info->tiled = 1; } else if (attr_name.compare("compression") == 0) { bool ok = false; if (data[0] < TINYEXR_COMPRESSIONTYPE_PIZ) { ok = true; } if (data[0] == TINYEXR_COMPRESSIONTYPE_PIZ) { #if TINYEXR_USE_PIZ ok = true; #else if (err) { (*err) = "PIZ compression is not supported."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; #endif } if (data[0] == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP ok = true; #else if (err) { (*err) = "ZFP compression is not supported."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; #endif } if (!ok) { if (err) { (*err) = "Unknown compression type."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } info->compression_type = static_cast<int>(data[0]); has_compression = true; } else if (attr_name.compare("channels") == 0) { // name: zero-terminated string, from 1 to 255 bytes long // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2 // pLinear: unsigned char, possible values are 0 and 1 // reserved: three chars, should be zero // xSampling: int // ySampling: int if (!ReadChannelInfo(info->channels, data)) { if (err) { (*err) += "Failed to parse channel info.\n"; } return TINYEXR_ERROR_INVALID_DATA; } if (info->channels.size() < 1) { if (err) { (*err) += "# of channels is zero.\n"; } return TINYEXR_ERROR_INVALID_DATA; } has_channels = true; } else if (attr_name.compare("dataWindow") == 0) { if (data.size() >= 16) { memcpy(&info->data_window.min_x, &data.at(0), sizeof(int)); memcpy(&info->data_window.min_y, &data.at(4), sizeof(int)); memcpy(&info->data_window.max_x, &data.at(8), sizeof(int)); memcpy(&info->data_window.max_y, &data.at(12), sizeof(int)); tinyexr::swap4(&info->data_window.min_x); tinyexr::swap4(&info->data_window.min_y); tinyexr::swap4(&info->data_window.max_x); tinyexr::swap4(&info->data_window.max_y); has_data_window = true; } } else if (attr_name.compare("displayWindow") == 0) { if (data.size() >= 16) { memcpy(&info->display_window.min_x, &data.at(0), sizeof(int)); memcpy(&info->display_window.min_y, &data.at(4), sizeof(int)); memcpy(&info->display_window.max_x, &data.at(8), sizeof(int)); memcpy(&info->display_window.max_y, &data.at(12), sizeof(int)); tinyexr::swap4(&info->display_window.min_x); tinyexr::swap4(&info->display_window.min_y); tinyexr::swap4(&info->display_window.max_x); tinyexr::swap4(&info->display_window.max_y); has_display_window = true; } } else if (attr_name.compare("lineOrder") == 0) { if (data.size() >= 1) { info->line_order = static_cast<int>(data[0]); has_line_order = true; } } else if (attr_name.compare("pixelAspectRatio") == 0) { if (data.size() >= sizeof(float)) { memcpy(&info->pixel_aspect_ratio, &data.at(0), sizeof(float)); tinyexr::swap4(&info->pixel_aspect_ratio); has_pixel_aspect_ratio = true; } } else if (attr_name.compare("screenWindowCenter") == 0) { if (data.size() >= 8) { memcpy(&info->screen_window_center[0], &data.at(0), sizeof(float)); memcpy(&info->screen_window_center[1], &data.at(4), sizeof(float)); tinyexr::swap4(&info->screen_window_center[0]); tinyexr::swap4(&info->screen_window_center[1]); has_screen_window_center = true; } } else if (attr_name.compare("screenWindowWidth") == 0) { if (data.size() >= sizeof(float)) { memcpy(&info->screen_window_width, &data.at(0), sizeof(float)); tinyexr::swap4(&info->screen_window_width); has_screen_window_width = true; } } else if (attr_name.compare("chunkCount") == 0) { if (data.size() >= sizeof(int)) { memcpy(&info->chunk_count, &data.at(0), sizeof(int)); tinyexr::swap4(&info->chunk_count); } } else if (attr_name.compare("name") == 0) { if (!data.empty() && data[0]) { data.push_back(0); size_t len = strlen(reinterpret_cast<const char*>(&data[0])); info->name.resize(len); info->name.assign(reinterpret_cast<const char*>(&data[0]), len); has_name = true; } } else if (attr_name.compare("type") == 0) { if (!data.empty() && data[0]) { data.push_back(0); size_t len = strlen(reinterpret_cast<const char*>(&data[0])); info->type.resize(len); info->type.assign(reinterpret_cast<const char*>(&data[0]), len); has_type = true; } } else { // Custom attribute(up to TINYEXR_MAX_CUSTOM_ATTRIBUTES) if (info->attributes.size() < TINYEXR_MAX_CUSTOM_ATTRIBUTES) { EXRAttribute attrib; #ifdef _MSC_VER strncpy_s(attrib.name, attr_name.c_str(), 255); strncpy_s(attrib.type, attr_type.c_str(), 255); #else strncpy(attrib.name, attr_name.c_str(), 255); strncpy(attrib.type, attr_type.c_str(), 255); #endif attrib.name[255] = '\0'; attrib.type[255] = '\0'; attrib.size = static_cast<int>(data.size()); attrib.value = static_cast<unsigned char *>(malloc(data.size())); memcpy(reinterpret_cast<char *>(attrib.value), &data.at(0), data.size()); info->attributes.push_back(attrib); } } } // Check if required attributes exist { std::stringstream ss_err; if (!has_compression) { ss_err << "\"compression\" attribute not found in the header." << std::endl; } if (!has_channels) { ss_err << "\"channels\" attribute not found in the header." << std::endl; } if (!has_line_order) { ss_err << "\"lineOrder\" attribute not found in the header." << std::endl; } if (!has_display_window) { ss_err << "\"displayWindow\" attribute not found in the header." << std::endl; } if (!has_data_window) { ss_err << "\"dataWindow\" attribute not found in the header or invalid." << std::endl; } if (!has_pixel_aspect_ratio) { ss_err << "\"pixelAspectRatio\" attribute not found in the header." << std::endl; } if (!has_screen_window_width) { ss_err << "\"screenWindowWidth\" attribute not found in the header." << std::endl; } if (!has_screen_window_center) { ss_err << "\"screenWindowCenter\" attribute not found in the header." << std::endl; } if (version->multipart || version->non_image) { if (!has_name) { ss_err << "\"name\" attribute not found in the header." << std::endl; } if (!has_type) { ss_err << "\"type\" attribute not found in the header." << std::endl; } } if (!(ss_err.str().empty())) { if (err) { (*err) += ss_err.str(); } return TINYEXR_ERROR_INVALID_HEADER; } } info->header_len = static_cast<unsigned int>(orig_size - size); return TINYEXR_SUCCESS; } // C++ HeaderInfo to C EXRHeader conversion. static void ConvertHeader(EXRHeader *exr_header, const HeaderInfo &info) { exr_header->pixel_aspect_ratio = info.pixel_aspect_ratio; exr_header->screen_window_center[0] = info.screen_window_center[0]; exr_header->screen_window_center[1] = info.screen_window_center[1]; exr_header->screen_window_width = info.screen_window_width; exr_header->chunk_count = info.chunk_count; exr_header->display_window.min_x = info.display_window.min_x; exr_header->display_window.min_y = info.display_window.min_y; exr_header->display_window.max_x = info.display_window.max_x; exr_header->display_window.max_y = info.display_window.max_y; exr_header->data_window.min_x = info.data_window.min_x; exr_header->data_window.min_y = info.data_window.min_y; exr_header->data_window.max_x = info.data_window.max_x; exr_header->data_window.max_y = info.data_window.max_y; exr_header->line_order = info.line_order; exr_header->compression_type = info.compression_type; exr_header->tiled = info.tiled; exr_header->tile_size_x = info.tile_size_x; exr_header->tile_size_y = info.tile_size_y; exr_header->tile_level_mode = info.tile_level_mode; exr_header->tile_rounding_mode = info.tile_rounding_mode; EXRSetNameAttr(exr_header, info.name.c_str()); if (!info.type.empty()) { if (info.type == "scanlineimage") { assert(!exr_header->tiled); } else if (info.type == "tiledimage") { assert(exr_header->tiled); } else if (info.type == "deeptile") { exr_header->non_image = 1; assert(exr_header->tiled); } else if (info.type == "deepscanline") { exr_header->non_image = 1; assert(!exr_header->tiled); } else { assert(false); } } exr_header->num_channels = static_cast<int>(info.channels.size()); exr_header->channels = static_cast<EXRChannelInfo *>(malloc( sizeof(EXRChannelInfo) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { #ifdef _MSC_VER strncpy_s(exr_header->channels[c].name, info.channels[c].name.c_str(), 255); #else strncpy(exr_header->channels[c].name, info.channels[c].name.c_str(), 255); #endif // manually add '\0' for safety. exr_header->channels[c].name[255] = '\0'; exr_header->channels[c].pixel_type = info.channels[c].pixel_type; exr_header->channels[c].p_linear = info.channels[c].p_linear; exr_header->channels[c].x_sampling = info.channels[c].x_sampling; exr_header->channels[c].y_sampling = info.channels[c].y_sampling; } exr_header->pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { exr_header->pixel_types[c] = info.channels[c].pixel_type; } // Initially fill with values of `pixel_types` exr_header->requested_pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { exr_header->requested_pixel_types[c] = info.channels[c].pixel_type; } exr_header->num_custom_attributes = static_cast<int>(info.attributes.size()); if (exr_header->num_custom_attributes > 0) { // TODO(syoyo): Report warning when # of attributes exceeds // `TINYEXR_MAX_CUSTOM_ATTRIBUTES` if (exr_header->num_custom_attributes > TINYEXR_MAX_CUSTOM_ATTRIBUTES) { exr_header->num_custom_attributes = TINYEXR_MAX_CUSTOM_ATTRIBUTES; } exr_header->custom_attributes = static_cast<EXRAttribute *>(malloc( sizeof(EXRAttribute) * size_t(exr_header->num_custom_attributes))); for (size_t i = 0; i < info.attributes.size(); i++) { memcpy(exr_header->custom_attributes[i].name, info.attributes[i].name, 256); memcpy(exr_header->custom_attributes[i].type, info.attributes[i].type, 256); exr_header->custom_attributes[i].size = info.attributes[i].size; // Just copy pointer exr_header->custom_attributes[i].value = info.attributes[i].value; } } else { exr_header->custom_attributes = NULL; } exr_header->header_len = info.header_len; } struct OffsetData { OffsetData() : num_x_levels(0), num_y_levels(0) {} std::vector<std::vector<std::vector <tinyexr::tinyexr_uint64> > > offsets; int num_x_levels; int num_y_levels; }; int LevelIndex(int lx, int ly, int tile_level_mode, int num_x_levels) { switch (tile_level_mode) { case TINYEXR_TILE_ONE_LEVEL: return 0; case TINYEXR_TILE_MIPMAP_LEVELS: return lx; case TINYEXR_TILE_RIPMAP_LEVELS: return lx + ly * num_x_levels; default: assert(false); } return 0; } static int LevelSize(int toplevel_size, int level, int tile_rounding_mode) { assert(level >= 0); int b = int(1u << unsigned(level)); int level_size = toplevel_size / b; if (tile_rounding_mode == TINYEXR_TILE_ROUND_UP && level_size * b < toplevel_size) level_size += 1; return std::max(level_size, 1); } static int DecodeTiledLevel(EXRImage* exr_image, const EXRHeader* exr_header, const OffsetData& offset_data, const std::vector<size_t>& channel_offset_list, int pixel_data_size, const unsigned char* head, const size_t size, std::string* err) { int num_channels = exr_header->num_channels; int level_index = LevelIndex(exr_image->level_x, exr_image->level_y, exr_header->tile_level_mode, offset_data.num_x_levels); int num_y_tiles = int(offset_data.offsets[level_index].size()); assert(num_y_tiles); int num_x_tiles = int(offset_data.offsets[level_index][0].size()); assert(num_x_tiles); int num_tiles = num_x_tiles * num_y_tiles; int err_code = TINYEXR_SUCCESS; enum { EF_SUCCESS = 0, EF_INVALID_DATA = 1, EF_INSUFFICIENT_DATA = 2, EF_FAILED_TO_DECODE = 4 }; #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) std::atomic<unsigned> error_flag(EF_SUCCESS); #else unsigned error_flag(EF_SUCCESS); #endif // Although the spec says : "...the data window is subdivided into an array of smaller rectangles...", // the IlmImf library allows the dimensions of the tile to be larger (or equal) than the dimensions of the data window. #if 0 if ((exr_header->tile_size_x > exr_image->width || exr_header->tile_size_y > exr_image->height) && exr_image->level_x == 0 && exr_image->level_y == 0) { if (err) { (*err) += "Failed to decode tile data.\n"; } err_code = TINYEXR_ERROR_INVALID_DATA; } #endif exr_image->tiles = static_cast<EXRTile*>( calloc(sizeof(EXRTile), static_cast<size_t>(num_tiles))); #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) std::vector<std::thread> workers; std::atomic<int> tile_count(0); int num_threads = std::max(1, int(std::thread::hardware_concurrency())); if (num_threads > int(num_tiles)) { num_threads = int(num_tiles); } for (int t = 0; t < num_threads; t++) { workers.emplace_back(std::thread([&]() { int tile_idx = 0; while ((tile_idx = tile_count++) < num_tiles) { #else #if TINYEXR_USE_OPENMP #pragma omp parallel for #endif for (int tile_idx = 0; tile_idx < num_tiles; tile_idx++) { #endif // Allocate memory for each tile. exr_image->tiles[tile_idx].images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, exr_header->tile_size_x, exr_header->tile_size_y); int x_tile = tile_idx % num_x_tiles; int y_tile = tile_idx / num_x_tiles; // 16 byte: tile coordinates // 4 byte : data size // ~ : data(uncompressed or compressed) tinyexr::tinyexr_uint64 offset = offset_data.offsets[level_index][y_tile][x_tile]; if (offset + sizeof(int) * 5 > size) { // Insufficient data size. error_flag |= EF_INSUFFICIENT_DATA; continue; } size_t data_size = size_t(size - (offset + sizeof(int) * 5)); const unsigned char* data_ptr = reinterpret_cast<const unsigned char*>(head + offset); int tile_coordinates[4]; memcpy(tile_coordinates, data_ptr, sizeof(int) * 4); tinyexr::swap4(&tile_coordinates[0]); tinyexr::swap4(&tile_coordinates[1]); tinyexr::swap4(&tile_coordinates[2]); tinyexr::swap4(&tile_coordinates[3]); if (tile_coordinates[2] != exr_image->level_x) { // Invalid data. error_flag |= EF_INVALID_DATA; continue; } if (tile_coordinates[3] != exr_image->level_y) { // Invalid data. error_flag |= EF_INVALID_DATA; continue; } int data_len; memcpy(&data_len, data_ptr + 16, sizeof(int)); // 16 = sizeof(tile_coordinates) tinyexr::swap4(&data_len); if (data_len < 2 || size_t(data_len) > data_size) { // Insufficient data size. error_flag |= EF_INSUFFICIENT_DATA; continue; } // Move to data addr: 20 = 16 + 4; data_ptr += 20; bool ret = tinyexr::DecodeTiledPixelData( exr_image->tiles[tile_idx].images, &(exr_image->tiles[tile_idx].width), &(exr_image->tiles[tile_idx].height), exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, exr_image->width, exr_image->height, tile_coordinates[0], tile_coordinates[1], exr_header->tile_size_x, exr_header->tile_size_y, static_cast<size_t>(pixel_data_size), static_cast<size_t>(exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list); if (!ret) { // Failed to decode tile data. error_flag |= EF_FAILED_TO_DECODE; } exr_image->tiles[tile_idx].offset_x = tile_coordinates[0]; exr_image->tiles[tile_idx].offset_y = tile_coordinates[1]; exr_image->tiles[tile_idx].level_x = tile_coordinates[2]; exr_image->tiles[tile_idx].level_y = tile_coordinates[3]; #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) } })); } // num_thread loop for (auto& t : workers) { t.join(); } #else } // parallel for #endif // Even in the event of an error, the reserved memory may be freed. exr_image->num_channels = num_channels; exr_image->num_tiles = static_cast<int>(num_tiles); if (error_flag) err_code = TINYEXR_ERROR_INVALID_DATA; if (err) { if (error_flag & EF_INSUFFICIENT_DATA) { (*err) += "Insufficient data length.\n"; } if (error_flag & EF_FAILED_TO_DECODE) { (*err) += "Failed to decode tile data.\n"; } } return err_code; } static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header, const OffsetData& offset_data, const unsigned char *head, const size_t size, std::string *err) { int num_channels = exr_header->num_channels; int num_scanline_blocks = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanline_blocks = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanline_blocks = 16; #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; if (!FindZFPCompressionParam(&zfp_compression_param, exr_header->custom_attributes, int(exr_header->num_custom_attributes), err)) { return TINYEXR_ERROR_INVALID_HEADER; } #endif } if (exr_header->data_window.max_x < exr_header->data_window.min_x || exr_header->data_window.max_y < exr_header->data_window.min_y) { if (err) { (*err) += "Invalid data window.\n"; } return TINYEXR_ERROR_INVALID_DATA; } int data_width = exr_header->data_window.max_x - exr_header->data_window.min_x + 1; int data_height = exr_header->data_window.max_y - exr_header->data_window.min_y + 1; // Do not allow too large data_width and data_height. header invalid? { if ((data_width > TINYEXR_DIMENSION_THRESHOLD) || (data_height > TINYEXR_DIMENSION_THRESHOLD)) { if (err) { std::stringstream ss; ss << "data_with or data_height too large. data_width: " << data_width << ", " << "data_height = " << data_height << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } if (exr_header->tiled) { if ((exr_header->tile_size_x > TINYEXR_DIMENSION_THRESHOLD) || (exr_header->tile_size_y > TINYEXR_DIMENSION_THRESHOLD)) { if (err) { std::stringstream ss; ss << "tile with or tile height too large. tile width: " << exr_header->tile_size_x << ", " << "tile height = " << exr_header->tile_size_y << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } } } const std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0]; size_t num_blocks = offsets.size(); std::vector<size_t> channel_offset_list; int pixel_data_size = 0; size_t channel_offset = 0; if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size, &channel_offset, num_channels, exr_header->channels)) { if (err) { (*err) += "Failed to compute channel layout.\n"; } return TINYEXR_ERROR_INVALID_DATA; } #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) std::atomic<bool> invalid_data(false); #else bool invalid_data(false); #endif if (exr_header->tiled) { // value check if (exr_header->tile_size_x < 0) { if (err) { std::stringstream ss; ss << "Invalid tile size x : " << exr_header->tile_size_x << "\n"; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_HEADER; } if (exr_header->tile_size_y < 0) { if (err) { std::stringstream ss; ss << "Invalid tile size y : " << exr_header->tile_size_y << "\n"; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_HEADER; } if (exr_header->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) { EXRImage* level_image = NULL; for (int level = 0; level < offset_data.num_x_levels; ++level) { if (!level_image) { level_image = exr_image; } else { level_image->next_level = new EXRImage; InitEXRImage(level_image->next_level); level_image = level_image->next_level; } level_image->width = LevelSize(exr_header->data_window.max_x - exr_header->data_window.min_x + 1, level, exr_header->tile_rounding_mode); level_image->height = LevelSize(exr_header->data_window.max_y - exr_header->data_window.min_y + 1, level, exr_header->tile_rounding_mode); level_image->level_x = level; level_image->level_y = level; int ret = DecodeTiledLevel(level_image, exr_header, offset_data, channel_offset_list, pixel_data_size, head, size, err); if (ret != TINYEXR_SUCCESS) return ret; } } else { EXRImage* level_image = NULL; for (int level_y = 0; level_y < offset_data.num_y_levels; ++level_y) for (int level_x = 0; level_x < offset_data.num_x_levels; ++level_x) { if (!level_image) { level_image = exr_image; } else { level_image->next_level = new EXRImage; InitEXRImage(level_image->next_level); level_image = level_image->next_level; } level_image->width = LevelSize(exr_header->data_window.max_x - exr_header->data_window.min_x + 1, level_x, exr_header->tile_rounding_mode); level_image->height = LevelSize(exr_header->data_window.max_y - exr_header->data_window.min_y + 1, level_y, exr_header->tile_rounding_mode); level_image->level_x = level_x; level_image->level_y = level_y; int ret = DecodeTiledLevel(level_image, exr_header, offset_data, channel_offset_list, pixel_data_size, head, size, err); if (ret != TINYEXR_SUCCESS) return ret; } } } else { // scanline format // Don't allow too large image(256GB * pixel_data_size or more). Workaround // for #104. size_t total_data_len = size_t(data_width) * size_t(data_height) * size_t(num_channels); const bool total_data_len_overflown = sizeof(void *) == 8 ? (total_data_len >= 0x4000000000) : false; if ((total_data_len == 0) || total_data_len_overflown) { if (err) { std::stringstream ss; ss << "Image data size is zero or too large: width = " << data_width << ", height = " << data_height << ", channels = " << num_channels << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } exr_image->images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, data_width, data_height); #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) std::vector<std::thread> workers; std::atomic<int> y_count(0); int num_threads = std::max(1, int(std::thread::hardware_concurrency())); if (num_threads > int(num_blocks)) { num_threads = int(num_blocks); } for (int t = 0; t < num_threads; t++) { workers.emplace_back(std::thread([&]() { int y = 0; while ((y = y_count++) < int(num_blocks)) { #else #if TINYEXR_USE_OPENMP #pragma omp parallel for #endif for (int y = 0; y < static_cast<int>(num_blocks); y++) { #endif size_t y_idx = static_cast<size_t>(y); if (offsets[y_idx] + sizeof(int) * 2 > size) { invalid_data = true; } else { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed or compressed) size_t data_size = size_t(size - (offsets[y_idx] + sizeof(int) * 2)); const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[y_idx]); int line_no; memcpy(&line_no, data_ptr, sizeof(int)); int data_len; memcpy(&data_len, data_ptr + 4, sizeof(int)); tinyexr::swap4(&line_no); tinyexr::swap4(&data_len); if (size_t(data_len) > data_size) { invalid_data = true; } else if ((line_no > (2 << 20)) || (line_no < -(2 << 20))) { // Too large value. Assume this is invalid // 2**20 = 1048576 = heuristic value. invalid_data = true; } else if (data_len == 0) { // TODO(syoyo): May be ok to raise the threshold for example // `data_len < 4` invalid_data = true; } else { // line_no may be negative. int end_line_no = (std::min)(line_no + num_scanline_blocks, (exr_header->data_window.max_y + 1)); int num_lines = end_line_no - line_no; if (num_lines <= 0) { invalid_data = true; } else { // Move to data addr: 8 = 4 + 4; data_ptr += 8; // Adjust line_no with data_window.bmin.y // overflow check tinyexr_int64 lno = static_cast<tinyexr_int64>(line_no) - static_cast<tinyexr_int64>(exr_header->data_window.min_y); if (lno > std::numeric_limits<int>::max()) { line_no = -1; // invalid } else if (lno < -std::numeric_limits<int>::max()) { line_no = -1; // invalid } else { line_no -= exr_header->data_window.min_y; } if (line_no < 0) { invalid_data = true; } else { if (!tinyexr::DecodePixelData( exr_image->images, exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, data_width, data_height, data_width, y, line_no, num_lines, static_cast<size_t>(pixel_data_size), static_cast<size_t>( exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list)) { invalid_data = true; } } } } } #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) } })); } for (auto &t : workers) { t.join(); } #else } // omp parallel #endif } if (invalid_data) { if (err) { std::stringstream ss; (*err) += "Invalid data found when decoding pixels.\n"; } return TINYEXR_ERROR_INVALID_DATA; } // Overwrite `pixel_type` with `requested_pixel_type`. { for (int c = 0; c < exr_header->num_channels; c++) { exr_header->pixel_types[c] = exr_header->requested_pixel_types[c]; } } { exr_image->num_channels = num_channels; exr_image->width = data_width; exr_image->height = data_height; } return TINYEXR_SUCCESS; } static bool ReconstructLineOffsets( std::vector<tinyexr::tinyexr_uint64> *offsets, size_t n, const unsigned char *head, const unsigned char *marker, const size_t size) { assert(head < marker); assert(offsets->size() == n); for (size_t i = 0; i < n; i++) { size_t offset = static_cast<size_t>(marker - head); // Offset should not exceed whole EXR file/data size. if ((offset + sizeof(tinyexr::tinyexr_uint64)) >= size) { return false; } int y; unsigned int data_len; memcpy(&y, marker, sizeof(int)); memcpy(&data_len, marker + 4, sizeof(unsigned int)); if (data_len >= size) { return false; } tinyexr::swap4(&y); tinyexr::swap4(&data_len); (*offsets)[i] = offset; marker += data_len + 8; // 8 = 4 bytes(y) + 4 bytes(data_len) } return true; } static int FloorLog2(unsigned x) { // // For x > 0, floorLog2(y) returns floor(log(x)/log(2)). // int y = 0; while (x > 1) { y += 1; x >>= 1u; } return y; } static int CeilLog2(unsigned x) { // // For x > 0, ceilLog2(y) returns ceil(log(x)/log(2)). // int y = 0; int r = 0; while (x > 1) { if (x & 1) r = 1; y += 1; x >>= 1u; } return y + r; } static int RoundLog2(int x, int tile_rounding_mode) { return (tile_rounding_mode == TINYEXR_TILE_ROUND_DOWN) ? FloorLog2(static_cast<unsigned>(x)) : CeilLog2(static_cast<unsigned>(x)); } static int CalculateNumXLevels(const EXRHeader* exr_header) { int min_x = exr_header->data_window.min_x; int max_x = exr_header->data_window.max_x; int min_y = exr_header->data_window.min_y; int max_y = exr_header->data_window.max_y; int num = 0; switch (exr_header->tile_level_mode) { case TINYEXR_TILE_ONE_LEVEL: num = 1; break; case TINYEXR_TILE_MIPMAP_LEVELS: { int w = max_x - min_x + 1; int h = max_y - min_y + 1; num = RoundLog2(std::max(w, h), exr_header->tile_rounding_mode) + 1; } break; case TINYEXR_TILE_RIPMAP_LEVELS: { int w = max_x - min_x + 1; num = RoundLog2(w, exr_header->tile_rounding_mode) + 1; } break; default: assert(false); } return num; } static int CalculateNumYLevels(const EXRHeader* exr_header) { int min_x = exr_header->data_window.min_x; int max_x = exr_header->data_window.max_x; int min_y = exr_header->data_window.min_y; int max_y = exr_header->data_window.max_y; int num = 0; switch (exr_header->tile_level_mode) { case TINYEXR_TILE_ONE_LEVEL: num = 1; break; case TINYEXR_TILE_MIPMAP_LEVELS: { int w = max_x - min_x + 1; int h = max_y - min_y + 1; num = RoundLog2(std::max(w, h), exr_header->tile_rounding_mode) + 1; } break; case TINYEXR_TILE_RIPMAP_LEVELS: { int h = max_y - min_y + 1; num = RoundLog2(h, exr_header->tile_rounding_mode) + 1; } break; default: assert(false); } return num; } static void CalculateNumTiles(std::vector<int>& numTiles, int toplevel_size, int size, int tile_rounding_mode) { for (unsigned i = 0; i < numTiles.size(); i++) { int l = LevelSize(toplevel_size, i, tile_rounding_mode); assert(l <= std::numeric_limits<int>::max() - size + 1); numTiles[i] = (l + size - 1) / size; } } static void PrecalculateTileInfo(std::vector<int>& num_x_tiles, std::vector<int>& num_y_tiles, const EXRHeader* exr_header) { int min_x = exr_header->data_window.min_x; int max_x = exr_header->data_window.max_x; int min_y = exr_header->data_window.min_y; int max_y = exr_header->data_window.max_y; int num_x_levels = CalculateNumXLevels(exr_header); int num_y_levels = CalculateNumYLevels(exr_header); num_x_tiles.resize(num_x_levels); num_y_tiles.resize(num_y_levels); CalculateNumTiles(num_x_tiles, max_x - min_x + 1, exr_header->tile_size_x, exr_header->tile_rounding_mode); CalculateNumTiles(num_y_tiles, max_y - min_y + 1, exr_header->tile_size_y, exr_header->tile_rounding_mode); } static void InitSingleResolutionOffsets(OffsetData& offset_data, size_t num_blocks) { offset_data.offsets.resize(1); offset_data.offsets[0].resize(1); offset_data.offsets[0][0].resize(num_blocks); offset_data.num_x_levels = 1; offset_data.num_y_levels = 1; } // Return sum of tile blocks. static int InitTileOffsets(OffsetData& offset_data, const EXRHeader* exr_header, const std::vector<int>& num_x_tiles, const std::vector<int>& num_y_tiles) { int num_tile_blocks = 0; offset_data.num_x_levels = static_cast<int>(num_x_tiles.size()); offset_data.num_y_levels = static_cast<int>(num_y_tiles.size()); switch (exr_header->tile_level_mode) { case TINYEXR_TILE_ONE_LEVEL: case TINYEXR_TILE_MIPMAP_LEVELS: assert(offset_data.num_x_levels == offset_data.num_y_levels); offset_data.offsets.resize(offset_data.num_x_levels); for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) { offset_data.offsets[l].resize(num_y_tiles[l]); for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) { offset_data.offsets[l][dy].resize(num_x_tiles[l]); num_tile_blocks += num_x_tiles[l]; } } break; case TINYEXR_TILE_RIPMAP_LEVELS: offset_data.offsets.resize(static_cast<size_t>(offset_data.num_x_levels) * static_cast<size_t>(offset_data.num_y_levels)); for (int ly = 0; ly < offset_data.num_y_levels; ++ly) { for (int lx = 0; lx < offset_data.num_x_levels; ++lx) { int l = ly * offset_data.num_x_levels + lx; offset_data.offsets[l].resize(num_y_tiles[ly]); for (size_t dy = 0; dy < offset_data.offsets[l].size(); ++dy) { offset_data.offsets[l][dy].resize(num_x_tiles[lx]); num_tile_blocks += num_x_tiles[lx]; } } } break; default: assert(false); } return num_tile_blocks; } static bool IsAnyOffsetsAreInvalid(const OffsetData& offset_data) { for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) if (reinterpret_cast<const tinyexr::tinyexr_int64&>(offset_data.offsets[l][dy][dx]) <= 0) return true; return false; } static bool isValidTile(const EXRHeader* exr_header, const OffsetData& offset_data, int dx, int dy, int lx, int ly) { if (lx < 0 || ly < 0 || dx < 0 || dy < 0) return false; int num_x_levels = offset_data.num_x_levels; int num_y_levels = offset_data.num_y_levels; switch (exr_header->tile_level_mode) { case TINYEXR_TILE_ONE_LEVEL: if (lx == 0 && ly == 0 && offset_data.offsets.size() > 0 && offset_data.offsets[0].size() > static_cast<size_t>(dy) && offset_data.offsets[0][dy].size() > static_cast<size_t>(dx)) { return true; } break; case TINYEXR_TILE_MIPMAP_LEVELS: if (lx < num_x_levels && ly < num_y_levels && offset_data.offsets.size() > static_cast<size_t>(lx) && offset_data.offsets[lx].size() > static_cast<size_t>(dy) && offset_data.offsets[lx][dy].size() > static_cast<size_t>(dx)) { return true; } break; case TINYEXR_TILE_RIPMAP_LEVELS: { size_t idx = static_cast<size_t>(lx) + static_cast<size_t>(ly)* static_cast<size_t>(num_x_levels); if (lx < num_x_levels && ly < num_y_levels && (offset_data.offsets.size() > idx) && offset_data.offsets[idx].size() > static_cast<size_t>(dy) && offset_data.offsets[idx][dy].size() > static_cast<size_t>(dx)) { return true; } } break; default: return false; } return false; } static void ReconstructTileOffsets(OffsetData& offset_data, const EXRHeader* exr_header, const unsigned char* head, const unsigned char* marker, const size_t size, bool isMultiPartFile, bool isDeep) { (void)size; int numXLevels = offset_data.num_x_levels; for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) { for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) { for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) { tinyexr::tinyexr_uint64 tileOffset = marker - head; if (isMultiPartFile) { //int partNumber; marker += sizeof(int); } int tileX; memcpy(&tileX, marker, sizeof(int)); tinyexr::swap4(&tileX); marker += sizeof(int); int tileY; memcpy(&tileY, marker, sizeof(int)); tinyexr::swap4(&tileY); marker += sizeof(int); int levelX; memcpy(&levelX, marker, sizeof(int)); tinyexr::swap4(&levelX); marker += sizeof(int); int levelY; memcpy(&levelY, marker, sizeof(int)); tinyexr::swap4(&levelY); marker += sizeof(int); if (isDeep) { tinyexr::tinyexr_int64 packed_offset_table_size; memcpy(&packed_offset_table_size, marker, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64*>(&packed_offset_table_size)); marker += sizeof(tinyexr::tinyexr_int64); tinyexr::tinyexr_int64 packed_sample_size; memcpy(&packed_sample_size, marker, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64*>(&packed_sample_size)); marker += sizeof(tinyexr::tinyexr_int64); // next Int64 is unpacked sample size - skip that too marker += packed_offset_table_size + packed_sample_size + 8; } else { int dataSize; memcpy(&dataSize, marker, sizeof(int)); tinyexr::swap4(&dataSize); marker += sizeof(int); marker += dataSize; } if (!isValidTile(exr_header, offset_data, tileX, tileY, levelX, levelY)) return; int level_idx = LevelIndex(levelX, levelY, exr_header->tile_level_mode, numXLevels); offset_data.offsets[level_idx][tileY][tileX] = tileOffset; } } } } // marker output is also static int ReadOffsets(OffsetData& offset_data, const unsigned char* head, const unsigned char*& marker, const size_t size, const char** err) { for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) { for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) { for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) { tinyexr::tinyexr_uint64 offset; if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) { tinyexr::SetErrorMessage("Insufficient data size in offset table.", err); return TINYEXR_ERROR_INVALID_DATA; } memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64)); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err); return TINYEXR_ERROR_INVALID_DATA; } marker += sizeof(tinyexr::tinyexr_uint64); // = 8 offset_data.offsets[l][dy][dx] = offset; } } } return TINYEXR_SUCCESS; } static int DecodeEXRImage(EXRImage *exr_image, const EXRHeader *exr_header, const unsigned char *head, const unsigned char *marker, const size_t size, const char **err) { if (exr_image == NULL || exr_header == NULL || head == NULL || marker == NULL || (size <= tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage("Invalid argument for DecodeEXRImage().", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } int num_scanline_blocks = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanline_blocks = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanline_blocks = 16; } if (exr_header->data_window.max_x < exr_header->data_window.min_x || exr_header->data_window.max_x - exr_header->data_window.min_x == std::numeric_limits<int>::max()) { // Issue 63 tinyexr::SetErrorMessage("Invalid data width value", err); return TINYEXR_ERROR_INVALID_DATA; } int data_width = exr_header->data_window.max_x - exr_header->data_window.min_x + 1; if (exr_header->data_window.max_y < exr_header->data_window.min_y || exr_header->data_window.max_y - exr_header->data_window.min_y == std::numeric_limits<int>::max()) { tinyexr::SetErrorMessage("Invalid data height value", err); return TINYEXR_ERROR_INVALID_DATA; } int data_height = exr_header->data_window.max_y - exr_header->data_window.min_y + 1; // Do not allow too large data_width and data_height. header invalid? { if (data_width > TINYEXR_DIMENSION_THRESHOLD) { tinyexr::SetErrorMessage("data width too large.", err); return TINYEXR_ERROR_INVALID_DATA; } if (data_height > TINYEXR_DIMENSION_THRESHOLD) { tinyexr::SetErrorMessage("data height too large.", err); return TINYEXR_ERROR_INVALID_DATA; } } if (exr_header->tiled) { if (exr_header->tile_size_x > TINYEXR_DIMENSION_THRESHOLD) { tinyexr::SetErrorMessage("tile width too large.", err); return TINYEXR_ERROR_INVALID_DATA; } if (exr_header->tile_size_y > TINYEXR_DIMENSION_THRESHOLD) { tinyexr::SetErrorMessage("tile height too large.", err); return TINYEXR_ERROR_INVALID_DATA; } } // Read offset tables. OffsetData offset_data; size_t num_blocks = 0; // For a multi-resolution image, the size of the offset table will be calculated from the other attributes of the header. // If chunk_count > 0 then chunk_count must be equal to the calculated tile count. if (exr_header->tiled) { { std::vector<int> num_x_tiles, num_y_tiles; PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_header); num_blocks = InitTileOffsets(offset_data, exr_header, num_x_tiles, num_y_tiles); if (exr_header->chunk_count > 0) { if (size_t(exr_header->chunk_count) != num_blocks) { tinyexr::SetErrorMessage("Invalid offset table size.", err); return TINYEXR_ERROR_INVALID_DATA; } } } int ret = ReadOffsets(offset_data, head, marker, size, err); if (ret != TINYEXR_SUCCESS) return ret; if (IsAnyOffsetsAreInvalid(offset_data)) { ReconstructTileOffsets(offset_data, exr_header, head, marker, size, exr_header->multipart, exr_header->non_image); } } else if (exr_header->chunk_count > 0) { // Use `chunkCount` attribute. num_blocks = static_cast<size_t>(exr_header->chunk_count); InitSingleResolutionOffsets(offset_data, num_blocks); } else { num_blocks = static_cast<size_t>(data_height) / static_cast<size_t>(num_scanline_blocks); if (num_blocks * static_cast<size_t>(num_scanline_blocks) < static_cast<size_t>(data_height)) { num_blocks++; } InitSingleResolutionOffsets(offset_data, num_blocks); } if (!exr_header->tiled) { std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0]; for (size_t y = 0; y < num_blocks; y++) { tinyexr::tinyexr_uint64 offset; // Issue #81 if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) { tinyexr::SetErrorMessage("Insufficient data size in offset table.", err); return TINYEXR_ERROR_INVALID_DATA; } memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64)); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err); return TINYEXR_ERROR_INVALID_DATA; } marker += sizeof(tinyexr::tinyexr_uint64); // = 8 offsets[y] = offset; } // If line offsets are invalid, we try to reconstruct it. // See OpenEXR/IlmImf/ImfScanLineInputFile.cpp::readLineOffsets() for details. for (size_t y = 0; y < num_blocks; y++) { if (offsets[y] <= 0) { // TODO(syoyo) Report as warning? // if (err) { // stringstream ss; // ss << "Incomplete lineOffsets." << std::endl; // (*err) += ss.str(); //} bool ret = ReconstructLineOffsets(&offsets, num_blocks, head, marker, size); if (ret) { // OK break; } else { tinyexr::SetErrorMessage( "Cannot reconstruct lineOffset table in DecodeEXRImage.", err); return TINYEXR_ERROR_INVALID_DATA; } } } } { std::string e; int ret = DecodeChunk(exr_image, exr_header, offset_data, head, size, &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty()) { tinyexr::SetErrorMessage(e, err); } #if 1 FreeEXRImage(exr_image); #else // release memory(if exists) if ((exr_header->num_channels > 0) && exr_image && exr_image->images) { for (size_t c = 0; c < size_t(exr_header->num_channels); c++) { if (exr_image->images[c]) { free(exr_image->images[c]); exr_image->images[c] = NULL; } } free(exr_image->images); exr_image->images = NULL; } #endif } return ret; } } static void GetLayers(const EXRHeader &exr_header, std::vector<std::string> &layer_names) { // Naive implementation // Group channels by layers // go over all channel names, split by periods // collect unique names layer_names.clear(); for (int c = 0; c < exr_header.num_channels; c++) { std::string full_name(exr_header.channels[c].name); const size_t pos = full_name.find_last_of('.'); if (pos != std::string::npos && pos != 0 && pos + 1 < full_name.size()) { full_name.erase(pos); if (std::find(layer_names.begin(), layer_names.end(), full_name) == layer_names.end()) layer_names.push_back(full_name); } } } struct LayerChannel { explicit LayerChannel(size_t i, std::string n) : index(i), name(n) {} size_t index; std::string name; }; static void ChannelsInLayer(const EXRHeader &exr_header, const std::string layer_name, std::vector<LayerChannel> &channels) { channels.clear(); for (int c = 0; c < exr_header.num_channels; c++) { std::string ch_name(exr_header.channels[c].name); if (layer_name.empty()) { const size_t pos = ch_name.find_last_of('.'); if (pos != std::string::npos && pos < ch_name.size()) { ch_name = ch_name.substr(pos + 1); } } else { const size_t pos = ch_name.find(layer_name + '.'); if (pos == std::string::npos) continue; if (pos == 0) { ch_name = ch_name.substr(layer_name.size() + 1); } } LayerChannel ch(size_t(c), ch_name); channels.push_back(ch); } } } // namespace tinyexr int EXRLayers(const char *filename, const char **layer_names[], int *num_layers, const char **err) { EXRVersion exr_version; EXRHeader exr_header; InitEXRHeader(&exr_header); { int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { tinyexr::SetErrorMessage("Invalid EXR header.", err); return ret; } if (exr_version.multipart || exr_version.non_image) { tinyexr::SetErrorMessage( "Loading multipart or DeepImage is not supported in LoadEXR() API", err); return TINYEXR_ERROR_INVALID_DATA; // @fixme. } } int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); return ret; } std::vector<std::string> layer_vec; tinyexr::GetLayers(exr_header, layer_vec); (*num_layers) = int(layer_vec.size()); (*layer_names) = static_cast<const char **>( malloc(sizeof(const char *) * static_cast<size_t>(layer_vec.size()))); for (size_t c = 0; c < static_cast<size_t>(layer_vec.size()); c++) { #ifdef _MSC_VER (*layer_names)[c] = _strdup(layer_vec[c].c_str()); #else (*layer_names)[c] = strdup(layer_vec[c].c_str()); #endif } FreeEXRHeader(&exr_header); return TINYEXR_SUCCESS; } int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err) { return LoadEXRWithLayer(out_rgba, width, height, filename, /* layername */ NULL, err); } int LoadEXRWithLayer(float **out_rgba, int *width, int *height, const char *filename, const char *layername, const char **err) { if (out_rgba == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXR()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRVersion exr_version; EXRImage exr_image; EXRHeader exr_header; InitEXRHeader(&exr_header); InitEXRImage(&exr_image); { int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { std::stringstream ss; ss << "Failed to open EXR file or read version info from EXR file. code(" << ret << ")"; tinyexr::SetErrorMessage(ss.str(), err); return ret; } if (exr_version.multipart || exr_version.non_image) { tinyexr::SetErrorMessage( "Loading multipart or DeepImage is not supported in LoadEXR() API", err); return TINYEXR_ERROR_INVALID_DATA; // @fixme. } } { int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); return ret; } } // Read HALF channel as FLOAT. for (int i = 0; i < exr_header.num_channels; i++) { if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) { exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; } } // TODO: Probably limit loading to layers (channels) selected by layer index { int ret = LoadEXRImageFromFile(&exr_image, &exr_header, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); return ret; } } // RGBA int idxR = -1; int idxG = -1; int idxB = -1; int idxA = -1; std::vector<std::string> layer_names; tinyexr::GetLayers(exr_header, layer_names); std::vector<tinyexr::LayerChannel> channels; tinyexr::ChannelsInLayer( exr_header, layername == NULL ? "" : std::string(layername), channels); if (channels.size() < 1) { tinyexr::SetErrorMessage("Layer Not Found", err); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_ERROR_LAYER_NOT_FOUND; } size_t ch_count = channels.size() < 4 ? channels.size() : 4; for (size_t c = 0; c < ch_count; c++) { const tinyexr::LayerChannel &ch = channels[c]; if (ch.name == "R") { idxR = int(ch.index); } else if (ch.name == "G") { idxG = int(ch.index); } else if (ch.name == "B") { idxB = int(ch.index); } else if (ch.name == "A") { idxA = int(ch.index); } } if (channels.size() == 1) { int chIdx = int(channels.front().index); // Grayscale channel only. (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * static_cast<int>(exr_header.tile_size_x) + i; const int jj = exr_image.tiles[it].offset_y * static_cast<int>(exr_header.tile_size_y) + j; const int idx = ii + jj * static_cast<int>(exr_image.width); // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[chIdx][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[chIdx][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[chIdx][srcIdx]; (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[chIdx][srcIdx]; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { const float val = reinterpret_cast<float **>(exr_image.images)[chIdx][i]; (*out_rgba)[4 * i + 0] = val; (*out_rgba)[4 * i + 1] = val; (*out_rgba)[4 * i + 2] = val; (*out_rgba)[4 * i + 3] = val; } } } else { // Assume RGB(A) if (idxR == -1) { tinyexr::SetErrorMessage("R channel not found", err); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_ERROR_INVALID_DATA; } if (idxG == -1) { tinyexr::SetErrorMessage("G channel not found", err); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_ERROR_INVALID_DATA; } if (idxB == -1) { tinyexr::SetErrorMessage("B channel not found", err); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_ERROR_INVALID_DATA; } (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[idxR][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[idxG][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[idxB][srcIdx]; if (idxA != -1) { (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[idxA][srcIdx]; } else { (*out_rgba)[4 * idx + 3] = 1.0; } } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { (*out_rgba)[4 * i + 0] = reinterpret_cast<float **>(exr_image.images)[idxR][i]; (*out_rgba)[4 * i + 1] = reinterpret_cast<float **>(exr_image.images)[idxG][i]; (*out_rgba)[4 * i + 2] = reinterpret_cast<float **>(exr_image.images)[idxB][i]; if (idxA != -1) { (*out_rgba)[4 * i + 3] = reinterpret_cast<float **>(exr_image.images)[idxA][i]; } else { (*out_rgba)[4 * i + 3] = 1.0; } } } } (*width) = exr_image.width; (*height) = exr_image.height; FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_SUCCESS; } int IsEXR(const char *filename) { EXRVersion exr_version; int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { return ret; } return TINYEXR_SUCCESS; } int ParseEXRHeaderFromMemory(EXRHeader *exr_header, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err) { if (memory == NULL || exr_header == NULL) { tinyexr::SetErrorMessage( "Invalid argument. `memory` or `exr_header` argument is null in " "ParseEXRHeaderFromMemory()", err); // Invalid argument return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { tinyexr::SetErrorMessage("Insufficient header/data size.\n", err); return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory + tinyexr::kEXRVersionSize; size_t marker_size = size - tinyexr::kEXRVersionSize; tinyexr::HeaderInfo info; info.clear(); std::string err_str; int ret = ParseEXRHeader(&info, NULL, version, &err_str, marker, marker_size); if (ret != TINYEXR_SUCCESS) { if (err && !err_str.empty()) { tinyexr::SetErrorMessage(err_str, err); } } ConvertHeader(exr_header, info); exr_header->multipart = version->multipart ? 1 : 0; exr_header->non_image = version->non_image ? 1 : 0; return ret; } int LoadEXRFromMemory(float **out_rgba, int *width, int *height, const unsigned char *memory, size_t size, const char **err) { if (out_rgba == NULL || memory == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRVersion exr_version; EXRImage exr_image; EXRHeader exr_header; InitEXRHeader(&exr_header); int ret = ParseEXRVersionFromMemory(&exr_version, memory, size); if (ret != TINYEXR_SUCCESS) { std::stringstream ss; ss << "Failed to parse EXR version. code(" << ret << ")"; tinyexr::SetErrorMessage(ss.str(), err); return ret; } ret = ParseEXRHeaderFromMemory(&exr_header, &exr_version, memory, size, err); if (ret != TINYEXR_SUCCESS) { return ret; } // Read HALF channel as FLOAT. for (int i = 0; i < exr_header.num_channels; i++) { if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) { exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; } } InitEXRImage(&exr_image); ret = LoadEXRImageFromMemory(&exr_image, &exr_header, memory, size, err); if (ret != TINYEXR_SUCCESS) { return ret; } // RGBA int idxR = -1; int idxG = -1; int idxB = -1; int idxA = -1; for (int c = 0; c < exr_header.num_channels; c++) { if (strcmp(exr_header.channels[c].name, "R") == 0) { idxR = c; } else if (strcmp(exr_header.channels[c].name, "G") == 0) { idxG = c; } else if (strcmp(exr_header.channels[c].name, "B") == 0) { idxB = c; } else if (strcmp(exr_header.channels[c].name, "A") == 0) { idxA = c; } } // TODO(syoyo): Refactor removing same code as used in LoadEXR(). if (exr_header.num_channels == 1) { // Grayscale channel only. (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[0][srcIdx]; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { const float val = reinterpret_cast<float **>(exr_image.images)[0][i]; (*out_rgba)[4 * i + 0] = val; (*out_rgba)[4 * i + 1] = val; (*out_rgba)[4 * i + 2] = val; (*out_rgba)[4 * i + 3] = val; } } } else { // TODO(syoyo): Support non RGBA image. if (idxR == -1) { tinyexr::SetErrorMessage("R channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxG == -1) { tinyexr::SetErrorMessage("G channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxB == -1) { tinyexr::SetErrorMessage("B channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[idxR][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[idxG][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[idxB][srcIdx]; if (idxA != -1) { (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[idxA][srcIdx]; } else { (*out_rgba)[4 * idx + 3] = 1.0; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { (*out_rgba)[4 * i + 0] = reinterpret_cast<float **>(exr_image.images)[idxR][i]; (*out_rgba)[4 * i + 1] = reinterpret_cast<float **>(exr_image.images)[idxG][i]; (*out_rgba)[4 * i + 2] = reinterpret_cast<float **>(exr_image.images)[idxB][i]; if (idxA != -1) { (*out_rgba)[4 * i + 3] = reinterpret_cast<float **>(exr_image.images)[idxA][i]; } else { (*out_rgba)[4 * i + 3] = 1.0; } } } } (*width) = exr_image.width; (*height) = exr_image.height; FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_SUCCESS; } int LoadEXRImageFromFile(EXRImage *exr_image, const EXRHeader *exr_header, const char *filename, const char **err) { if (exr_image == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } FILE *fp = NULL; #ifdef _WIN32 #if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang errno_t errcode = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb"); if (errcode != 0) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); // TODO(syoyo): return wfopen_s erro code return TINYEXR_ERROR_CANT_OPEN_FILE; } #else // Unknown compiler fp = fopen(filename, "rb"); #endif #else fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (filesize < 16) { tinyexr::SetErrorMessage("File size too short " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); (void)ret; } return LoadEXRImageFromMemory(exr_image, exr_header, &buf.at(0), filesize, err); } int LoadEXRImageFromMemory(EXRImage *exr_image, const EXRHeader *exr_header, const unsigned char *memory, const size_t size, const char **err) { if (exr_image == NULL || memory == NULL || (size < tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_header->header_len == 0) { tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } const unsigned char *head = memory; const unsigned char *marker = reinterpret_cast<const unsigned char *>( memory + exr_header->header_len + 8); // +8 for magic number + version header. return tinyexr::DecodeEXRImage(exr_image, exr_header, head, marker, size, err); } namespace tinyexr { // out_data must be allocated initially with the block-header size // of the current image(-part) type static bool EncodePixelData(/* out */ std::vector<unsigned char>& out_data, const unsigned char* const* images, const int* requested_pixel_types, int compression_type, int line_order, int width, // for tiled : tile.width int height, // for tiled : header.tile_size_y int x_stride, // for tiled : header.tile_size_x int line_no, // for tiled : 0 int num_lines, // for tiled : tile.height size_t pixel_data_size, const std::vector<ChannelInfo>& channels, const std::vector<size_t>& channel_offset_list, const void* compression_param = 0) // zfp compression param { (void)line_order; (void)height; (void)compression_param; size_t buf_size = static_cast<size_t>(width) * static_cast<size_t>(num_lines) * static_cast<size_t>(pixel_data_size); //int last2bit = (buf_size & 3); // buf_size must be multiple of four //if(last2bit) buf_size += 4 - last2bit; std::vector<unsigned char> buf(buf_size); size_t start_y = static_cast<size_t>(line_no); for (size_t c = 0; c < channels.size(); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < num_lines; y++) { // Assume increasing Y float *line_ptr = reinterpret_cast<float *>(&buf.at( static_cast<size_t>(pixel_data_size * y * width) + channel_offset_list[c] * static_cast<size_t>(width))); for (int x = 0; x < width; x++) { tinyexr::FP16 h16; h16.u = reinterpret_cast<const unsigned short * const *>( images)[c][(y + start_y) * x_stride + x]; tinyexr::FP32 f32 = half_to_float(h16); tinyexr::swap4(&f32.f); // line_ptr[x] = f32.f; tinyexr::cpy4(line_ptr + x, &(f32.f)); } } } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < num_lines; y++) { // Assume increasing Y unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &buf.at(static_cast<size_t>(pixel_data_size * y * width) + channel_offset_list[c] * static_cast<size_t>(width))); for (int x = 0; x < width; x++) { unsigned short val = reinterpret_cast<const unsigned short * const *>( images)[c][(y + start_y) * x_stride + x]; tinyexr::swap2(&val); // line_ptr[x] = val; tinyexr::cpy2(line_ptr + x, &val); } } } else { assert(0); } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < num_lines; y++) { // Assume increasing Y unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &buf.at(static_cast<size_t>(pixel_data_size * y * width) + channel_offset_list[c] * static_cast<size_t>(width))); for (int x = 0; x < width; x++) { tinyexr::FP32 f32; f32.f = reinterpret_cast<const float * const *>( images)[c][(y + start_y) * x_stride + x]; tinyexr::FP16 h16; h16 = float_to_half_full(f32); tinyexr::swap2(reinterpret_cast<unsigned short *>(&h16.u)); // line_ptr[x] = h16.u; tinyexr::cpy2(line_ptr + x, &(h16.u)); } } } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < num_lines; y++) { // Assume increasing Y float *line_ptr = reinterpret_cast<float *>(&buf.at( static_cast<size_t>(pixel_data_size * y * width) + channel_offset_list[c] * static_cast<size_t>(width))); for (int x = 0; x < width; x++) { float val = reinterpret_cast<const float * const *>( images)[c][(y + start_y) * x_stride + x]; tinyexr::swap4(&val); // line_ptr[x] = val; tinyexr::cpy4(line_ptr + x, &val); } } } else { assert(0); } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { for (int y = 0; y < num_lines; y++) { // Assume increasing Y unsigned int *line_ptr = reinterpret_cast<unsigned int *>(&buf.at( static_cast<size_t>(pixel_data_size * y * width) + channel_offset_list[c] * static_cast<size_t>(width))); for (int x = 0; x < width; x++) { unsigned int val = reinterpret_cast<const unsigned int * const *>( images)[c][(y + start_y) * x_stride + x]; tinyexr::swap4(&val); // line_ptr[x] = val; tinyexr::cpy4(line_ptr + x, &val); } } } } if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed) out_data.insert(out_data.end(), buf.begin(), buf.end()); } else if ((compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) { #if TINYEXR_USE_MINIZ std::vector<unsigned char> block(tinyexr::miniz::mz_compressBound( static_cast<unsigned long>(buf.size()))); #else std::vector<unsigned char> block( compressBound(static_cast<uLong>(buf.size()))); #endif tinyexr::tinyexr_uint64 outSize = block.size(); tinyexr::CompressZip(&block.at(0), outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), static_cast<unsigned long>(buf.size())); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) unsigned int data_len = static_cast<unsigned int>(outSize); // truncate out_data.insert(out_data.end(), block.begin(), block.begin() + data_len); } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) { // (buf.size() * 3) / 2 would be enough. std::vector<unsigned char> block((buf.size() * 3) / 2); tinyexr::tinyexr_uint64 outSize = block.size(); tinyexr::CompressRle(&block.at(0), outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), static_cast<unsigned long>(buf.size())); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) unsigned int data_len = static_cast<unsigned int>(outSize); // truncate out_data.insert(out_data.end(), block.begin(), block.begin() + data_len); } else if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { #if TINYEXR_USE_PIZ unsigned int bufLen = 8192 + static_cast<unsigned int>( 2 * static_cast<unsigned int>( buf.size())); // @fixme { compute good bound. } std::vector<unsigned char> block(bufLen); unsigned int outSize = static_cast<unsigned int>(block.size()); CompressPiz(&block.at(0), &outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), buf.size(), channels, width, num_lines); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) unsigned int data_len = outSize; out_data.insert(out_data.end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP const ZFPCompressionParam* zfp_compression_param = reinterpret_cast<const ZFPCompressionParam*>(compression_param); std::vector<unsigned char> block; unsigned int outSize; tinyexr::CompressZfp( &block, &outSize, reinterpret_cast<const float *>(&buf.at(0)), width, num_lines, static_cast<int>(channels.size()), *zfp_compression_param); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) unsigned int data_len = outSize; out_data.insert(out_data.end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else { assert(0); return false; } return true; } static int EncodeTiledLevel(const EXRImage* level_image, const EXRHeader* exr_header, const std::vector<tinyexr::ChannelInfo>& channels, std::vector<std::vector<unsigned char> >& data_list, size_t start_index, // for data_list int num_x_tiles, int num_y_tiles, const std::vector<size_t>& channel_offset_list, int pixel_data_size, const void* compression_param, // must be set if zfp compression is enabled std::string* err) { int num_tiles = num_x_tiles * num_y_tiles; assert(num_tiles == level_image->num_tiles); if ((exr_header->tile_size_x > level_image->width || exr_header->tile_size_y > level_image->height) && level_image->level_x == 0 && level_image->level_y == 0) { if (err) { (*err) += "Failed to encode tile data.\n"; } return TINYEXR_ERROR_INVALID_DATA; } #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) std::atomic<bool> invalid_data(false); #else bool invalid_data(false); #endif #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) std::vector<std::thread> workers; std::atomic<int> tile_count(0); int num_threads = std::max(1, int(std::thread::hardware_concurrency())); if (num_threads > int(num_tiles)) { num_threads = int(num_tiles); } for (int t = 0; t < num_threads; t++) { workers.emplace_back(std::thread([&]() { int i = 0; while ((i = tile_count++) < num_tiles) { #else // Use signed int since some OpenMP compiler doesn't allow unsigned type for // `parallel for` #if TINYEXR_USE_OPENMP #pragma omp parallel for #endif for (int i = 0; i < num_tiles; i++) { #endif size_t tile_idx = static_cast<size_t>(i); size_t data_idx = tile_idx + start_index; int x_tile = i % num_x_tiles; int y_tile = i / num_x_tiles; EXRTile& tile = level_image->tiles[tile_idx]; const unsigned char* const* images = static_cast<const unsigned char* const*>(tile.images); data_list[data_idx].resize(5*sizeof(int)); size_t data_header_size = data_list[data_idx].size(); bool ret = EncodePixelData(data_list[data_idx], images, exr_header->requested_pixel_types, exr_header->compression_type, 0, // increasing y tile.width, exr_header->tile_size_y, exr_header->tile_size_x, 0, tile.height, pixel_data_size, channels, channel_offset_list, compression_param); if (!ret) { invalid_data = true; continue; } assert(data_list[data_idx].size() > data_header_size); int data_len = static_cast<int>(data_list[data_idx].size() - data_header_size); //tileX, tileY, levelX, levelY // pixel_data_size(int) memcpy(&data_list[data_idx][0], &x_tile, sizeof(int)); memcpy(&data_list[data_idx][4], &y_tile, sizeof(int)); memcpy(&data_list[data_idx][8], &level_image->level_x, sizeof(int)); memcpy(&data_list[data_idx][12], &level_image->level_y, sizeof(int)); memcpy(&data_list[data_idx][16], &data_len, sizeof(int)); swap4(reinterpret_cast<int*>(&data_list[data_idx][0])); swap4(reinterpret_cast<int*>(&data_list[data_idx][4])); swap4(reinterpret_cast<int*>(&data_list[data_idx][8])); swap4(reinterpret_cast<int*>(&data_list[data_idx][12])); swap4(reinterpret_cast<int*>(&data_list[data_idx][16])); #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) } })); } for (auto &t : workers) { t.join(); } #else } // omp parallel #endif if (invalid_data) { if (err) { (*err) += "Failed to encode tile data.\n"; } return TINYEXR_ERROR_INVALID_DATA; } return TINYEXR_SUCCESS; } static int NumScanlines(int compression_type) { int num_scanlines = 1; if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanlines = 16; } else if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanlines = 32; } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanlines = 16; } return num_scanlines; } static int EncodeChunk(const EXRImage* exr_image, const EXRHeader* exr_header, const std::vector<ChannelInfo>& channels, int num_blocks, tinyexr_uint64 chunk_offset, // starting offset of current chunk bool is_multipart, OffsetData& offset_data, // output block offsets, must be initialized std::vector<std::vector<unsigned char> >& data_list, // output tinyexr_uint64& total_size, // output: ending offset of current chunk std::string* err) { int num_scanlines = NumScanlines(exr_header->compression_type); data_list.resize(num_blocks); std::vector<size_t> channel_offset_list( static_cast<size_t>(exr_header->num_channels)); int pixel_data_size = 0; { size_t channel_offset = 0; for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { channel_offset_list[c] = channel_offset; if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { pixel_data_size += sizeof(unsigned short); channel_offset += sizeof(unsigned short); } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { pixel_data_size += sizeof(float); channel_offset += sizeof(float); } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT) { pixel_data_size += sizeof(unsigned int); channel_offset += sizeof(unsigned int); } else { assert(0); } } } const void* compression_param = 0; #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; // Use ZFP compression parameter from custom attributes(if such a parameter // exists) { std::string e; bool ret = tinyexr::FindZFPCompressionParam( &zfp_compression_param, exr_header->custom_attributes, exr_header->num_custom_attributes, &e); if (!ret) { // Use predefined compression parameter. zfp_compression_param.type = 0; zfp_compression_param.rate = 2; } compression_param = &zfp_compression_param; } #endif tinyexr_uint64 offset = chunk_offset; tinyexr_uint64 doffset = is_multipart ? 4u : 0u; if (exr_image->tiles) { const EXRImage* level_image = exr_image; size_t block_idx = 0; tinyexr::tinyexr_uint64 block_data_size = 0; int num_levels = (exr_header->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) ? offset_data.num_x_levels : (offset_data.num_x_levels * offset_data.num_y_levels); for (int level_index = 0; level_index < num_levels; ++level_index) { if (!level_image) { if (err) { (*err) += "Invalid number of tiled levels for EncodeChunk\n"; } return TINYEXR_ERROR_INVALID_DATA; } int level_index_from_image = LevelIndex(level_image->level_x, level_image->level_y, exr_header->tile_level_mode, offset_data.num_x_levels); if (level_index_from_image != level_index) { if (err) { (*err) += "Incorrect level ordering in tiled image\n"; } return TINYEXR_ERROR_INVALID_DATA; } int num_y_tiles = int(offset_data.offsets[level_index].size()); assert(num_y_tiles); int num_x_tiles = int(offset_data.offsets[level_index][0].size()); assert(num_x_tiles); std::string e; int ret = EncodeTiledLevel(level_image, exr_header, channels, data_list, block_idx, num_x_tiles, num_y_tiles, channel_offset_list, pixel_data_size, compression_param, &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty() && err) { (*err) += e; } return ret; } for (size_t j = 0; j < static_cast<size_t>(num_y_tiles); ++j) for (size_t i = 0; i < static_cast<size_t>(num_x_tiles); ++i) { offset_data.offsets[level_index][j][i] = offset; swap8(reinterpret_cast<tinyexr_uint64*>(&offset_data.offsets[level_index][j][i])); offset += data_list[block_idx].size() + doffset; block_data_size += data_list[block_idx].size(); ++block_idx; } level_image = level_image->next_level; } assert(block_idx == size_t(num_blocks)); total_size = offset; } else { // scanlines std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data.offsets[0][0]; #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) std::atomic<bool> invalid_data(false); std::vector<std::thread> workers; std::atomic<int> block_count(0); int num_threads = std::min(std::max(1, int(std::thread::hardware_concurrency())), num_blocks); for (int t = 0; t < num_threads; t++) { workers.emplace_back(std::thread([&]() { int i = 0; while ((i = block_count++) < num_blocks) { #else bool invalid_data(false); #if TINYEXR_USE_OPENMP #pragma omp parallel for #endif for (int i = 0; i < num_blocks; i++) { #endif int start_y = num_scanlines * i; int end_Y = (std::min)(num_scanlines * (i + 1), exr_image->height); int num_lines = end_Y - start_y; const unsigned char* const* images = static_cast<const unsigned char* const*>(exr_image->images); data_list[i].resize(2*sizeof(int)); size_t data_header_size = data_list[i].size(); bool ret = EncodePixelData(data_list[i], images, exr_header->requested_pixel_types, exr_header->compression_type, 0, // increasing y exr_image->width, exr_image->height, exr_image->width, start_y, num_lines, pixel_data_size, channels, channel_offset_list, compression_param); if (!ret) { invalid_data = true; continue; // "break" cannot be used with OpenMP } assert(data_list[i].size() > data_header_size); int data_len = static_cast<int>(data_list[i].size() - data_header_size); memcpy(&data_list[i][0], &start_y, sizeof(int)); memcpy(&data_list[i][4], &data_len, sizeof(int)); swap4(reinterpret_cast<int*>(&data_list[i][0])); swap4(reinterpret_cast<int*>(&data_list[i][4])); #if TINYEXR_HAS_CXX11 && (TINYEXR_USE_THREAD > 0) } })); } for (auto &t : workers) { t.join(); } #else } // omp parallel #endif if (invalid_data) { if (err) { (*err) += "Failed to encode scanline data.\n"; } return TINYEXR_ERROR_INVALID_DATA; } for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) { offsets[i] = offset; tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offsets[i])); offset += data_list[i].size() + doffset; } total_size = static_cast<size_t>(offset); } return TINYEXR_SUCCESS; } // can save a single or multi-part image (no deep* formats) static size_t SaveEXRNPartImageToMemory(const EXRImage* exr_images, const EXRHeader** exr_headers, unsigned int num_parts, unsigned char** memory_out, const char** err) { if (exr_images == NULL || exr_headers == NULL || num_parts == 0 || memory_out == NULL) { SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory", err); return 0; } { for (unsigned int i = 0; i < num_parts; ++i) { if (exr_headers[i]->compression_type < 0) { SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory", err); return 0; } #if !TINYEXR_USE_PIZ if (exr_headers[i]->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { SetErrorMessage("PIZ compression is not supported in this build", err); return 0; } #endif #if !TINYEXR_USE_ZFP if (exr_headers[i]->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { SetErrorMessage("ZFP compression is not supported in this build", err); return 0; } #else for (int c = 0; c < exr_header->num_channels; ++c) { if (exr_headers[i]->requested_pixel_types[c] != TINYEXR_PIXELTYPE_FLOAT) { SetErrorMessage("Pixel type must be FLOAT for ZFP compression", err); return 0; } } #endif } } std::vector<unsigned char> memory; // Header { const char header[] = { 0x76, 0x2f, 0x31, 0x01 }; memory.insert(memory.end(), header, header + 4); } // Version // using value from the first header int long_name = exr_headers[0]->long_name; { char marker[] = { 2, 0, 0, 0 }; /* @todo if (exr_header->non_image) { marker[1] |= 0x8; } */ // tiled if (num_parts == 1 && exr_images[0].tiles) { marker[1] |= 0x2; } // long_name if (long_name) { marker[1] |= 0x4; } // multipart if (num_parts > 1) { marker[1] |= 0x10; } memory.insert(memory.end(), marker, marker + 4); } int total_chunk_count = 0; std::vector<int> chunk_count(num_parts); std::vector<OffsetData> offset_data(num_parts); for (unsigned int i = 0; i < num_parts; ++i) { if (!exr_images[i].tiles) { int num_scanlines = NumScanlines(exr_headers[i]->compression_type); chunk_count[i] = (exr_images[i].height + num_scanlines - 1) / num_scanlines; InitSingleResolutionOffsets(offset_data[i], chunk_count[i]); total_chunk_count += chunk_count[i]; } else { { std::vector<int> num_x_tiles, num_y_tiles; PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_headers[i]); chunk_count[i] = InitTileOffsets(offset_data[i], exr_headers[i], num_x_tiles, num_y_tiles); total_chunk_count += chunk_count[i]; } } } // Write attributes to memory buffer. std::vector< std::vector<tinyexr::ChannelInfo> > channels(num_parts); { std::set<std::string> partnames; for (unsigned int i = 0; i < num_parts; ++i) { //channels { std::vector<unsigned char> data; for (int c = 0; c < exr_headers[i]->num_channels; c++) { tinyexr::ChannelInfo info; info.p_linear = 0; info.pixel_type = exr_headers[i]->requested_pixel_types[c]; info.x_sampling = 1; info.y_sampling = 1; info.name = std::string(exr_headers[i]->channels[c].name); channels[i].push_back(info); } tinyexr::WriteChannelInfo(data, channels[i]); tinyexr::WriteAttributeToMemory(&memory, "channels", "chlist", &data.at(0), static_cast<int>(data.size())); } { int comp = exr_headers[i]->compression_type; swap4(&comp); WriteAttributeToMemory( &memory, "compression", "compression", reinterpret_cast<const unsigned char*>(&comp), 1); } { int data[4] = { 0, 0, exr_images[i].width - 1, exr_images[i].height - 1 }; swap4(&data[0]); swap4(&data[1]); swap4(&data[2]); swap4(&data[3]); WriteAttributeToMemory( &memory, "dataWindow", "box2i", reinterpret_cast<const unsigned char*>(data), sizeof(int) * 4); int data0[4] = { 0, 0, exr_images[0].width - 1, exr_images[0].height - 1 }; swap4(&data0[0]); swap4(&data0[1]); swap4(&data0[2]); swap4(&data0[3]); // Note: must be the same across parts (currently, using value from the first header) WriteAttributeToMemory( &memory, "displayWindow", "box2i", reinterpret_cast<const unsigned char*>(data0), sizeof(int) * 4); } { unsigned char line_order = 0; // @fixme { read line_order from EXRHeader } WriteAttributeToMemory(&memory, "lineOrder", "lineOrder", &line_order, 1); } { // Note: must be the same across parts float aspectRatio = 1.0f; swap4(&aspectRatio); WriteAttributeToMemory( &memory, "pixelAspectRatio", "float", reinterpret_cast<const unsigned char*>(&aspectRatio), sizeof(float)); } { float center[2] = { 0.0f, 0.0f }; swap4(&center[0]); swap4(&center[1]); WriteAttributeToMemory( &memory, "screenWindowCenter", "v2f", reinterpret_cast<const unsigned char*>(center), 2 * sizeof(float)); } { float w = 1.0f; swap4(&w); WriteAttributeToMemory(&memory, "screenWindowWidth", "float", reinterpret_cast<const unsigned char*>(&w), sizeof(float)); } if (exr_images[i].tiles) { unsigned char tile_mode = static_cast<unsigned char>(exr_headers[i]->tile_level_mode & 0x3); if (exr_headers[i]->tile_rounding_mode) tile_mode |= (1u << 4u); //unsigned char data[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; unsigned int datai[3] = { 0, 0, 0 }; unsigned char* data = reinterpret_cast<unsigned char*>(&datai[0]); datai[0] = static_cast<unsigned int>(exr_headers[i]->tile_size_x); datai[1] = static_cast<unsigned int>(exr_headers[i]->tile_size_y); data[8] = tile_mode; swap4(reinterpret_cast<unsigned int*>(&data[0])); swap4(reinterpret_cast<unsigned int*>(&data[4])); WriteAttributeToMemory( &memory, "tiles", "tiledesc", reinterpret_cast<const unsigned char*>(data), 9); } // must be present for multi-part files - according to spec. if (num_parts > 1) { // name { size_t len = 0; if ((len = strlen(exr_headers[i]->name)) > 0) { partnames.insert(std::string(exr_headers[i]->name)); if (partnames.size() != i + 1) { SetErrorMessage("'name' attributes must be unique for a multi-part file", err); return 0; } WriteAttributeToMemory( &memory, "name", "string", reinterpret_cast<const unsigned char*>(exr_headers[i]->name), static_cast<int>(len)); } else { SetErrorMessage("Invalid 'name' attribute for a multi-part file", err); return 0; } } // type { const char* type = "scanlineimage"; if (exr_images[i].tiles) type = "tiledimage"; WriteAttributeToMemory( &memory, "type", "string", reinterpret_cast<const unsigned char*>(type), static_cast<int>(strlen(type))); } // chunkCount { WriteAttributeToMemory( &memory, "chunkCount", "int", reinterpret_cast<const unsigned char*>(&chunk_count[i]), 4); } } // Custom attributes if (exr_headers[i]->num_custom_attributes > 0) { for (int j = 0; j < exr_headers[i]->num_custom_attributes; j++) { tinyexr::WriteAttributeToMemory( &memory, exr_headers[i]->custom_attributes[j].name, exr_headers[i]->custom_attributes[j].type, reinterpret_cast<const unsigned char*>( exr_headers[i]->custom_attributes[j].value), exr_headers[i]->custom_attributes[j].size); } } { // end of header memory.push_back(0); } } } if (num_parts > 1) { // end of header list memory.push_back(0); } tinyexr_uint64 chunk_offset = memory.size() + size_t(total_chunk_count) * sizeof(tinyexr_uint64); tinyexr_uint64 total_size = 0; std::vector< std::vector< std::vector<unsigned char> > > data_lists(num_parts); for (unsigned int i = 0; i < num_parts; ++i) { std::string e; int ret = EncodeChunk(&exr_images[i], exr_headers[i], channels[i], chunk_count[i], // starting offset of current chunk after part-number chunk_offset, num_parts > 1, offset_data[i], // output: block offsets, must be initialized data_lists[i], // output total_size, // output &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty()) { tinyexr::SetErrorMessage(e, err); } return 0; } chunk_offset = total_size; } // Allocating required memory if (total_size == 0) { // something went wrong tinyexr::SetErrorMessage("Output memory size is zero", err); return 0; } (*memory_out) = static_cast<unsigned char*>(malloc(total_size)); // Writing header memcpy((*memory_out), &memory[0], memory.size()); unsigned char* memory_ptr = *memory_out + memory.size(); size_t sum = memory.size(); // Writing offset data for chunks for (unsigned int i = 0; i < num_parts; ++i) { if (exr_images[i].tiles) { const EXRImage* level_image = &exr_images[i]; int num_levels = (exr_headers[i]->tile_level_mode != TINYEXR_TILE_RIPMAP_LEVELS) ? offset_data[i].num_x_levels : (offset_data[i].num_x_levels * offset_data[i].num_y_levels); for (int level_index = 0; level_index < num_levels; ++level_index) { for (size_t j = 0; j < offset_data[i].offsets[level_index].size(); ++j) { size_t num_bytes = sizeof(tinyexr_uint64) * offset_data[i].offsets[level_index][j].size(); sum += num_bytes; assert(sum <= total_size); memcpy(memory_ptr, reinterpret_cast<unsigned char*>(&offset_data[i].offsets[level_index][j][0]), num_bytes); memory_ptr += num_bytes; } level_image = level_image->next_level; } } else { size_t num_bytes = sizeof(tinyexr::tinyexr_uint64) * static_cast<size_t>(chunk_count[i]); sum += num_bytes; assert(sum <= total_size); std::vector<tinyexr::tinyexr_uint64>& offsets = offset_data[i].offsets[0][0]; memcpy(memory_ptr, reinterpret_cast<unsigned char*>(&offsets[0]), num_bytes); memory_ptr += num_bytes; } } // Writing chunk data for (unsigned int i = 0; i < num_parts; ++i) { for (size_t j = 0; j < static_cast<size_t>(chunk_count[i]); ++j) { if (num_parts > 1) { sum += 4; assert(sum <= total_size); unsigned int part_number = i; swap4(&part_number); memcpy(memory_ptr, &part_number, 4); memory_ptr += 4; } sum += data_lists[i][j].size(); assert(sum <= total_size); memcpy(memory_ptr, &data_lists[i][j][0], data_lists[i][j].size()); memory_ptr += data_lists[i][j].size(); } } assert(sum == total_size); return total_size; // OK } } // tinyexr size_t SaveEXRImageToMemory(const EXRImage* exr_image, const EXRHeader* exr_header, unsigned char** memory_out, const char** err) { return tinyexr::SaveEXRNPartImageToMemory(exr_image, &exr_header, 1, memory_out, err); } int SaveEXRImageToFile(const EXRImage *exr_image, const EXRHeader *exr_header, const char *filename, const char **err) { if (exr_image == NULL || filename == NULL || exr_header->compression_type < 0) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #if !TINYEXR_USE_PIZ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { tinyexr::SetErrorMessage("PIZ compression is not supported in this build", err); return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } #endif #if !TINYEXR_USE_ZFP if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { tinyexr::SetErrorMessage("ZFP compression is not supported in this build", err); return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } #endif FILE *fp = NULL; #ifdef _WIN32 #if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang errno_t errcode = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"wb"); if (errcode != 0) { tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename), err); return TINYEXR_ERROR_CANT_WRITE_FILE; } #else // Unknown compiler fp = fopen(filename, "wb"); #endif #else fp = fopen(filename, "wb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename), err); return TINYEXR_ERROR_CANT_WRITE_FILE; } unsigned char *mem = NULL; size_t mem_size = SaveEXRImageToMemory(exr_image, exr_header, &mem, err); if (mem_size == 0) { return TINYEXR_ERROR_SERIALZATION_FAILED; } size_t written_size = 0; if ((mem_size > 0) && mem) { written_size = fwrite(mem, 1, mem_size, fp); } free(mem); fclose(fp); if (written_size != mem_size) { tinyexr::SetErrorMessage("Cannot write a file", err); return TINYEXR_ERROR_CANT_WRITE_FILE; } return TINYEXR_SUCCESS; } size_t SaveEXRMultipartImageToMemory(const EXRImage* exr_images, const EXRHeader** exr_headers, unsigned int num_parts, unsigned char** memory_out, const char** err) { if (exr_images == NULL || exr_headers == NULL || num_parts < 2 || memory_out == NULL) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRNPartImageToMemory", err); return 0; } return tinyexr::SaveEXRNPartImageToMemory(exr_images, exr_headers, num_parts, memory_out, err); } int SaveEXRMultipartImageToFile(const EXRImage* exr_images, const EXRHeader** exr_headers, unsigned int num_parts, const char* filename, const char** err) { if (exr_images == NULL || exr_headers == NULL || num_parts < 2) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRMultipartImageToFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } FILE *fp = NULL; #ifdef _WIN32 #if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang errno_t errcode = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"wb"); if (errcode != 0) { tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename), err); return TINYEXR_ERROR_CANT_WRITE_FILE; } #else // Unknown compiler fp = fopen(filename, "wb"); #endif #else fp = fopen(filename, "wb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot write a file: " + std::string(filename), err); return TINYEXR_ERROR_CANT_WRITE_FILE; } unsigned char *mem = NULL; size_t mem_size = SaveEXRMultipartImageToMemory(exr_images, exr_headers, num_parts, &mem, err); if (mem_size == 0) { return TINYEXR_ERROR_SERIALZATION_FAILED; } size_t written_size = 0; if ((mem_size > 0) && mem) { written_size = fwrite(mem, 1, mem_size, fp); } free(mem); fclose(fp); if (written_size != mem_size) { tinyexr::SetErrorMessage("Cannot write a file", err); return TINYEXR_ERROR_CANT_WRITE_FILE; } return TINYEXR_SUCCESS; } int LoadDeepEXR(DeepImage *deep_image, const char *filename, const char **err) { if (deep_image == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadDeepEXR", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; #if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang errno_t errcode = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb"); if (errcode != 0) { tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #else // Unknown compiler fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #else FILE *fp = fopen(filename, "rb"); if (!fp) { tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #endif size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (filesize == 0) { fclose(fp); tinyexr::SetErrorMessage("File size is zero : " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } std::vector<char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); (void)ret; } fclose(fp); const char *head = &buf[0]; const char *marker = &buf[0]; // Header check. { const char header[] = {0x76, 0x2f, 0x31, 0x01}; if (memcmp(marker, header, 4) != 0) { tinyexr::SetErrorMessage("Invalid magic number", err); return TINYEXR_ERROR_INVALID_MAGIC_NUMBER; } marker += 4; } // Version, scanline. { // ver 2.0, scanline, deep bit on(0x800) // must be [2, 0, 0, 0] if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) { tinyexr::SetErrorMessage("Unsupported version or scanline", err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } marker += 4; } int dx = -1; int dy = -1; int dw = -1; int dh = -1; int num_scanline_blocks = 1; // 16 for ZIP compression. int compression_type = -1; int num_channels = -1; std::vector<tinyexr::ChannelInfo> channels; // Read attributes size_t size = filesize - tinyexr::kEXRVersionSize; for (;;) { if (0 == size) { return TINYEXR_ERROR_INVALID_DATA; } else if (marker[0] == '\0') { marker++; size--; break; } std::string attr_name; std::string attr_type; std::vector<unsigned char> data; size_t marker_size; if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size, marker, size)) { std::stringstream ss; ss << "Failed to parse attribute\n"; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_INVALID_DATA; } marker += marker_size; size -= marker_size; if (attr_name.compare("compression") == 0) { compression_type = data[0]; if (compression_type > TINYEXR_COMPRESSIONTYPE_PIZ) { std::stringstream ss; ss << "Unsupported compression type : " << compression_type; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } } else if (attr_name.compare("channels") == 0) { // name: zero-terminated string, from 1 to 255 bytes long // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2 // pLinear: unsigned char, possible values are 0 and 1 // reserved: three chars, should be zero // xSampling: int // ySampling: int if (!tinyexr::ReadChannelInfo(channels, data)) { tinyexr::SetErrorMessage("Failed to parse channel info", err); return TINYEXR_ERROR_INVALID_DATA; } num_channels = static_cast<int>(channels.size()); if (num_channels < 1) { tinyexr::SetErrorMessage("Invalid channels format", err); return TINYEXR_ERROR_INVALID_DATA; } } else if (attr_name.compare("dataWindow") == 0) { memcpy(&dx, &data.at(0), sizeof(int)); memcpy(&dy, &data.at(4), sizeof(int)); memcpy(&dw, &data.at(8), sizeof(int)); memcpy(&dh, &data.at(12), sizeof(int)); tinyexr::swap4(&dx); tinyexr::swap4(&dy); tinyexr::swap4(&dw); tinyexr::swap4(&dh); } else if (attr_name.compare("displayWindow") == 0) { int x; int y; int w; int h; memcpy(&x, &data.at(0), sizeof(int)); memcpy(&y, &data.at(4), sizeof(int)); memcpy(&w, &data.at(8), sizeof(int)); memcpy(&h, &data.at(12), sizeof(int)); tinyexr::swap4(&x); tinyexr::swap4(&y); tinyexr::swap4(&w); tinyexr::swap4(&h); } } assert(dx >= 0); assert(dy >= 0); assert(dw >= 0); assert(dh >= 0); assert(num_channels >= 1); int data_width = dw - dx + 1; int data_height = dh - dy + 1; std::vector<float> image( static_cast<size_t>(data_width * data_height * 4)); // 4 = RGBA // Read offset tables. int num_blocks = data_height / num_scanline_blocks; if (num_blocks * num_scanline_blocks < data_height) { num_blocks++; } std::vector<tinyexr::tinyexr_int64> offsets(static_cast<size_t>(num_blocks)); for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) { tinyexr::tinyexr_int64 offset; memcpy(&offset, marker, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offset)); marker += sizeof(tinyexr::tinyexr_int64); // = 8 offsets[y] = offset; } #if TINYEXR_USE_PIZ if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) || (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) || (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ)) { #else if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) || (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) { #endif // OK } else { tinyexr::SetErrorMessage("Unsupported compression format", err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } deep_image->image = static_cast<float ***>( malloc(sizeof(float **) * static_cast<size_t>(num_channels))); for (int c = 0; c < num_channels; c++) { deep_image->image[c] = static_cast<float **>( malloc(sizeof(float *) * static_cast<size_t>(data_height))); for (int y = 0; y < data_height; y++) { } } deep_image->offset_table = static_cast<int **>( malloc(sizeof(int *) * static_cast<size_t>(data_height))); for (int y = 0; y < data_height; y++) { deep_image->offset_table[y] = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(data_width))); } for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) { const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[y]); // int: y coordinate // int64: packed size of pixel offset table // int64: packed size of sample data // int64: unpacked size of sample data // compressed pixel offset table // compressed sample data int line_no; tinyexr::tinyexr_int64 packedOffsetTableSize; tinyexr::tinyexr_int64 packedSampleDataSize; tinyexr::tinyexr_int64 unpackedSampleDataSize; memcpy(&line_no, data_ptr, sizeof(int)); memcpy(&packedOffsetTableSize, data_ptr + 4, sizeof(tinyexr::tinyexr_int64)); memcpy(&packedSampleDataSize, data_ptr + 12, sizeof(tinyexr::tinyexr_int64)); memcpy(&unpackedSampleDataSize, data_ptr + 20, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap4(&line_no); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedOffsetTableSize)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedSampleDataSize)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&unpackedSampleDataSize)); std::vector<int> pixelOffsetTable(static_cast<size_t>(data_width)); // decode pixel offset table. { unsigned long dstLen = static_cast<unsigned long>(pixelOffsetTable.size() * sizeof(int)); if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)), &dstLen, data_ptr + 28, static_cast<unsigned long>(packedOffsetTableSize))) { return false; } assert(dstLen == pixelOffsetTable.size() * sizeof(int)); for (size_t i = 0; i < static_cast<size_t>(data_width); i++) { deep_image->offset_table[y][i] = pixelOffsetTable[i]; } } std::vector<unsigned char> sample_data( static_cast<size_t>(unpackedSampleDataSize)); // decode sample data. { unsigned long dstLen = static_cast<unsigned long>(unpackedSampleDataSize); if (dstLen) { if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&sample_data.at(0)), &dstLen, data_ptr + 28 + packedOffsetTableSize, static_cast<unsigned long>(packedSampleDataSize))) { return false; } assert(dstLen == static_cast<unsigned long>(unpackedSampleDataSize)); } } // decode sample int sampleSize = -1; std::vector<int> channel_offset_list(static_cast<size_t>(num_channels)); { int channel_offset = 0; for (size_t i = 0; i < static_cast<size_t>(num_channels); i++) { channel_offset_list[i] = channel_offset; if (channels[i].pixel_type == TINYEXR_PIXELTYPE_UINT) { // UINT channel_offset += 4; } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_HALF) { // half channel_offset += 2; } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { // float channel_offset += 4; } else { assert(0); } } sampleSize = channel_offset; } assert(sampleSize >= 2); assert(static_cast<size_t>( pixelOffsetTable[static_cast<size_t>(data_width - 1)] * sampleSize) == sample_data.size()); int samples_per_line = static_cast<int>(sample_data.size()) / sampleSize; // // Alloc memory // // // pixel data is stored as image[channels][pixel_samples] // { tinyexr::tinyexr_uint64 data_offset = 0; for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { deep_image->image[c][y] = static_cast<float *>( malloc(sizeof(float) * static_cast<size_t>(samples_per_line))); if (channels[c].pixel_type == 0) { // UINT for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { unsigned int ui; unsigned int *src_ptr = reinterpret_cast<unsigned int *>( &sample_data.at(size_t(data_offset) + x * sizeof(int))); tinyexr::cpy4(&ui, src_ptr); deep_image->image[c][y][x] = static_cast<float>(ui); // @fixme } data_offset += sizeof(unsigned int) * static_cast<size_t>(samples_per_line); } else if (channels[c].pixel_type == 1) { // half for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { tinyexr::FP16 f16; const unsigned short *src_ptr = reinterpret_cast<unsigned short *>( &sample_data.at(size_t(data_offset) + x * sizeof(short))); tinyexr::cpy2(&(f16.u), src_ptr); tinyexr::FP32 f32 = half_to_float(f16); deep_image->image[c][y][x] = f32.f; } data_offset += sizeof(short) * static_cast<size_t>(samples_per_line); } else { // float for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { float f; const float *src_ptr = reinterpret_cast<float *>( &sample_data.at(size_t(data_offset) + x * sizeof(float))); tinyexr::cpy4(&f, src_ptr); deep_image->image[c][y][x] = f; } data_offset += sizeof(float) * static_cast<size_t>(samples_per_line); } } } } // y deep_image->width = data_width; deep_image->height = data_height; deep_image->channel_names = static_cast<const char **>( malloc(sizeof(const char *) * static_cast<size_t>(num_channels))); for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { #ifdef _WIN32 deep_image->channel_names[c] = _strdup(channels[c].name.c_str()); #else deep_image->channel_names[c] = strdup(channels[c].name.c_str()); #endif } deep_image->num_channels = num_channels; return TINYEXR_SUCCESS; } void InitEXRImage(EXRImage *exr_image) { if (exr_image == NULL) { return; } exr_image->width = 0; exr_image->height = 0; exr_image->num_channels = 0; exr_image->images = NULL; exr_image->tiles = NULL; exr_image->next_level = NULL; exr_image->level_x = 0; exr_image->level_y = 0; exr_image->num_tiles = 0; } void FreeEXRErrorMessage(const char *msg) { if (msg) { free(reinterpret_cast<void *>(const_cast<char *>(msg))); } return; } void InitEXRHeader(EXRHeader *exr_header) { if (exr_header == NULL) { return; } memset(exr_header, 0, sizeof(EXRHeader)); } int FreeEXRHeader(EXRHeader *exr_header) { if (exr_header == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_header->channels) { free(exr_header->channels); } if (exr_header->pixel_types) { free(exr_header->pixel_types); } if (exr_header->requested_pixel_types) { free(exr_header->requested_pixel_types); } for (int i = 0; i < exr_header->num_custom_attributes; i++) { if (exr_header->custom_attributes[i].value) { free(exr_header->custom_attributes[i].value); } } if (exr_header->custom_attributes) { free(exr_header->custom_attributes); } EXRSetNameAttr(exr_header, NULL); return TINYEXR_SUCCESS; } void EXRSetNameAttr(EXRHeader* exr_header, const char* name) { if (exr_header == NULL) { return; } memset(exr_header->name, 0, 256); if (name != NULL) { size_t len = std::min(strlen(name), size_t(255)); if (len) { memcpy(exr_header->name, name, len); } } } int EXRNumLevels(const EXRImage* exr_image) { if (exr_image == NULL) return 0; if(exr_image->images) return 1; // scanlines int levels = 1; const EXRImage* level_image = exr_image; while((level_image = level_image->next_level)) ++levels; return levels; } int FreeEXRImage(EXRImage *exr_image) { if (exr_image == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_image->next_level) { FreeEXRImage(exr_image->next_level); delete exr_image->next_level; } for (int i = 0; i < exr_image->num_channels; i++) { if (exr_image->images && exr_image->images[i]) { free(exr_image->images[i]); } } if (exr_image->images) { free(exr_image->images); } if (exr_image->tiles) { for (int tid = 0; tid < exr_image->num_tiles; tid++) { for (int i = 0; i < exr_image->num_channels; i++) { if (exr_image->tiles[tid].images && exr_image->tiles[tid].images[i]) { free(exr_image->tiles[tid].images[i]); } } if (exr_image->tiles[tid].images) { free(exr_image->tiles[tid].images); } } free(exr_image->tiles); } return TINYEXR_SUCCESS; } int ParseEXRHeaderFromFile(EXRHeader *exr_header, const EXRVersion *exr_version, const char *filename, const char **err) { if (exr_header == NULL || exr_version == NULL || filename == NULL) { tinyexr::SetErrorMessage("Invalid argument for ParseEXRHeaderFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } FILE *fp = NULL; #ifdef _WIN32 #if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang errno_t errcode = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb"); if (errcode != 0) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } #else // Unknown compiler fp = fopen(filename, "rb"); #endif #else fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); if (ret != filesize) { tinyexr::SetErrorMessage("fread() error on " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } } return ParseEXRHeaderFromMemory(exr_header, exr_version, &buf.at(0), filesize, err); } int ParseEXRMultipartHeaderFromMemory(EXRHeader ***exr_headers, int *num_headers, const EXRVersion *exr_version, const unsigned char *memory, size_t size, const char **err) { if (memory == NULL || exr_headers == NULL || num_headers == NULL || exr_version == NULL) { // Invalid argument tinyexr::SetErrorMessage( "Invalid argument for ParseEXRMultipartHeaderFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { tinyexr::SetErrorMessage("Data size too short", err); return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory + tinyexr::kEXRVersionSize; size_t marker_size = size - tinyexr::kEXRVersionSize; std::vector<tinyexr::HeaderInfo> infos; for (;;) { tinyexr::HeaderInfo info; info.clear(); std::string err_str; bool empty_header = false; int ret = ParseEXRHeader(&info, &empty_header, exr_version, &err_str, marker, marker_size); if (ret != TINYEXR_SUCCESS) { tinyexr::SetErrorMessage(err_str, err); return ret; } if (empty_header) { marker += 1; // skip '\0' break; } // `chunkCount` must exist in the header. if (info.chunk_count == 0) { tinyexr::SetErrorMessage( "`chunkCount' attribute is not found in the header.", err); return TINYEXR_ERROR_INVALID_DATA; } infos.push_back(info); // move to next header. marker += info.header_len; size -= info.header_len; } // allocate memory for EXRHeader and create array of EXRHeader pointers. (*exr_headers) = static_cast<EXRHeader **>(malloc(sizeof(EXRHeader *) * infos.size())); for (size_t i = 0; i < infos.size(); i++) { EXRHeader *exr_header = static_cast<EXRHeader *>(malloc(sizeof(EXRHeader))); memset(exr_header, 0, sizeof(EXRHeader)); ConvertHeader(exr_header, infos[i]); exr_header->multipart = exr_version->multipart ? 1 : 0; (*exr_headers)[i] = exr_header; } (*num_headers) = static_cast<int>(infos.size()); return TINYEXR_SUCCESS; } int ParseEXRMultipartHeaderFromFile(EXRHeader ***exr_headers, int *num_headers, const EXRVersion *exr_version, const char *filename, const char **err) { if (exr_headers == NULL || num_headers == NULL || exr_version == NULL || filename == NULL) { tinyexr::SetErrorMessage( "Invalid argument for ParseEXRMultipartHeaderFromFile()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } FILE *fp = NULL; #ifdef _WIN32 #if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang errno_t errcode = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb"); if (errcode != 0) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } #else // Unknown compiler fp = fopen(filename, "rb"); #endif #else fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); if (ret != filesize) { tinyexr::SetErrorMessage("`fread' error. file may be corrupted.", err); return TINYEXR_ERROR_INVALID_FILE; } } return ParseEXRMultipartHeaderFromMemory( exr_headers, num_headers, exr_version, &buf.at(0), filesize, err); } int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory, size_t size) { if (version == NULL || memory == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory; // Header check. { const char header[] = {0x76, 0x2f, 0x31, 0x01}; if (memcmp(marker, header, 4) != 0) { return TINYEXR_ERROR_INVALID_MAGIC_NUMBER; } marker += 4; } version->tiled = false; version->long_name = false; version->non_image = false; version->multipart = false; // Parse version header. { // must be 2 if (marker[0] != 2) { return TINYEXR_ERROR_INVALID_EXR_VERSION; } if (version == NULL) { return TINYEXR_SUCCESS; // May OK } version->version = 2; if (marker[1] & 0x2) { // 9th bit version->tiled = true; } if (marker[1] & 0x4) { // 10th bit version->long_name = true; } if (marker[1] & 0x8) { // 11th bit version->non_image = true; // (deep image) } if (marker[1] & 0x10) { // 12th bit version->multipart = true; } } return TINYEXR_SUCCESS; } int ParseEXRVersionFromFile(EXRVersion *version, const char *filename) { if (filename == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } FILE *fp = NULL; #ifdef _WIN32 #if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang errno_t err = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb"); if (err != 0) { // TODO(syoyo): return wfopen_s erro code return TINYEXR_ERROR_CANT_OPEN_FILE; } #else // Unknown compiler fp = fopen(filename, "rb"); #endif #else fp = fopen(filename, "rb"); #endif if (!fp) { return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t file_size; // Compute size fseek(fp, 0, SEEK_END); file_size = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (file_size < tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_FILE; } unsigned char buf[tinyexr::kEXRVersionSize]; size_t ret = fread(&buf[0], 1, tinyexr::kEXRVersionSize, fp); fclose(fp); if (ret != tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_FILE; } return ParseEXRVersionFromMemory(version, buf, tinyexr::kEXRVersionSize); } int LoadEXRMultipartImageFromMemory(EXRImage *exr_images, const EXRHeader **exr_headers, unsigned int num_parts, const unsigned char *memory, const size_t size, const char **err) { if (exr_images == NULL || exr_headers == NULL || num_parts == 0 || memory == NULL || (size <= tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage( "Invalid argument for LoadEXRMultipartImageFromMemory()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } // compute total header size. size_t total_header_size = 0; for (unsigned int i = 0; i < num_parts; i++) { if (exr_headers[i]->header_len == 0) { tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } total_header_size += exr_headers[i]->header_len; } const char *marker = reinterpret_cast<const char *>( memory + total_header_size + 4 + 4); // +8 for magic number and version header. marker += 1; // Skip empty header. // NOTE 1: // In multipart image, There is 'part number' before chunk data. // 4 byte : part number // 4+ : chunk // // NOTE 2: // EXR spec says 'part number' is 'unsigned long' but actually this is // 'unsigned int(4 bytes)' in OpenEXR implementation... // http://www.openexr.com/openexrfilelayout.pdf // Load chunk offset table. std::vector<tinyexr::OffsetData> chunk_offset_table_list; chunk_offset_table_list.reserve(num_parts); for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) { chunk_offset_table_list.resize(chunk_offset_table_list.size() + 1); tinyexr::OffsetData& offset_data = chunk_offset_table_list.back(); if (!exr_headers[i]->tiled || exr_headers[i]->tile_level_mode == TINYEXR_TILE_ONE_LEVEL) { tinyexr::InitSingleResolutionOffsets(offset_data, exr_headers[i]->chunk_count); std::vector<tinyexr::tinyexr_uint64>& offset_table = offset_data.offsets[0][0]; for (size_t c = 0; c < offset_table.size(); c++) { tinyexr::tinyexr_uint64 offset; memcpy(&offset, marker, 8); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.", err); return TINYEXR_ERROR_INVALID_DATA; } offset_table[c] = offset + 4; // +4 to skip 'part number' marker += 8; } } else { { std::vector<int> num_x_tiles, num_y_tiles; tinyexr::PrecalculateTileInfo(num_x_tiles, num_y_tiles, exr_headers[i]); int num_blocks = InitTileOffsets(offset_data, exr_headers[i], num_x_tiles, num_y_tiles); if (num_blocks != exr_headers[i]->chunk_count) { tinyexr::SetErrorMessage("Invalid offset table size.", err); return TINYEXR_ERROR_INVALID_DATA; } } for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) { for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) { for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) { tinyexr::tinyexr_uint64 offset; memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64)); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.", err); return TINYEXR_ERROR_INVALID_DATA; } offset_data.offsets[l][dy][dx] = offset + 4; // +4 to skip 'part number' marker += sizeof(tinyexr::tinyexr_uint64); // = 8 } } } } } // Decode image. for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) { tinyexr::OffsetData &offset_data = chunk_offset_table_list[i]; // First check 'part number' is identitical to 'i' for (unsigned int l = 0; l < offset_data.offsets.size(); ++l) for (unsigned int dy = 0; dy < offset_data.offsets[l].size(); ++dy) for (unsigned int dx = 0; dx < offset_data.offsets[l][dy].size(); ++dx) { const unsigned char *part_number_addr = memory + offset_data.offsets[l][dy][dx] - 4; // -4 to move to 'part number' field. unsigned int part_no; memcpy(&part_no, part_number_addr, sizeof(unsigned int)); // 4 tinyexr::swap4(&part_no); if (part_no != i) { tinyexr::SetErrorMessage("Invalid `part number' in EXR header chunks.", err); return TINYEXR_ERROR_INVALID_DATA; } } std::string e; int ret = tinyexr::DecodeChunk(&exr_images[i], exr_headers[i], offset_data, memory, size, &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty()) { tinyexr::SetErrorMessage(e, err); } return ret; } } return TINYEXR_SUCCESS; } int LoadEXRMultipartImageFromFile(EXRImage *exr_images, const EXRHeader **exr_headers, unsigned int num_parts, const char *filename, const char **err) { if (exr_images == NULL || exr_headers == NULL || num_parts == 0) { tinyexr::SetErrorMessage( "Invalid argument for LoadEXRMultipartImageFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } FILE *fp = NULL; #ifdef _WIN32 #if defined(_MSC_VER) || defined(__MINGW32__) // MSVC, MinGW gcc or clang errno_t errcode = _wfopen_s(&fp, tinyexr::UTF8ToWchar(filename).c_str(), L"rb"); if (errcode != 0) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #else // Unknown compiler fp = fopen(filename, "rb"); #endif #else fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); (void)ret; } return LoadEXRMultipartImageFromMemory(exr_images, exr_headers, num_parts, &buf.at(0), filesize, err); } int SaveEXR(const float *data, int width, int height, int components, const int save_as_fp16, const char *outfilename, const char **err) { if ((components == 1) || components == 3 || components == 4) { // OK } else { std::stringstream ss; ss << "Unsupported component value : " << components << std::endl; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRHeader header; InitEXRHeader(&header); if ((width < 16) && (height < 16)) { // No compression for small image. header.compression_type = TINYEXR_COMPRESSIONTYPE_NONE; } else { header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP; } EXRImage image; InitEXRImage(&image); image.num_channels = components; std::vector<float> images[4]; if (components == 1) { images[0].resize(static_cast<size_t>(width * height)); memcpy(images[0].data(), data, sizeof(float) * size_t(width * height)); } else { images[0].resize(static_cast<size_t>(width * height)); images[1].resize(static_cast<size_t>(width * height)); images[2].resize(static_cast<size_t>(width * height)); images[3].resize(static_cast<size_t>(width * height)); // Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers for (size_t i = 0; i < static_cast<size_t>(width * height); i++) { images[0][i] = data[static_cast<size_t>(components) * i + 0]; images[1][i] = data[static_cast<size_t>(components) * i + 1]; images[2][i] = data[static_cast<size_t>(components) * i + 2]; if (components == 4) { images[3][i] = data[static_cast<size_t>(components) * i + 3]; } } } float *image_ptr[4] = {0, 0, 0, 0}; if (components == 4) { image_ptr[0] = &(images[3].at(0)); // A image_ptr[1] = &(images[2].at(0)); // B image_ptr[2] = &(images[1].at(0)); // G image_ptr[3] = &(images[0].at(0)); // R } else if (components == 3) { image_ptr[0] = &(images[2].at(0)); // B image_ptr[1] = &(images[1].at(0)); // G image_ptr[2] = &(images[0].at(0)); // R } else if (components == 1) { image_ptr[0] = &(images[0].at(0)); // A } image.images = reinterpret_cast<unsigned char **>(image_ptr); image.width = width; image.height = height; header.num_channels = components; header.channels = static_cast<EXRChannelInfo *>(malloc( sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels))); // Must be (A)BGR order, since most of EXR viewers expect this channel order. if (components == 4) { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "A", 255); strncpy_s(header.channels[1].name, "B", 255); strncpy_s(header.channels[2].name, "G", 255); strncpy_s(header.channels[3].name, "R", 255); #else strncpy(header.channels[0].name, "A", 255); strncpy(header.channels[1].name, "B", 255); strncpy(header.channels[2].name, "G", 255); strncpy(header.channels[3].name, "R", 255); #endif header.channels[0].name[strlen("A")] = '\0'; header.channels[1].name[strlen("B")] = '\0'; header.channels[2].name[strlen("G")] = '\0'; header.channels[3].name[strlen("R")] = '\0'; } else if (components == 3) { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "B", 255); strncpy_s(header.channels[1].name, "G", 255); strncpy_s(header.channels[2].name, "R", 255); #else strncpy(header.channels[0].name, "B", 255); strncpy(header.channels[1].name, "G", 255); strncpy(header.channels[2].name, "R", 255); #endif header.channels[0].name[strlen("B")] = '\0'; header.channels[1].name[strlen("G")] = '\0'; header.channels[2].name[strlen("R")] = '\0'; } else { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "A", 255); #else strncpy(header.channels[0].name, "A", 255); #endif header.channels[0].name[strlen("A")] = '\0'; } header.pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(header.num_channels))); header.requested_pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(header.num_channels))); for (int i = 0; i < header.num_channels; i++) { header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image if (save_as_fp16 > 0) { header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format } else { header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e. // no precision reduction) } } int ret = SaveEXRImageToFile(&image, &header, outfilename, err); if (ret != TINYEXR_SUCCESS) { return ret; } free(header.channels); free(header.pixel_types); free(header.requested_pixel_types); return ret; } #ifdef __clang__ // zero-as-null-ppinter-constant #pragma clang diagnostic pop #endif #endif // TINYEXR_IMPLEMENTATION_DEFINED #endif // TINYEXR_IMPLEMENTATION
mmap_send.c
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <unistd.h> #include <string.h> int main() { int threads = 16; int msg_size = 2048*64; size_t size = threads * msg_size; int fd = open("/tmp/testmmap", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); ftruncate(fd, size + 4096); volatile char *buf = (char*)mmap(NULL, 4096 + size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); char *src = (char*)malloc(size); for (size_t i = 0; i < threads; i++) { buf[i] = 1; } for (size_t i = 0; i < size; i++) { src[i] = i; } #pragma omp parallel for for (size_t i = 0; i < threads; i++) { size_t off = i * size/threads; for (int j = 0; j < 1e3; j++) { memset(src+off, (char)i, size/threads); while (buf[i] == 0) { } memcpy(buf+(off+4096), src+off, size/threads); buf[i] = 0; } } return 0; }
GB_binop__isgt_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__isgt_uint64 // A.*B function (eWiseMult): GB_AemultB__isgt_uint64 // A*D function (colscale): GB_AxD__isgt_uint64 // D*A function (rowscale): GB_DxB__isgt_uint64 // C+=B function (dense accum): GB_Cdense_accumB__isgt_uint64 // C+=b function (dense accum): GB_Cdense_accumb__isgt_uint64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__isgt_uint64 // C=scalar+B GB_bind1st__isgt_uint64 // C=scalar+B' GB_bind1st_tran__isgt_uint64 // C=A+scalar GB_bind2nd__isgt_uint64 // C=A'+scalar GB_bind2nd_tran__isgt_uint64 // C type: uint64_t // A type: uint64_t // B,b type: uint64_t // BinaryOp: cij = (aij > bij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = (x > y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISGT || GxB_NO_UINT64 || GxB_NO_ISGT_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__isgt_uint64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__isgt_uint64 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__isgt_uint64 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__isgt_uint64 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *GB_RESTRICT Cx = (uint64_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__isgt_uint64 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *GB_RESTRICT Cx = (uint64_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__isgt_uint64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__isgt_uint64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__isgt_uint64 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint64_t bij = Bx [p] ; Cx [p] = (x > bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__isgt_uint64 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint64_t aij = Ax [p] ; Cx [p] = (aij > y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = (x > aij) ; \ } GrB_Info GB_bind1st_tran__isgt_uint64 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = (aij > y) ; \ } GrB_Info GB_bind2nd_tran__isgt_uint64 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t y = (*((const uint64_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
ChainCollectionLearner.h
/** * @file ChainCollectionLearner.h * @brief header file of the CRF chain model learner * * .. invisible: * _ _ _____ _ _____ _____ * * | | | | ___| | | ___/ ___| * * | | | | |__ | | | |__ \ `--. * * | | | | __|| | | __| `--. \ * * \ \_/ / |___| |___| |___/\__/ / * * \___/\____/\_____|____/\____/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License * */ #ifndef CHAIN_COLLECTION_LEARNER #define CHAIN_COLLECTION_LEARNER #include <string> #include <vector> #include <memory> #include <iostream> #include <unordered_map> #include <unordered_set> #include <omp.h> #include <tuple> #include "IChainTransformer.h" #include "ChainOptimizable.h" #include "IPossibleStateFinder.h" #include "IRegularization.h" #include "VectorFactorsExtractor.h" #include "Factors.h" #include "LBFGS.h" #include "CRF.h" #include "State.h" #include "CRFBinaryWriter.h" #include "CRFBinaryReader.h" #include "ChainCollectionTester.h" using std::string; using std::vector; using std::shared_ptr; using std::cout; using std::unordered_map; using std::unordered_set; using std::tuple; using std::wcout; using std::wcin; #define CHAIN_COLLECTION_LEARNER_TEMPLATE template < \ class Optimizer_ \ , class Tester_ \ , ConsideringOfFeaturesInCliques typeOfFeaturesConsideration> #define CHAIN_COLLECTION_LEARNER_TEMPLATE1 ChainCollectionLearner< \ Optimizer_, Tester_, typeOfFeaturesConsideration> namespace LinearCRF { const string problemChainsFile = "IndexesOfProblemSentences.txt"; static int MAX_NUMBER_IN_TRAINING_SET = 10000000; /** * @class ChainCollectionLearner * @brief CRF chain model learner */ CHAIN_COLLECTION_LEARNER_TEMPLATE class ChainCollectionLearner : public Optimization::IOptimizable , public Optimization::ICallable { public: typedef ChainOptimizable<typeOfFeaturesConsideration> OptimizableChain; typedef Optimizer_ Optimizer; typedef Tester_ Tester; ChainCollectionLearner() {} /** * @brief Constructor. Reads file filled in special <token features label> format * @param[in] trainingSetFile - file for training * @param[in] testSetFile - file for testing intermediate results * @param[in] ChainTransformer - transforms each chain * @param[in] possibleStateFinder - finds possible states of chains (only using features) * @param[in] regularizationFactor - factor used for smoothing optimizable function */ ChainCollectionLearner( const string& trainingSetFile , const string& testSetFile , const string& outputFile , shared_ptr<IChainTransformer> ChainTransformer , shared_ptr<IPossibleStateFinder> possibleStateFinder , shared_ptr<IRegularization> regularizator); /** * @brief Prints chain in the form that enables to check correctness of pipe and possible state finder * (token, label, possible states) * @param[in] file - file where to print results */ void PrintForChecking(const string& file); /** * @brief Prints chain in the form that enables to check correctness of pipe and possible state finder * (token, label, possible states) * @param[in] file - file where to print results * @param[in] sentenceIndex - index of sentence in training set */ void PrintOneSentenceForChecking(const string& file, int sentenceIndex); /** * @brief Destructor */ ~ChainCollectionLearner(void); /** * @brief Calculates log probability of the chain * @param[in] point - parameters for calculations */ double CalculateValue(const vector<double>& point); /** * @brief Calculates gradient of log probability of the chain * @param[in] point - parameters for calculations * @param[out] gradient - gradient of log probability of the chain */ void CalculateGradient( const vector<double>& point, vector<double>* gradient); /** * @brief Finds optimal parameters for CRF * @param[in] numberOfIterations - max number of gradient descent steps * @param[in] periodOfTesting - period of iterations when preliminary tester starts evaluation * @param[in] periodOfPriniting - period of iterations when the model is saved to auxiliary file */ virtual CRF Learn(int numberOfIterations, int periodOfTesting , int periodOfPriniting); /** * @brief Evaluates auxiliary results and decides if it's time to stop learning * @param[in] currentIteration - iteration of gradient calculations * @param[in] _parameters - current parameters of the model * @param[in] dimension - size of parameters */ virtual bool Call(int currentIteration , const double* _parameters , int dimension); /** * @brief Gets vector factors extractor. For example, can be used to get special regularization in relearning */ shared_ptr<VectorFactorsExtractor> GetVectorFactorsExtractor(); string outputFile; shared_ptr<IChainTransformer> chainTransformer; /**< ChainTransformer transforming chains from file into some prefered format*/ shared_ptr<IPossibleStateFinder> possibleStateFinder; /**< Enables to find possible states of chains (only using features)*/ shared_ptr<IRegularization> regularizator; /**< Factor used for smoothing optimizable function*/ shared_ptr<Alphabet> weightAlphabet; /**< cliques of CRF*/ shared_ptr<Alphabet> inputAlphabet; /**< features for CRF*/ shared_ptr<Alphabet> outputAlphabet; /**< hidden labels of CRF*/ shared_ptr<TransitionConverter> transitionConverter; /**< converts tranisition (input index to output index) to index of weightAlphabet*/ shared_ptr<VectorFactorsExtractor> vectorFactorsExtractor; /**< enables to find CRF parameters from vector*/ vector<OptimizableChain> chains; /**< data for learning*/ int periodOfTesting; /**< period of iterations when preliminary tester starts evaluation*/ int periodOfPrinting; /**< period of iterations when the model is saved to auxiliary file*/ CRF outputModel; /**< model that should be learned and printed by the algorithm*/ Tester tester; /**< evaluates intermediate results of the algorithm*/ bool areValueAndGradientCalculated /**< gradient and value are calculated together at once. This variable enables not to recalculate them in alternating call of CalculateValue and CalculateGradient*/; double value; vector<double> gradient; /** * @brief Gets chains optimizables from file * @param[in] file - file to read */ void readFile(const string& file); /** * @brief Finds possible features for each clique */ unordered_map<int, unordered_set<int> > findCliquePossibleFeatures(); /** * @brief Initializes vectorFactorsExtractor */ void initializeVectorFactorsExtractor(); /** * @brief Prints some information after chains are downloaded */ void printResultsOfInitialization(); /** * @brief Calculates value and gradient; Calculate value and gradient calls this function * @param[in] point - parameters to optimize */ void calculateGradientAndValue(const vector<double>& point); /** * @brief Finds states that are used in output CRF model * @param[in] crf - crf model */ shared_ptr<vector<State> > getStates(CRF* crf); /** * @brief Finds cliques data that is used in output CRF model * @param[in] factorsVector - parameters of the model */ shared_ptr<vector<unordered_map<int, double> > > getCliquesData( const vector<double>& factorsVector); /** * @brief After the training file is read we full alphabets and states in outputModel */ void initializeOutputModel(); /** * @brief Reads data for tester */ void initializeTester(const string& testSetFile); /** * @brief Fills crf-model with calculated content * @param[in] factorsVector - parameters of the model */ void fillOutputModel(const vector<double>& factorsVector); /** * @brief Verifies if possible states are correct in chain * @param[in] chain - chain to process */ bool checkChain(const Chain& chain); /** * @brief Constructs transitionConverter by CRF-model * @param[in] i_crf - CRF-model */ void fillTransitionConverter(const CRF& i_crf); }; CHAIN_COLLECTION_LEARNER_TEMPLATE CHAIN_COLLECTION_LEARNER_TEMPLATE1::ChainCollectionLearner( const string& trainingSetFile , const string& testSetFile , const string& outputFile , shared_ptr<IChainTransformer> chainTransformer , shared_ptr<IPossibleStateFinder> possibleStateFinder , shared_ptr<IRegularization> regularizator) : outputFile(outputFile) , chainTransformer(chainTransformer) , possibleStateFinder(possibleStateFinder) , regularizator(regularizator) , weightAlphabet(new Alphabet()) , inputAlphabet(new Alphabet()) , outputAlphabet(new Alphabet()) , transitionConverter(new TransitionConverter) , areValueAndGradientCalculated(false) { wcout << "ChainCollectionLearner: number of cores: " << omp_get_num_procs() << std::endl; vectorFactorsExtractor = std::make_shared<VectorFactorsExtractor>(); readFile(trainingSetFile); initializeVectorFactorsExtractor(); dimension = vectorFactorsExtractor->GetDimension(); initializeOutputModel(); initializeTester(testSetFile); printResultsOfInitialization(); } CHAIN_COLLECTION_LEARNER_TEMPLATE void CHAIN_COLLECTION_LEARNER_TEMPLATE1::readFile(const string& file) { wcout << "ChainCollectionLearner: starting reading file..." << std::endl; // Create auxiliary iterators, etc. int enumerator = 0; int badChainsEnumerator = 0; wifstream in(file); Tools::SetLocale(in); Chain chain; // Iterate over file while(in >> chain) { if (chain.GetSize() == 0) { break; } // Pass chain through ChainTransformer Chain transformedChain = chainTransformer->ForwardTransform(chain); possibleStateFinder->FindPossibleStates(&transformedChain); if (checkChain(transformedChain)) { // Transform chain to digital format and insert to the collection chains.emplace_back( OptimizableChain( transitionConverter, vectorFactorsExtractor , weightAlphabet, inputAlphabet , outputAlphabet, transformedChain)); } else { ++badChainsEnumerator; } // Print status of data downloading ++enumerator; wcout << L"\rHave evaluated " << enumerator << L" chains, number of bad chains = " << badChainsEnumerator; if (enumerator > MAX_NUMBER_IN_TRAINING_SET) { break; } } in.close(); wcout << L"\rHave evaluated " << chains.size() << " chains..."; wcout << L"\nChainCollectionLearner: end reading file...\n"; } CHAIN_COLLECTION_LEARNER_TEMPLATE unordered_map<int, unordered_set<int> > CHAIN_COLLECTION_LEARNER_TEMPLATE1:: findCliquePossibleFeatures() { wcout << L"\nFinding possible features for cliques...\n"; unordered_map<int, unordered_set<int> > cliquePossibleFeatures; for (int iter = 0; iter < weightAlphabet->Size(); ++iter) { cliquePossibleFeatures[iter] = unordered_set<int>(); } for (size_t chainEnumerator = 0; chainEnumerator < chains.size(); ++chainEnumerator) { chains[chainEnumerator].UpdateCliquePossibleFeatures( &cliquePossibleFeatures); wcout << L"\rHave evaluated " << chainEnumerator << L" chains..."; } return cliquePossibleFeatures; } CHAIN_COLLECTION_LEARNER_TEMPLATE void CHAIN_COLLECTION_LEARNER_TEMPLATE1::initializeVectorFactorsExtractor() { unordered_map<int, unordered_set<int> > cliquePossibleFeatures = findCliquePossibleFeatures(); wcout << "\nInitializing vectors factor extractor...\n"; vectorFactorsExtractor->Initialize( outputAlphabet->Size(), inputAlphabet->Size(), weightAlphabet->Size(), cliquePossibleFeatures); wcout << "\nEnd initializing vectors factor extractor...\n"; } CHAIN_COLLECTION_LEARNER_TEMPLATE void CHAIN_COLLECTION_LEARNER_TEMPLATE1::initializeOutputModel() { outputModel.SetInputAlphabet(inputAlphabet); outputModel.SetOutputAlphabet(outputAlphabet); outputModel.SetWeightAlphabet(weightAlphabet); shared_ptr<vector<State> > states = getStates(&outputModel); outputModel.SetStates(states); } CHAIN_COLLECTION_LEARNER_TEMPLATE void CHAIN_COLLECTION_LEARNER_TEMPLATE1::initializeTester( const string& testSetFile) { tester = Tester(chainTransformer, possibleStateFinder , &outputModel); tester.Initialize(testSetFile); } CHAIN_COLLECTION_LEARNER_TEMPLATE void CHAIN_COLLECTION_LEARNER_TEMPLATE1::printResultsOfInitialization() { wcout << "\nChainCollectionLearner: constructor finished..." << std::endl; wcout << "Number of hidden states: " << outputAlphabet->Size() << std::endl; wcout << "Number of features: " << inputAlphabet->Size() << std::endl; wcout << "Number of cliques: " << weightAlphabet->Size() << std::endl; wcout << "Dimension of the model: " << dimension << std::endl; wcout << "Input something... " << std::endl; wstring s; wcin >> s; } CHAIN_COLLECTION_LEARNER_TEMPLATE CHAIN_COLLECTION_LEARNER_TEMPLATE1::~ChainCollectionLearner(void) { } CHAIN_COLLECTION_LEARNER_TEMPLATE void CHAIN_COLLECTION_LEARNER_TEMPLATE1::PrintForChecking(const string& file) { wofstream out(file); Tools::SetLocale(out); for (size_t chainIndex = 0; chainIndex < chains.size(); ++chainIndex) { chains[chainIndex].PrintForChecking(out); out << std::endl; } out.close(); } CHAIN_COLLECTION_LEARNER_TEMPLATE void CHAIN_COLLECTION_LEARNER_TEMPLATE1::PrintOneSentenceForChecking( const string& file, int sentenceIndex) { wofstream out(file); Tools::SetLocale(out); chains[sentenceIndex].PrintForChecking(out); out.close(); } CHAIN_COLLECTION_LEARNER_TEMPLATE double CHAIN_COLLECTION_LEARNER_TEMPLATE1::CalculateValue(const vector<double>& point) { if (!areValueAndGradientCalculated) { calculateGradientAndValue(point); areValueAndGradientCalculated = true; } else { areValueAndGradientCalculated = false; } return value; } CHAIN_COLLECTION_LEARNER_TEMPLATE void CHAIN_COLLECTION_LEARNER_TEMPLATE1::CalculateGradient( const vector<double>& point, vector<double>* gradientToCalculate) { if (!areValueAndGradientCalculated) { calculateGradientAndValue(point); areValueAndGradientCalculated = true; } else { areValueAndGradientCalculated = false; } *gradientToCalculate = gradient; } CHAIN_COLLECTION_LEARNER_TEMPLATE shared_ptr<VectorFactorsExtractor> CHAIN_COLLECTION_LEARNER_TEMPLATE1::GetVectorFactorsExtractor() { return vectorFactorsExtractor; } CHAIN_COLLECTION_LEARNER_TEMPLATE void CHAIN_COLLECTION_LEARNER_TEMPLATE1::calculateGradientAndValue( const vector<double>& point) { value = 0; gradient.resize(point.size()); for (size_t gradIndex = 0; gradIndex < gradient.size(); ++gradIndex) { gradient[gradIndex] = 0; } // Create threads vector<double> threadSplittedValues(omp_get_num_procs(), 0); vector<vector<double>> threadSplittedGradient(omp_get_num_procs()); for (int it = 0; it < omp_get_num_procs(); ++it) { threadSplittedGradient[it].resize(gradient.size()); } // Calculate value #pragma omp parallel for for (int it = 0; it < int(chains.size()); ++it) { threadSplittedValues[omp_get_thread_num()] += chains[it].CalculateValueAndGradient( point, &threadSplittedGradient[omp_get_thread_num()]); } // Merge into one value for (size_t threadIndex = 0; threadIndex < threadSplittedValues.size() ; ++threadIndex) { value += threadSplittedValues[threadIndex]; for (size_t gradIndex = 0; gradIndex < gradient.size(); ++gradIndex) { gradient[gradIndex] += threadSplittedGradient[threadIndex][gradIndex]; } } // Calculate normFactor regularizator->UpdateValue(point, chains.size(), &value); regularizator->UpdateGradient(point, chains.size(), &gradient); // std::wcout << L"Value: " << value << std::endl; } CHAIN_COLLECTION_LEARNER_TEMPLATE CRF CHAIN_COLLECTION_LEARNER_TEMPLATE1::Learn( int numberOfIterations, int _periodOfTesting , int _periodOfPriniting) { periodOfTesting = _periodOfTesting; periodOfPrinting = _periodOfPriniting; clock_t startTime = clock(); std::wcout << L"Starting learning, number of iterations = " << numberOfIterations << std::endl; int dimension = vectorFactorsExtractor->GetDimension(); vector<double> initialPoint(dimension, 0); vector<double> parameters(dimension); Optimizer optimizer; optimizer.Optimize(*this, this, initialPoint, &parameters, numberOfIterations); clock_t endTime = clock(); fillOutputModel(parameters); std::wcout << L"Have learned for " << (double)(endTime - startTime) / CLOCKS_PER_SEC << L" seconds" << endl; return outputModel; } CHAIN_COLLECTION_LEARNER_TEMPLATE shared_ptr<vector<State> > CHAIN_COLLECTION_LEARNER_TEMPLATE1::getStates(CRF* crf) { shared_ptr<vector<State> > states(new vector<State>); for (int stateIndex = 0; stateIndex < outputAlphabet->Size(); ++stateIndex) { // Getting state name const wstring& stateName = outputAlphabet->LookUpObject(stateIndex); // Getting destinations const unordered_map<int, int>& destinationToClique = (*transitionConverter)[stateIndex]; shared_ptr<vector<int> > destinations(new vector<int>()); destinations->reserve(destinationToClique.size()); shared_ptr<vector<vector<int> > > weightIndexes(new vector<vector<int> >); weightIndexes->reserve(destinationToClique.size()); shared_ptr<vector<wstring> > destinationNames(new vector<wstring>); destinationNames->reserve(destinationToClique.size()); for (auto iterator = destinationToClique.begin(); iterator != destinationToClique.end(); ++iterator) { destinations->push_back(iterator->first); weightIndexes->push_back(vector<int>(1, iterator->second)); destinationNames->push_back(outputAlphabet->LookUpObject(iterator->first)); } states->emplace_back(State( stateName, stateIndex, destinations, weightIndexes, destinationNames, crf)); } return states; } CHAIN_COLLECTION_LEARNER_TEMPLATE shared_ptr<vector<unordered_map<int, double> > > CHAIN_COLLECTION_LEARNER_TEMPLATE1::getCliquesData( const vector<double>& factorsVector) { vector<unordered_map<int, double> > cliquesData; for (int cliqueIndex = 0; cliqueIndex < weightAlphabet->Size(); ++cliqueIndex) { cliquesData.emplace_back( vectorFactorsExtractor->GetCliqueWeights(cliqueIndex, factorsVector)); } return std::make_shared<vector<unordered_map<int, double> > >( std::move(cliquesData)); } CHAIN_COLLECTION_LEARNER_TEMPLATE void CHAIN_COLLECTION_LEARNER_TEMPLATE1::fillOutputModel( const vector<double>& factorsVector) { outputModel.SetInitialWeights(vectorFactorsExtractor->GetInitialWeights(factorsVector)); outputModel.SetDefaultWeights(vectorFactorsExtractor->GetDefaultWeights(factorsVector)); outputModel.SetFinalWeights(vectorFactorsExtractor->GetFinalWeights(factorsVector)); shared_ptr<vector<unordered_map<int, double>> > cliqueWeights = getCliquesData(factorsVector); outputModel.SetWeights(cliqueWeights); } CHAIN_COLLECTION_LEARNER_TEMPLATE bool CHAIN_COLLECTION_LEARNER_TEMPLATE1::Call(int currentIteration , const double* _parameters, int dimension) { bool shouldPrint = (currentIteration > 0) && (currentIteration % periodOfPrinting == 0); bool shouldTest = (currentIteration > 0) && (currentIteration % periodOfTesting == 0); if (shouldPrint || shouldTest) { std::wcout << L"Printing model" << std::endl; vector<double> parameters(dimension); for (int index = 0; index < dimension; ++index) { parameters[index] = _parameters[index]; } fillOutputModel(parameters); CRFBinaryWriter writer(outputFile); writer.Write(outputModel); } if (shouldTest) { CRFBinaryReader reader(outputFile); reader.Read(outputModel); TestedResultsData resultData = tester.TestToFile("REAL_TEST_SET.txt"); resultData.Print(); } return false; } CHAIN_COLLECTION_LEARNER_TEMPLATE bool CHAIN_COLLECTION_LEARNER_TEMPLATE1::checkChain( const Chain& chain) { const vector<wstring>& labels = chain.GetLabels(); const vector<vector<wstring> >& possibleStates = chain.GetPossibleStates(); for (size_t nodeIndex = 0; nodeIndex < labels.size(); ++nodeIndex) { bool found = false; for (size_t labelIndex = 0; labelIndex < possibleStates[nodeIndex].size() ; ++labelIndex) { if (possibleStates[nodeIndex][labelIndex] == labels[nodeIndex]) { found = true; break; } } if (!found) { return false; } } return true; } CHAIN_COLLECTION_LEARNER_TEMPLATE void CHAIN_COLLECTION_LEARNER_TEMPLATE1::fillTransitionConverter( const CRF& i_crf) { const vector<State>& states = i_crf.GetStates(); for (size_t sIndex = 0; sIndex < states.size(); ++sIndex) { // Add state int stateIndex = states[sIndex].GetIndex(); auto stateIterator = transitionConverter->find(stateIndex); if (stateIterator == transitionConverter->end()) { (*transitionConverter)[stateIndex] = unordered_map<int, int>(); stateIterator = transitionConverter->find(stateIndex); } // Add transitions const vector<int>& transitionIndexes = states[sIndex].GetDestinations(); const vector<vector<int> >& cliqueIndexes = states[sIndex].GetWeightsIndexes(); for (size_t tIndex = 0; tIndex < transitionIndexes.size(); ++tIndex) { stateIterator->second[transitionIndexes[tIndex]] = cliqueIndexes[tIndex][0]; } } } }; #endif // CHAIN_COLLECTION_LEARNER
declare8.c
/* Example of multiple declare simd directives for a function Multiple SIMD versions of the function are generated. The invocation of a specific version of the function is determined by where it is called. */ #pragma omp declare simd linear(pixel) uniform(mask) inbranch #pragma omp declare simd linear(pixel) notinbranch #pragma omp declare simd extern void compute_pixel(char *pixel, char mask);
GB_unop__bnot_int32_int32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__bnot_int32_int32) // op(A') function: GB (_unop_tran__bnot_int32_int32) // C type: int32_t // A type: int32_t // cast: int32_t cij = aij // unaryop: cij = ~(aij) #define GB_ATYPE \ int32_t #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = ~(x) ; // casting #define GB_CAST(z, aij) \ int32_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int32_t z = aij ; \ Cx [pC] = ~(z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BNOT || GxB_NO_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__bnot_int32_int32) ( int32_t *Cx, // Cx and Ax may be aliased const int32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int32_t aij = Ax [p] ; int32_t z = aij ; Cx [p] = ~(z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; int32_t aij = Ax [p] ; int32_t z = aij ; Cx [p] = ~(z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__bnot_int32_int32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
sse.h
/* SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Copyright: * 2017-2020 Evan Nemerson <evan@nemerson.com> * 2015-2017 John W. Ratcliff <jratcliffscarab@gmail.com> * 2015 Brandon Rowlett <browlett@nvidia.com> * 2015 Ken Fast <kfast@gdeb.com> */ #if !defined(SIMDE_X86_SSE_H) #define SIMDE_X86_SSE_H #include "mmx.h" #if defined(_WIN32) #include <windows.h> #endif HEDLEY_DIAGNOSTIC_PUSH SIMDE_DISABLE_UNWANTED_DIAGNOSTICS SIMDE_BEGIN_DECLS_ typedef union { #if defined(SIMDE_VECTOR_SUBSCRIPT) SIMDE_ALIGN_TO_16 int8_t i8 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 int16_t i16 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 int32_t i32 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 int64_t i64 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 uint8_t u8 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 uint16_t u16 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 uint32_t u32 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 uint64_t u64 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; #if defined(SIMDE_HAVE_INT128_) SIMDE_ALIGN_TO_16 simde_int128 i128 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 simde_uint128 u128 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; #endif SIMDE_ALIGN_TO_16 simde_float32 f32 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 int_fast32_t i32f SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 uint_fast32_t u32f SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; #else SIMDE_ALIGN_TO_16 int8_t i8[16]; SIMDE_ALIGN_TO_16 int16_t i16[8]; SIMDE_ALIGN_TO_16 int32_t i32[4]; SIMDE_ALIGN_TO_16 int64_t i64[2]; SIMDE_ALIGN_TO_16 uint8_t u8[16]; SIMDE_ALIGN_TO_16 uint16_t u16[8]; SIMDE_ALIGN_TO_16 uint32_t u32[4]; SIMDE_ALIGN_TO_16 uint64_t u64[2]; #if defined(SIMDE_HAVE_INT128_) SIMDE_ALIGN_TO_16 simde_int128 i128[1]; SIMDE_ALIGN_TO_16 simde_uint128 u128[1]; #endif SIMDE_ALIGN_TO_16 simde_float32 f32[4]; SIMDE_ALIGN_TO_16 int_fast32_t i32f[16 / sizeof(int_fast32_t)]; SIMDE_ALIGN_TO_16 uint_fast32_t u32f[16 / sizeof(uint_fast32_t)]; #endif SIMDE_ALIGN_TO_16 simde__m64_private m64_private[2]; SIMDE_ALIGN_TO_16 simde__m64 m64[2]; #if defined(SIMDE_X86_SSE_NATIVE) SIMDE_ALIGN_TO_16 __m128 n; #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) SIMDE_ALIGN_TO_16 int8x16_t neon_i8; SIMDE_ALIGN_TO_16 int16x8_t neon_i16; SIMDE_ALIGN_TO_16 int32x4_t neon_i32; SIMDE_ALIGN_TO_16 int64x2_t neon_i64; SIMDE_ALIGN_TO_16 uint8x16_t neon_u8; SIMDE_ALIGN_TO_16 uint16x8_t neon_u16; SIMDE_ALIGN_TO_16 uint32x4_t neon_u32; SIMDE_ALIGN_TO_16 uint64x2_t neon_u64; SIMDE_ALIGN_TO_16 float32x4_t neon_f32; #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) SIMDE_ALIGN_TO_16 float64x2_t neon_f64; #endif #elif defined(SIMDE_WASM_SIMD128_NATIVE) SIMDE_ALIGN_TO_16 v128_t wasm_v128; #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(unsigned char) altivec_u8; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(unsigned short) altivec_u16; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(unsigned int) altivec_u32; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(signed char) altivec_i8; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(signed short) altivec_i16; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(signed int) altivec_i32; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(float) altivec_f32; #if defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(unsigned long long) altivec_u64; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(signed long long) altivec_i64; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(double) altivec_f64; #endif #endif } simde__m128_private; #if defined(SIMDE_X86_SSE_NATIVE) typedef __m128 simde__m128; #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) typedef float32x4_t simde__m128; #elif defined(SIMDE_WASM_SIMD128_NATIVE) typedef v128_t simde__m128; #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) typedef SIMDE_POWER_ALTIVEC_VECTOR(float) simde__m128; #elif defined(SIMDE_VECTOR_SUBSCRIPT) typedef simde_float32 simde__m128 SIMDE_ALIGN_TO_16 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; #else typedef simde__m128_private simde__m128; #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) typedef simde__m128 __m128; #endif HEDLEY_STATIC_ASSERT(16 == sizeof(simde__m128), "simde__m128 size incorrect"); HEDLEY_STATIC_ASSERT(16 == sizeof(simde__m128_private), "simde__m128_private size incorrect"); #if defined(SIMDE_CHECK_ALIGNMENT) && defined(SIMDE_ALIGN_OF) HEDLEY_STATIC_ASSERT(SIMDE_ALIGN_OF(simde__m128) == 16, "simde__m128 is not 16-byte aligned"); HEDLEY_STATIC_ASSERT(SIMDE_ALIGN_OF(simde__m128_private) == 16, "simde__m128_private is not 16-byte aligned"); #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde__m128_from_private(simde__m128_private v) { simde__m128 r; simde_memcpy(&r, &v, sizeof(r)); return r; } SIMDE_FUNCTION_ATTRIBUTES simde__m128_private simde__m128_to_private(simde__m128 v) { simde__m128_private r; simde_memcpy(&r, &v, sizeof(r)); return r; } #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, int8x16_t, neon, i8) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, int16x8_t, neon, i16) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, int32x4_t, neon, i32) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, int64x2_t, neon, i64) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, uint8x16_t, neon, u8) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, uint16x8_t, neon, u16) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, uint32x4_t, neon, u32) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, uint64x2_t, neon, u64) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, float32x4_t, neon, f32) #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, float64x2_t, neon, f64) #endif #endif /* defined(SIMDE_ARM_NEON_A32V7_NATIVE) */ #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(signed char), altivec, i8) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(signed short), altivec, i16) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(signed int), altivec, i32) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(unsigned char), altivec, u8) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(unsigned short), altivec, u16) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(unsigned int), altivec, u32) #if defined(SIMDE_BUG_GCC_95782) SIMDE_FUNCTION_ATTRIBUTES SIMDE_POWER_ALTIVEC_VECTOR(float) simde__m128_to_altivec_f32(simde__m128 value) { simde__m128_private r_ = simde__m128_to_private(value); return r_.altivec_f32; } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde__m128_from_altivec_f32(SIMDE_POWER_ALTIVEC_VECTOR(float) value) { simde__m128_private r_; r_.altivec_f32 = value; return simde__m128_from_private(r_); } #else SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(float), altivec, f32) #endif #if defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(signed long long), altivec, i64) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(unsigned long long), altivec, u64) #endif #elif defined(SIMDE_WASM_SIMD128_NATIVE) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, v128_t, wasm, v128); #endif /* defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) */ enum { #if defined(SIMDE_X86_SSE_NATIVE) SIMDE_MM_ROUND_NEAREST = _MM_ROUND_NEAREST, SIMDE_MM_ROUND_DOWN = _MM_ROUND_DOWN, SIMDE_MM_ROUND_UP = _MM_ROUND_UP, SIMDE_MM_ROUND_TOWARD_ZERO = _MM_ROUND_TOWARD_ZERO #else SIMDE_MM_ROUND_NEAREST = 0x0000, SIMDE_MM_ROUND_DOWN = 0x2000, SIMDE_MM_ROUND_UP = 0x4000, SIMDE_MM_ROUND_TOWARD_ZERO = 0x6000 #endif }; #if defined(_MM_FROUND_TO_NEAREST_INT) # define SIMDE_MM_FROUND_TO_NEAREST_INT _MM_FROUND_TO_NEAREST_INT # define SIMDE_MM_FROUND_TO_NEG_INF _MM_FROUND_TO_NEG_INF # define SIMDE_MM_FROUND_TO_POS_INF _MM_FROUND_TO_POS_INF # define SIMDE_MM_FROUND_TO_ZERO _MM_FROUND_TO_ZERO # define SIMDE_MM_FROUND_CUR_DIRECTION _MM_FROUND_CUR_DIRECTION # define SIMDE_MM_FROUND_RAISE_EXC _MM_FROUND_RAISE_EXC # define SIMDE_MM_FROUND_NO_EXC _MM_FROUND_NO_EXC #else # define SIMDE_MM_FROUND_TO_NEAREST_INT 0x00 # define SIMDE_MM_FROUND_TO_NEG_INF 0x01 # define SIMDE_MM_FROUND_TO_POS_INF 0x02 # define SIMDE_MM_FROUND_TO_ZERO 0x03 # define SIMDE_MM_FROUND_CUR_DIRECTION 0x04 # define SIMDE_MM_FROUND_RAISE_EXC 0x00 # define SIMDE_MM_FROUND_NO_EXC 0x08 #endif #define SIMDE_MM_FROUND_NINT \ (SIMDE_MM_FROUND_TO_NEAREST_INT | SIMDE_MM_FROUND_RAISE_EXC) #define SIMDE_MM_FROUND_FLOOR \ (SIMDE_MM_FROUND_TO_NEG_INF | SIMDE_MM_FROUND_RAISE_EXC) #define SIMDE_MM_FROUND_CEIL \ (SIMDE_MM_FROUND_TO_POS_INF | SIMDE_MM_FROUND_RAISE_EXC) #define SIMDE_MM_FROUND_TRUNC \ (SIMDE_MM_FROUND_TO_ZERO | SIMDE_MM_FROUND_RAISE_EXC) #define SIMDE_MM_FROUND_RINT \ (SIMDE_MM_FROUND_CUR_DIRECTION | SIMDE_MM_FROUND_RAISE_EXC) #define SIMDE_MM_FROUND_NEARBYINT \ (SIMDE_MM_FROUND_CUR_DIRECTION | SIMDE_MM_FROUND_NO_EXC) #if defined(SIMDE_X86_SSE4_1_ENABLE_NATIVE_ALIASES) && !defined(_MM_FROUND_TO_NEAREST_INT) # define _MM_FROUND_TO_NEAREST_INT SIMDE_MM_FROUND_TO_NEAREST_INT # define _MM_FROUND_TO_NEG_INF SIMDE_MM_FROUND_TO_NEG_INF # define _MM_FROUND_TO_POS_INF SIMDE_MM_FROUND_TO_POS_INF # define _MM_FROUND_TO_ZERO SIMDE_MM_FROUND_TO_ZERO # define _MM_FROUND_CUR_DIRECTION SIMDE_MM_FROUND_CUR_DIRECTION # define _MM_FROUND_RAISE_EXC SIMDE_MM_FROUND_RAISE_EXC # define _MM_FROUND_NINT SIMDE_MM_FROUND_NINT # define _MM_FROUND_FLOOR SIMDE_MM_FROUND_FLOOR # define _MM_FROUND_CEIL SIMDE_MM_FROUND_CEIL # define _MM_FROUND_TRUNC SIMDE_MM_FROUND_TRUNC # define _MM_FROUND_RINT SIMDE_MM_FROUND_RINT # define _MM_FROUND_NEARBYINT SIMDE_MM_FROUND_NEARBYINT #endif #if defined(_MM_EXCEPT_INVALID) # define SIMDE_MM_EXCEPT_INVALID _MM_EXCEPT_INVALID #else # define SIMDE_MM_EXCEPT_INVALID (0x0001) #endif #if defined(_MM_EXCEPT_DENORM) # define SIMDE_MM_EXCEPT_DENORM _MM_EXCEPT_DENORM #else # define SIMDE_MM_EXCEPT_DENORM (0x0002) #endif #if defined(_MM_EXCEPT_DIV_ZERO) # define SIMDE_MM_EXCEPT_DIV_ZERO _MM_EXCEPT_DIV_ZERO #else # define SIMDE_MM_EXCEPT_DIV_ZERO (0x0004) #endif #if defined(_MM_EXCEPT_OVERFLOW) # define SIMDE_MM_EXCEPT_OVERFLOW _MM_EXCEPT_OVERFLOW #else # define SIMDE_MM_EXCEPT_OVERFLOW (0x0008) #endif #if defined(_MM_EXCEPT_UNDERFLOW) # define SIMDE_MM_EXCEPT_UNDERFLOW _MM_EXCEPT_UNDERFLOW #else # define SIMDE_MM_EXCEPT_UNDERFLOW (0x0010) #endif #if defined(_MM_EXCEPT_INEXACT) # define SIMDE_MM_EXCEPT_INEXACT _MM_EXCEPT_INEXACT #else # define SIMDE_MM_EXCEPT_INEXACT (0x0020) #endif #if defined(_MM_EXCEPT_MASK) # define SIMDE_MM_EXCEPT_MASK _MM_EXCEPT_MASK #else # define SIMDE_MM_EXCEPT_MASK \ (SIMDE_MM_EXCEPT_INVALID | SIMDE_MM_EXCEPT_DENORM | \ SIMDE_MM_EXCEPT_DIV_ZERO | SIMDE_MM_EXCEPT_OVERFLOW | \ SIMDE_MM_EXCEPT_UNDERFLOW | SIMDE_MM_EXCEPT_INEXACT) #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _MM_EXCEPT_INVALID SIMDE_MM_EXCEPT_INVALID #define _MM_EXCEPT_DENORM SIMDE_MM_EXCEPT_DENORM #define _MM_EXCEPT_DIV_ZERO SIMDE_MM_EXCEPT_DIV_ZERO #define _MM_EXCEPT_OVERFLOW SIMDE_MM_EXCEPT_OVERFLOW #define _MM_EXCEPT_UNDERFLOW SIMDE_MM_EXCEPT_UNDERFLOW #define _MM_EXCEPT_INEXACT SIMDE_MM_EXCEPT_INEXACT #define _MM_EXCEPT_MASK SIMDE_MM_EXCEPT_MASK #endif #if defined(_MM_MASK_INVALID) # define SIMDE_MM_MASK_INVALID _MM_MASK_INVALID #else # define SIMDE_MM_MASK_INVALID (0x0080) #endif #if defined(_MM_MASK_DENORM) # define SIMDE_MM_MASK_DENORM _MM_MASK_DENORM #else # define SIMDE_MM_MASK_DENORM (0x0100) #endif #if defined(_MM_MASK_DIV_ZERO) # define SIMDE_MM_MASK_DIV_ZERO _MM_MASK_DIV_ZERO #else # define SIMDE_MM_MASK_DIV_ZERO (0x0200) #endif #if defined(_MM_MASK_OVERFLOW) # define SIMDE_MM_MASK_OVERFLOW _MM_MASK_OVERFLOW #else # define SIMDE_MM_MASK_OVERFLOW (0x0400) #endif #if defined(_MM_MASK_UNDERFLOW) # define SIMDE_MM_MASK_UNDERFLOW _MM_MASK_UNDERFLOW #else # define SIMDE_MM_MASK_UNDERFLOW (0x0800) #endif #if defined(_MM_MASK_INEXACT) # define SIMDE_MM_MASK_INEXACT _MM_MASK_INEXACT #else # define SIMDE_MM_MASK_INEXACT (0x1000) #endif #if defined(_MM_MASK_MASK) # define SIMDE_MM_MASK_MASK _MM_MASK_MASK #else # define SIMDE_MM_MASK_MASK \ (SIMDE_MM_MASK_INVALID | SIMDE_MM_MASK_DENORM | \ SIMDE_MM_MASK_DIV_ZERO | SIMDE_MM_MASK_OVERFLOW | \ SIMDE_MM_MASK_UNDERFLOW | SIMDE_MM_MASK_INEXACT) #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _MM_MASK_INVALID SIMDE_MM_MASK_INVALID #define _MM_MASK_DENORM SIMDE_MM_MASK_DENORM #define _MM_MASK_DIV_ZERO SIMDE_MM_MASK_DIV_ZERO #define _MM_MASK_OVERFLOW SIMDE_MM_MASK_OVERFLOW #define _MM_MASK_UNDERFLOW SIMDE_MM_MASK_UNDERFLOW #define _MM_MASK_INEXACT SIMDE_MM_MASK_INEXACT #define _MM_MASK_MASK SIMDE_MM_MASK_MASK #endif #if defined(_MM_FLUSH_ZERO_MASK) # define SIMDE_MM_FLUSH_ZERO_MASK _MM_FLUSH_ZERO_MASK #else # define SIMDE_MM_FLUSH_ZERO_MASK (0x8000) #endif #if defined(_MM_FLUSH_ZERO_ON) # define SIMDE_MM_FLUSH_ZERO_ON _MM_FLUSH_ZERO_ON #else # define SIMDE_MM_FLUSH_ZERO_ON (0x8000) #endif #if defined(_MM_FLUSH_ZERO_OFF) # define SIMDE_MM_FLUSH_ZERO_OFF _MM_FLUSH_ZERO_OFF #else # define SIMDE_MM_FLUSH_ZERO_OFF (0x0000) #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _MM_FLUSH_ZERO_MASK SIMDE_MM_FLUSH_ZERO_MASK #define _MM_FLUSH_ZERO_ON SIMDE_MM_FLUSH_ZERO_ON #define _MM_FLUSH_ZERO_OFF SIMDE_MM_FLUSH_ZERO_OFF #endif SIMDE_FUNCTION_ATTRIBUTES unsigned int SIMDE_MM_GET_ROUNDING_MODE(void) { #if defined(SIMDE_X86_SSE_NATIVE) return _MM_GET_ROUNDING_MODE(); #elif defined(SIMDE_HAVE_FENV_H) unsigned int vfe_mode; switch (fegetround()) { #if defined(FE_TONEAREST) case FE_TONEAREST: vfe_mode = SIMDE_MM_ROUND_NEAREST; break; #endif #if defined(FE_TOWARDZERO) case FE_TOWARDZERO: vfe_mode = SIMDE_MM_ROUND_DOWN; break; #endif #if defined(FE_UPWARD) case FE_UPWARD: vfe_mode = SIMDE_MM_ROUND_UP; break; #endif #if defined(FE_DOWNWARD) case FE_DOWNWARD: vfe_mode = SIMDE_MM_ROUND_TOWARD_ZERO; break; #endif default: vfe_mode = SIMDE_MM_ROUND_NEAREST; break; } return vfe_mode; #else return SIMDE_MM_ROUND_NEAREST; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _MM_GET_ROUNDING_MODE() SIMDE_MM_GET_ROUNDING_MODE() #endif SIMDE_FUNCTION_ATTRIBUTES void SIMDE_MM_SET_ROUNDING_MODE(unsigned int a) { #if defined(SIMDE_X86_SSE_NATIVE) _MM_SET_ROUNDING_MODE(a); #elif defined(SIMDE_HAVE_FENV_H) int fe_mode = FE_TONEAREST; switch (a) { #if defined(FE_TONEAREST) case SIMDE_MM_ROUND_NEAREST: fe_mode = FE_TONEAREST; break; #endif #if defined(FE_TOWARDZERO) case SIMDE_MM_ROUND_TOWARD_ZERO: fe_mode = FE_TOWARDZERO; break; #endif #if defined(FE_DOWNWARD) case SIMDE_MM_ROUND_DOWN: fe_mode = FE_DOWNWARD; break; #endif #if defined(FE_UPWARD) case SIMDE_MM_ROUND_UP: fe_mode = FE_UPWARD; break; #endif default: return; } fesetround(fe_mode); #else (void) a; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _MM_SET_ROUNDING_MODE(a) SIMDE_MM_SET_ROUNDING_MODE(a) #endif SIMDE_FUNCTION_ATTRIBUTES uint32_t SIMDE_MM_GET_FLUSH_ZERO_MODE (void) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_getcsr() & _MM_FLUSH_ZERO_MASK; #else return SIMDE_MM_FLUSH_ZERO_OFF; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _MM_SET_FLUSH_ZERO_MODE(a) SIMDE_MM_SET_FLUSH_ZERO_MODE(a) #endif SIMDE_FUNCTION_ATTRIBUTES void SIMDE_MM_SET_FLUSH_ZERO_MODE (uint32_t a) { #if defined(SIMDE_X86_SSE_NATIVE) _MM_SET_FLUSH_ZERO_MODE(a); #else (void) a; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _MM_SET_FLUSH_ZERO_MODE(a) SIMDE_MM_SET_FLUSH_ZERO_MODE(a) #endif SIMDE_FUNCTION_ATTRIBUTES uint32_t simde_mm_getcsr (void) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_getcsr(); #else return SIMDE_MM_GET_ROUNDING_MODE(); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _mm_getcsr() simde_mm_getcsr() #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_setcsr (uint32_t a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_setcsr(a); #else SIMDE_MM_SET_ROUNDING_MODE(HEDLEY_STATIC_CAST(unsigned int, a)); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _mm_setcsr(a) simde_mm_setcsr(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_round_ps (simde__m128 a, int rounding, int lax_rounding) SIMDE_REQUIRE_CONSTANT_RANGE(rounding, 0, 15) SIMDE_REQUIRE_CONSTANT_RANGE(lax_rounding, 0, 1) { simde__m128_private r_, a_ = simde__m128_to_private(a); (void) lax_rounding; /* For architectures which lack a current direction SIMD instruction. * * Note that NEON actually has a current rounding mode instruction, * but in ARMv8+ the rounding mode is ignored and nearest is always * used, so we treat ARMv7 as having a rounding mode but ARMv8 as * not. */ #if \ defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || \ defined(SIMDE_ARM_NEON_A32V8) if ((rounding & 7) == SIMDE_MM_FROUND_CUR_DIRECTION) rounding = HEDLEY_STATIC_CAST(int, SIMDE_MM_GET_ROUNDING_MODE()) << 13; #endif switch (rounding & ~SIMDE_MM_FROUND_NO_EXC) { case SIMDE_MM_FROUND_CUR_DIRECTION: #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_round(a_.altivec_f32)); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) && !defined(SIMDE_BUG_GCC_95399) r_.neon_f32 = vrndiq_f32(a_.neon_f32); #elif defined(simde_math_nearbyintf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_nearbyintf(a_.f32[i]); } #else HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); #endif break; case SIMDE_MM_FROUND_TO_NEAREST_INT: #if defined(SIMDE_POWER_ALTIVEC_P8_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_rint(a_.altivec_f32)); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) r_.neon_f32 = vrndnq_f32(a_.neon_f32); #elif defined(simde_math_roundevenf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_roundevenf(a_.f32[i]); } #else HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); #endif break; case SIMDE_MM_FROUND_TO_NEG_INF: #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_floor(a_.altivec_f32)); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) r_.neon_f32 = vrndmq_f32(a_.neon_f32); #elif defined(simde_math_floorf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_floorf(a_.f32[i]); } #else HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); #endif break; case SIMDE_MM_FROUND_TO_POS_INF: #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_ceil(a_.altivec_f32)); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) r_.neon_f32 = vrndpq_f32(a_.neon_f32); #elif defined(simde_math_ceilf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_ceilf(a_.f32[i]); } #else HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); #endif break; case SIMDE_MM_FROUND_TO_ZERO: #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_trunc(a_.altivec_f32)); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) r_.neon_f32 = vrndq_f32(a_.neon_f32); #elif defined(simde_math_truncf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_truncf(a_.f32[i]); } #else HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); #endif break; default: HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); } return simde__m128_from_private(r_); } #if defined(SIMDE_X86_SSE4_1_NATIVE) #define simde_mm_round_ps(a, rounding) _mm_round_ps((a), (rounding)) #else #define simde_mm_round_ps(a, rounding) simde_x_mm_round_ps((a), (rounding), 0) #endif #if defined(SIMDE_X86_SSE4_1_ENABLE_NATIVE_ALIASES) #define _mm_round_ps(a, rounding) simde_mm_round_ps((a), (rounding)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_set_ps (simde_float32 e3, simde_float32 e2, simde_float32 e1, simde_float32 e0) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_set_ps(e3, e2, e1, e0); #else simde__m128_private r_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) SIMDE_ALIGN_TO_16 simde_float32 data[4] = { e0, e1, e2, e3 }; r_.neon_f32 = vld1q_f32(data); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_make(e0, e1, e2, e3); #else r_.f32[0] = e0; r_.f32[1] = e1; r_.f32[2] = e2; r_.f32[3] = e3; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_set_ps(e3, e2, e1, e0) simde_mm_set_ps(e3, e2, e1, e0) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_set_ps1 (simde_float32 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_set_ps1(a); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vdupq_n_f32(a); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) (void) a; return vec_splats(a); #else return simde_mm_set_ps(a, a, a, a); #endif } #define simde_mm_set1_ps(a) simde_mm_set_ps1(a) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_set_ps1(a) simde_mm_set_ps1(a) # define _mm_set1_ps(a) simde_mm_set1_ps(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_move_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_move_ss(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(vgetq_lane_f32(b_.neon_f32, 0), a_.neon_f32, 0); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) SIMDE_POWER_ALTIVEC_VECTOR(unsigned char) m = { 16, 17, 18, 19, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; r_.altivec_f32 = vec_perm(a_.altivec_f32, b_.altivec_f32, m); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v8x16_shuffle(b_.wasm_v128, a_.wasm_v128, 0, 1, 2, 3, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, b_.f32, 4, 1, 2, 3); #else r_.f32[0] = b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_move_ss(a, b) simde_mm_move_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_add_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_add_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vaddq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_add(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_add(a_.altivec_f32, b_.altivec_f32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.f32 = a_.f32 + b_.f32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = a_.f32[i] + b_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_add_ps(a, b) simde_mm_add_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_add_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_add_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_add_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32_t b0 = vgetq_lane_f32(b_.neon_f32, 0); float32x4_t value = vsetq_lane_f32(b0, vdupq_n_f32(0), 0); // the upper values in the result must be the remnants of <a>. r_.neon_f32 = vaddq_f32(a_.neon_f32, value); #else r_.f32[0] = a_.f32[0] + b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_add_ss(a, b) simde_mm_add_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_and_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_and_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = vandq_s32(a_.neon_i32, b_.neon_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_and(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = a_.i32 & b_.i32; #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_and(a_.altivec_f32, b_.altivec_f32); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { r_.i32[i] = a_.i32[i] & b_.i32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_and_ps(a, b) simde_mm_and_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_andnot_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_andnot_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = vbicq_s32(b_.neon_i32, a_.neon_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_andnot(b_.wasm_v128, a_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_andc(b_.altivec_f32, a_.altivec_f32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = ~a_.i32 & b_.i32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { r_.i32[i] = ~(a_.i32[i]) & b_.i32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_andnot_ps(a, b) simde_mm_andnot_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_xor_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_xor_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = veorq_s32(a_.neon_i32, b_.neon_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_xor(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_i32 = vec_xor(a_.altivec_i32, b_.altivec_i32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32f = a_.i32f ^ b_.i32f; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u32) / sizeof(r_.u32[0])) ; i++) { r_.u32[i] = a_.u32[i] ^ b_.u32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_xor_ps(a, b) simde_mm_xor_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_or_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_or_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = vorrq_s32(a_.neon_i32, b_.neon_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_or(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_i32 = vec_or(a_.altivec_i32, b_.altivec_i32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32f = a_.i32f | b_.i32f; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u32) / sizeof(r_.u32[0])) ; i++) { r_.u32[i] = a_.u32[i] | b_.u32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_or_ps(a, b) simde_mm_or_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_not_ps(simde__m128 a) { #if defined(SIMDE_X86_AVX512VL_NATIVE) __m128i ai = _mm_castps_si128(a); return _mm_castsi128_ps(_mm_ternarylogic_epi32(ai, ai, ai, 0x55)); #elif defined(SIMDE_X86_SSE2_NATIVE) /* Note: we use ints instead of floats because we don't want cmpeq * to return false for (NaN, NaN) */ __m128i ai = _mm_castps_si128(a); return _mm_castsi128_ps(_mm_andnot_si128(ai, _mm_cmpeq_epi32(ai, ai))); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = vmvnq_s32(a_.neon_i32); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_i32 = vec_nor(a_.altivec_i32, a_.altivec_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_not(a_.wasm_v128); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = ~a_.i32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { r_.i32[i] = ~(a_.i32[i]); } #endif return simde__m128_from_private(r_); #endif } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_select_ps(simde__m128 a, simde__m128 b, simde__m128 mask) { /* This function is for when you want to blend two elements together * according to a mask. It is similar to _mm_blendv_ps, except that * it is undefined whether the blend is based on the highest bit in * each lane (like blendv) or just bitwise operations. This allows * us to implement the function efficiently everywhere. * * Basically, you promise that all the lanes in mask are either 0 or * ~0. */ #if defined(SIMDE_X86_SSE4_1_NATIVE) return _mm_blendv_ps(a, b, mask); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b), mask_ = simde__m128_to_private(mask); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = vbslq_s32(mask_.neon_u32, b_.neon_i32, a_.neon_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_bitselect(b_.wasm_v128, a_.wasm_v128, mask_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_i32 = vec_sel(a_.altivec_i32, b_.altivec_i32, mask_.altivec_u32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = a_.i32 ^ ((a_.i32 ^ b_.i32) & mask_.i32); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { r_.i32[i] = a_.i32[i] ^ ((a_.i32[i] ^ b_.i32[i]) & mask_.i32[i]); } #endif return simde__m128_from_private(r_); #endif } SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_avg_pu16 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_avg_pu16(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u16 = vrhadd_u16(b_.neon_u16, a_.neon_u16); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) && defined(SIMDE_VECTOR_SUBSCRIPT_SCALAR) && defined(SIMDE_CONVERT_VECTOR_) uint32_t wa SIMDE_VECTOR(16); uint32_t wb SIMDE_VECTOR(16); uint32_t wr SIMDE_VECTOR(16); SIMDE_CONVERT_VECTOR_(wa, a_.u16); SIMDE_CONVERT_VECTOR_(wb, b_.u16); wr = (wa + wb + 1) >> 1; SIMDE_CONVERT_VECTOR_(r_.u16, wr); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u16) / sizeof(r_.u16[0])) ; i++) { r_.u16[i] = (a_.u16[i] + b_.u16[i] + 1) >> 1; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pavgw(a, b) simde_mm_avg_pu16(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_avg_pu16(a, b) simde_mm_avg_pu16(a, b) # define _m_pavgw(a, b) simde_mm_avg_pu16(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_avg_pu8 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_avg_pu8(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u8 = vrhadd_u8(b_.neon_u8, a_.neon_u8); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) && defined(SIMDE_VECTOR_SUBSCRIPT_SCALAR) && defined(SIMDE_CONVERT_VECTOR_) uint16_t wa SIMDE_VECTOR(16); uint16_t wb SIMDE_VECTOR(16); uint16_t wr SIMDE_VECTOR(16); SIMDE_CONVERT_VECTOR_(wa, a_.u8); SIMDE_CONVERT_VECTOR_(wb, b_.u8); wr = (wa + wb + 1) >> 1; SIMDE_CONVERT_VECTOR_(r_.u8, wr); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u8) / sizeof(r_.u8[0])) ; i++) { r_.u8[i] = (a_.u8[i] + b_.u8[i] + 1) >> 1; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pavgb(a, b) simde_mm_avg_pu8(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_avg_pu8(a, b) simde_mm_avg_pu8(a, b) # define _m_pavgb(a, b) simde_mm_avg_pu8(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_abs_ps(simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) simde_float32 mask_; uint32_t u32_ = UINT32_C(0x7FFFFFFF); simde_memcpy(&mask_, &u32_, sizeof(u32_)); return _mm_and_ps(_mm_set1_ps(mask_), a); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vabsq_f32(a_.neon_f32); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_abs(a_.altivec_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_abs(a_.wasm_v128); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_fabsf(a_.f32[i]); } #endif return simde__m128_from_private(r_); #endif } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpeq_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpeq_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vceqq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_eq(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmpeq(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), a_.f32 == b_.f32); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] == b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpeq_ps(a, b) simde_mm_cmpeq_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpeq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpeq_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpeq_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] == b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpeq_ss(a, b) simde_mm_cmpeq_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpge_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpge_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vcgeq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_ge(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmpge(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), (a_.f32 >= b_.f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] >= b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpge_ps(a, b) simde_mm_cmpge_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpge_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) && !defined(__PGI) return _mm_cmpge_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpge_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] >= b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpge_ss(a, b) simde_mm_cmpge_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpgt_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpgt_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vcgtq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_gt(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmpgt(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), (a_.f32 > b_.f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] > b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpgt_ps(a, b) simde_mm_cmpgt_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpgt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) && !defined(__PGI) return _mm_cmpgt_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpgt_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] > b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpgt_ss(a, b) simde_mm_cmpgt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmple_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmple_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vcleq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_le(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmple(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), (a_.f32 <= b_.f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] <= b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmple_ps(a, b) simde_mm_cmple_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmple_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmple_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmple_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] <= b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmple_ss(a, b) simde_mm_cmple_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmplt_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmplt_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vcltq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_lt(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmplt(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), (a_.f32 < b_.f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] < b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmplt_ps(a, b) simde_mm_cmplt_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmplt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmplt_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmplt_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] < b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmplt_ss(a, b) simde_mm_cmplt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpneq_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpneq_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vmvnq_u32(vceqq_f32(a_.neon_f32, b_.neon_f32)); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_ne(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P9_NATIVE) && SIMDE_ARCH_POWER_CHECK(900) && !defined(HEDLEY_IBM_VERSION) /* vec_cmpne(SIMDE_POWER_ALTIVEC_VECTOR(float), SIMDE_POWER_ALTIVEC_VECTOR(float)) is missing from XL C/C++ v16.1.1, though the documentation (table 89 on page 432 of the IBM XL C/C++ for Linux Compiler Reference, Version 16.1.1) shows that it should be present. Both GCC and clang support it. */ r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmpne(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmpeq(a_.altivec_f32, b_.altivec_f32)); r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_nor(r_.altivec_f32, r_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), (a_.f32 != b_.f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] != b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpneq_ps(a, b) simde_mm_cmpneq_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpneq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpneq_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpneq_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] != b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpneq_ss(a, b) simde_mm_cmpneq_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnge_ps (simde__m128 a, simde__m128 b) { return simde_mm_cmplt_ps(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnge_ps(a, b) simde_mm_cmpnge_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnge_ss (simde__m128 a, simde__m128 b) { return simde_mm_cmplt_ss(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnge_ss(a, b) simde_mm_cmpnge_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpngt_ps (simde__m128 a, simde__m128 b) { return simde_mm_cmple_ps(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpngt_ps(a, b) simde_mm_cmpngt_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpngt_ss (simde__m128 a, simde__m128 b) { return simde_mm_cmple_ss(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpngt_ss(a, b) simde_mm_cmpngt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnle_ps (simde__m128 a, simde__m128 b) { return simde_mm_cmpgt_ps(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnle_ps(a, b) simde_mm_cmpnle_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnle_ss (simde__m128 a, simde__m128 b) { return simde_mm_cmpgt_ss(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnle_ss(a, b) simde_mm_cmpnle_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnlt_ps (simde__m128 a, simde__m128 b) { return simde_mm_cmpge_ps(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnlt_ps(a, b) simde_mm_cmpnlt_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnlt_ss (simde__m128 a, simde__m128 b) { return simde_mm_cmpge_ss(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnlt_ss(a, b) simde_mm_cmpnlt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpord_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpord_ps(a, b); #elif defined(SIMDE_WASM_SIMD128_NATIVE) return wasm_v128_and(wasm_f32x4_eq(a, a), wasm_f32x4_eq(b, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) /* Note: NEON does not have ordered compare builtin Need to compare a eq a and b eq b to check for NaN Do AND of results to get final */ uint32x4_t ceqaa = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t ceqbb = vceqq_f32(b_.neon_f32, b_.neon_f32); r_.neon_u32 = vandq_u32(ceqaa, ceqbb); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_and(wasm_f32x4_eq(a_.wasm_v128, a_.wasm_v128), wasm_f32x4_eq(b_.wasm_v128, b_.wasm_v128)); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_and(vec_cmpeq(a_.altivec_f32, a_.altivec_f32), vec_cmpeq(b_.altivec_f32, b_.altivec_f32))); #elif defined(simde_math_isnanf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (simde_math_isnanf(a_.f32[i]) || simde_math_isnanf(b_.f32[i])) ? UINT32_C(0) : ~UINT32_C(0); } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpord_ps(a, b) simde_mm_cmpord_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpunord_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpunord_ps(a, b); #elif defined(SIMDE_WASM_SIMD128_NATIVE) return wasm_v128_or(wasm_f32x4_ne(a, a), wasm_f32x4_ne(b, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t ceqaa = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t ceqbb = vceqq_f32(b_.neon_f32, b_.neon_f32); r_.neon_u32 = vmvnq_u32(vandq_u32(ceqaa, ceqbb)); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_or(wasm_f32x4_ne(a_.wasm_v128, a_.wasm_v128), wasm_f32x4_ne(b_.wasm_v128, b_.wasm_v128)); #elif defined(SIMDE_POWER_ALTIVEC_P8_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_nand(vec_cmpeq(a_.altivec_f32, a_.altivec_f32), vec_cmpeq(b_.altivec_f32, b_.altivec_f32))); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_and(vec_cmpeq(a_.altivec_f32, a_.altivec_f32), vec_cmpeq(b_.altivec_f32, b_.altivec_f32))); r_.altivec_f32 = vec_nor(r_.altivec_f32, r_.altivec_f32); #elif defined(simde_math_isnanf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (simde_math_isnanf(a_.f32[i]) || simde_math_isnanf(b_.f32[i])) ? ~UINT32_C(0) : UINT32_C(0); } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpunord_ps(a, b) simde_mm_cmpunord_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpunord_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) && !defined(__PGI) return _mm_cmpunord_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpunord_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(simde_math_isnanf) r_.u32[0] = (simde_math_isnanf(a_.f32[0]) || simde_math_isnanf(b_.f32[0])) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.u32) / sizeof(r_.u32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpunord_ss(a, b) simde_mm_cmpunord_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comieq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comieq_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_eq_b = vceqq_f32(a_.neon_f32, b_.neon_f32); return !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_eq_b), 0) != 0); #else return a_.f32[0] == b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comieq_ss(a, b) simde_mm_comieq_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comige_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comige_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_ge_b = vcgeq_f32(a_.neon_f32, b_.neon_f32); return !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_ge_b), 0) != 0); #else return a_.f32[0] >= b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comige_ss(a, b) simde_mm_comige_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comigt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comigt_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_gt_b = vcgtq_f32(a_.neon_f32, b_.neon_f32); return !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_gt_b), 0) != 0); #else return a_.f32[0] > b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comigt_ss(a, b) simde_mm_comigt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comile_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comile_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_le_b = vcleq_f32(a_.neon_f32, b_.neon_f32); return !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_le_b), 0) != 0); #else return a_.f32[0] <= b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comile_ss(a, b) simde_mm_comile_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comilt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comilt_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_lt_b = vcltq_f32(a_.neon_f32, b_.neon_f32); return !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_lt_b), 0) != 0); #else return a_.f32[0] < b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comilt_ss(a, b) simde_mm_comilt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comineq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comineq_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_neq_b = vmvnq_u32(vceqq_f32(a_.neon_f32, b_.neon_f32)); return !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_neq_b), 0) != 0); #else return a_.f32[0] != b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comineq_ss(a, b) simde_mm_comineq_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_copysign_ps(simde__m128 dest, simde__m128 src) { simde__m128_private r_, dest_ = simde__m128_to_private(dest), src_ = simde__m128_to_private(src); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) const uint32x4_t sign_pos = vreinterpretq_u32_f32(vdupq_n_f32(-SIMDE_FLOAT32_C(0.0))); r_.neon_u32 = vbslq_u32(sign_pos, src_.neon_u32, dest_.neon_u32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) const v128_t sign_pos = wasm_f32x4_splat(-0.0f); r_.wasm_v128 = wasm_v128_bitselect(src_.wasm_v128, dest_.wasm_v128, sign_pos); #elif defined(SIMDE_POWER_ALTIVEC_P9_NATIVE) #if !defined(HEDLEY_IBM_VERSION) r_.altivec_f32 = vec_cpsgn(dest_.altivec_f32, src_.altivec_f32); #else r_.altivec_f32 = vec_cpsgn(src_.altivec_f32, dest_.altivec_f32); #endif #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) const SIMDE_POWER_ALTIVEC_VECTOR(unsigned int) sign_pos = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(unsigned int), vec_splats(-0.0f)); r_.altivec_f32 = vec_sel(dest_.altivec_f32, src_.altivec_f32, sign_pos); #elif defined(SIMDE_IEEE754_STORAGE) (void) src_; (void) dest_; simde__m128 sign_pos = simde_mm_set1_ps(-0.0f); r_ = simde__m128_to_private(simde_mm_xor_ps(dest, simde_mm_and_ps(simde_mm_xor_ps(dest, src), sign_pos))); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_copysignf(dest_.f32[i], src_.f32[i]); } #endif return simde__m128_from_private(r_); } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_xorsign_ps(simde__m128 dest, simde__m128 src) { return simde_mm_xor_ps(simde_mm_and_ps(simde_mm_set1_ps(-0.0f), src), dest); } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvt_pi2ps (simde__m128 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvt_pi2ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a); simde__m64_private b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcombine_f32(vcvt_f32_s32(b_.neon_i32), vget_high_f32(a_.neon_f32)); #elif defined(SIMDE_CONVERT_VECTOR_) SIMDE_CONVERT_VECTOR_(r_.m64_private[0].f32, b_.i32); r_.m64_private[1] = a_.m64_private[1]; #else r_.f32[0] = (simde_float32) b_.i32[0]; r_.f32[1] = (simde_float32) b_.i32[1]; r_.i32[2] = a_.i32[2]; r_.i32[3] = a_.i32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvt_pi2ps(a, b) simde_mm_cvt_pi2ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_cvt_ps2pi (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvt_ps2pi(a); #else simde__m64_private r_; simde__m128_private a_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) a_ = simde__m128_to_private(simde_mm_round_ps(a, SIMDE_MM_FROUND_CUR_DIRECTION)); r_.neon_i32 = vcvt_s32_f32(vget_low_f32(a_.neon_f32)); #elif defined(SIMDE_CONVERT_VECTOR_) && SIMDE_NATURAL_VECTOR_SIZE_GE(128) a_ = simde__m128_to_private(simde_mm_round_ps(a, SIMDE_MM_FROUND_CUR_DIRECTION)); SIMDE_CONVERT_VECTOR_(r_.i32, a_.m64_private[0].f32); #else a_ = simde__m128_to_private(a); SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { r_.i32[i] = HEDLEY_STATIC_CAST(int32_t, simde_math_nearbyintf(a_.f32[i])); } #endif return simde__m64_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvt_ps2pi(a) simde_mm_cvt_ps2pi((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvt_si2ss (simde__m128 a, int32_t b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cvt_si2ss(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(HEDLEY_STATIC_CAST(float, b), a_.neon_f32, 0); #else r_.f32[0] = HEDLEY_STATIC_CAST(simde_float32, b); r_.i32[1] = a_.i32[1]; r_.i32[2] = a_.i32[2]; r_.i32[3] = a_.i32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvt_si2ss(a, b) simde_mm_cvt_si2ss((a), b) #endif SIMDE_FUNCTION_ATTRIBUTES int32_t simde_mm_cvt_ss2si (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cvt_ss2si(a); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) && defined(SIMDE_FAST_CONVERSION_RANGE) && !defined(SIMDE_BUG_GCC_95399) return vgetq_lane_s32(vcvtnq_s32_f32(simde__m128_to_neon_f32(a)), 0); #else simde__m128_private a_ = simde__m128_to_private(simde_mm_round_ps(a, SIMDE_MM_FROUND_CUR_DIRECTION)); #if !defined(SIMDE_FAST_CONVERSION_RANGE) return ((a_.f32[0] > HEDLEY_STATIC_CAST(simde_float32, INT32_MIN)) && (a_.f32[0] < HEDLEY_STATIC_CAST(simde_float32, INT32_MAX))) ? SIMDE_CONVERT_FTOI(int32_t, a_.f32[0]) : INT32_MIN; #else return SIMDE_CONVERT_FTOI(int32_t, a_.f32[0]); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvt_ss2si(a) simde_mm_cvt_ss2si((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpi16_ps (simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpi16_ps(a); #else simde__m128_private r_; simde__m64_private a_ = simde__m64_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcvtq_f32_s32(vmovl_s16(a_.neon_i16)); #elif defined(SIMDE_CONVERT_VECTOR_) SIMDE_CONVERT_VECTOR_(r_.f32, a_.i16); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { simde_float32 v = a_.i16[i]; r_.f32[i] = v; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpi16_ps(a) simde_mm_cvtpi16_ps(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpi32_ps (simde__m128 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpi32_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a); simde__m64_private b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcombine_f32(vcvt_f32_s32(b_.neon_i32), vget_high_f32(a_.neon_f32)); #elif defined(SIMDE_CONVERT_VECTOR_) SIMDE_CONVERT_VECTOR_(r_.m64_private[0].f32, b_.i32); r_.m64_private[1] = a_.m64_private[1]; #else r_.f32[0] = (simde_float32) b_.i32[0]; r_.f32[1] = (simde_float32) b_.i32[1]; r_.i32[2] = a_.i32[2]; r_.i32[3] = a_.i32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpi32_ps(a, b) simde_mm_cvtpi32_ps((a), b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpi32x2_ps (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpi32x2_ps(a, b); #else simde__m128_private r_; simde__m64_private a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcvtq_f32_s32(vcombine_s32(a_.neon_i32, b_.neon_i32)); #elif defined(SIMDE_CONVERT_VECTOR_) SIMDE_CONVERT_VECTOR_(r_.m64_private[0].f32, a_.i32); SIMDE_CONVERT_VECTOR_(r_.m64_private[1].f32, b_.i32); #else r_.f32[0] = (simde_float32) a_.i32[0]; r_.f32[1] = (simde_float32) a_.i32[1]; r_.f32[2] = (simde_float32) b_.i32[0]; r_.f32[3] = (simde_float32) b_.i32[1]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpi32x2_ps(a, b) simde_mm_cvtpi32x2_ps(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpi8_ps (simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpi8_ps(a); #else simde__m128_private r_; simde__m64_private a_ = simde__m64_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcvtq_f32_s32(vmovl_s16(vget_low_s16(vmovl_s8(a_.neon_i8)))); #else r_.f32[0] = HEDLEY_STATIC_CAST(simde_float32, a_.i8[0]); r_.f32[1] = HEDLEY_STATIC_CAST(simde_float32, a_.i8[1]); r_.f32[2] = HEDLEY_STATIC_CAST(simde_float32, a_.i8[2]); r_.f32[3] = HEDLEY_STATIC_CAST(simde_float32, a_.i8[3]); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpi8_ps(a) simde_mm_cvtpi8_ps(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_cvtps_pi16 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtps_pi16(a); #else simde__m64_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V8_NATIVE) && !defined(SIMDE_BUG_GCC_95399) r_.neon_i16 = vmovn_s32(vcvtq_s32_f32(vrndiq_f32(a_.neon_f32))); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i16) / sizeof(r_.i16[0])) ; i++) { r_.i16[i] = SIMDE_CONVERT_FTOI(int16_t, simde_math_roundf(a_.f32[i])); } #endif return simde__m64_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtps_pi16(a) simde_mm_cvtps_pi16((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_cvtps_pi32 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtps_pi32(a); #else simde__m64_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V8_NATIVE) && defined(SIMDE_FAST_CONVERSION_RANGE) && !defined(SIMDE_BUG_GCC_95399) r_.neon_i32 = vcvt_s32_f32(vget_low_f32(vrndiq_f32(a_.neon_f32))); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { simde_float32 v = simde_math_roundf(a_.f32[i]); #if !defined(SIMDE_FAST_CONVERSION_RANGE) r_.i32[i] = ((v > HEDLEY_STATIC_CAST(simde_float32, INT32_MIN)) && (v < HEDLEY_STATIC_CAST(simde_float32, INT32_MAX))) ? SIMDE_CONVERT_FTOI(int32_t, v) : INT32_MIN; #else r_.i32[i] = SIMDE_CONVERT_FTOI(int32_t, v); #endif } #endif return simde__m64_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtps_pi32(a) simde_mm_cvtps_pi32((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_cvtps_pi8 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtps_pi8(a); #else simde__m64_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V8_NATIVE) && !defined(SIMDE_BUG_GCC_95471) /* Clamp the input to [INT8_MIN, INT8_MAX], round, convert to i32, narrow to * i16, combine with an all-zero vector of i16 (which will become the upper * half), narrow to i8. */ float32x4_t max = vdupq_n_f32(HEDLEY_STATIC_CAST(simde_float32, INT8_MAX)); float32x4_t min = vdupq_n_f32(HEDLEY_STATIC_CAST(simde_float32, INT8_MIN)); float32x4_t values = vrndnq_f32(vmaxq_f32(vminq_f32(max, a_.neon_f32), min)); r_.neon_i8 = vmovn_s16(vcombine_s16(vmovn_s32(vcvtq_s32_f32(values)), vdup_n_s16(0))); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(a_.f32) / sizeof(a_.f32[0])) ; i++) { if (a_.f32[i] > HEDLEY_STATIC_CAST(simde_float32, INT8_MAX)) r_.i8[i] = INT8_MAX; else if (a_.f32[i] < HEDLEY_STATIC_CAST(simde_float32, INT8_MIN)) r_.i8[i] = INT8_MIN; else r_.i8[i] = SIMDE_CONVERT_FTOI(int8_t, simde_math_roundf(a_.f32[i])); } /* Note: the upper half is undefined */ #endif return simde__m64_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtps_pi8(a) simde_mm_cvtps_pi8((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpu16_ps (simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpu16_ps(a); #else simde__m128_private r_; simde__m64_private a_ = simde__m64_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcvtq_f32_u32(vmovl_u16(a_.neon_u16)); #elif defined(SIMDE_CONVERT_VECTOR_) SIMDE_CONVERT_VECTOR_(r_.f32, a_.u16); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = (simde_float32) a_.u16[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpu16_ps(a) simde_mm_cvtpu16_ps(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpu8_ps (simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpu8_ps(a); #else simde__m128_private r_; simde__m64_private a_ = simde__m64_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcvtq_f32_u32(vmovl_u16(vget_low_u16(vmovl_u8(a_.neon_u8)))); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = HEDLEY_STATIC_CAST(simde_float32, a_.u8[i]); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpu8_ps(a) simde_mm_cvtpu8_ps(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtsi32_ss (simde__m128 a, int32_t b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cvtsi32_ss(a, b); #else simde__m128_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(HEDLEY_STATIC_CAST(float32_t, b), a_.neon_f32, 0); #else r_ = a_; r_.f32[0] = HEDLEY_STATIC_CAST(simde_float32, b); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtsi32_ss(a, b) simde_mm_cvtsi32_ss((a), b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtsi64_ss (simde__m128 a, int64_t b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_ARCH_AMD64) #if !defined(__PGI) return _mm_cvtsi64_ss(a, b); #else return _mm_cvtsi64x_ss(a, b); #endif #else simde__m128_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(HEDLEY_STATIC_CAST(float32_t, b), a_.neon_f32, 0); #else r_ = a_; r_.f32[0] = HEDLEY_STATIC_CAST(simde_float32, b); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtsi64_ss(a, b) simde_mm_cvtsi64_ss((a), b) #endif SIMDE_FUNCTION_ATTRIBUTES simde_float32 simde_mm_cvtss_f32 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cvtss_f32(a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vgetq_lane_f32(a_.neon_f32, 0); #else return a_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtss_f32(a) simde_mm_cvtss_f32((a)) #endif SIMDE_FUNCTION_ATTRIBUTES int32_t simde_mm_cvtss_si32 (simde__m128 a) { return simde_mm_cvt_ss2si(a); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtss_si32(a) simde_mm_cvtss_si32((a)) #endif SIMDE_FUNCTION_ATTRIBUTES int64_t simde_mm_cvtss_si64 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_ARCH_AMD64) #if !defined(__PGI) return _mm_cvtss_si64(a); #else return _mm_cvtss_si64x(a); #endif #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return SIMDE_CONVERT_FTOI(int64_t, simde_math_roundf(vgetq_lane_f32(a_.neon_f32, 0))); #else return SIMDE_CONVERT_FTOI(int64_t, simde_math_roundf(a_.f32[0])); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtss_si64(a) simde_mm_cvtss_si64((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_cvtt_ps2pi (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtt_ps2pi(a); #else simde__m64_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) && defined(SIMDE_FAST_CONVERSION_RANGE) r_.neon_i32 = vcvt_s32_f32(vget_low_f32(a_.neon_f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { simde_float32 v = a_.f32[i]; #if !defined(SIMDE_FAST_CONVERSION_RANGE) r_.i32[i] = ((v > HEDLEY_STATIC_CAST(simde_float32, INT32_MIN)) && (v < HEDLEY_STATIC_CAST(simde_float32, INT32_MAX))) ? SIMDE_CONVERT_FTOI(int32_t, v) : INT32_MIN; #else r_.i32[i] = SIMDE_CONVERT_FTOI(int32_t, v); #endif } #endif return simde__m64_from_private(r_); #endif } #define simde_mm_cvttps_pi32(a) simde_mm_cvtt_ps2pi(a) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtt_ps2pi(a) simde_mm_cvtt_ps2pi((a)) # define _mm_cvttps_pi32(a) simde_mm_cvttps_pi32((a)) #endif SIMDE_FUNCTION_ATTRIBUTES int32_t simde_mm_cvtt_ss2si (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cvtt_ss2si(a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) && defined(SIMDE_FAST_CONVERSION_RANGE) return SIMDE_CONVERT_FTOI(int32_t, vgetq_lane_f32(a_.neon_f32, 0)); #else simde_float32 v = a_.f32[0]; #if !defined(SIMDE_FAST_CONVERSION_RANGE) return ((v > HEDLEY_STATIC_CAST(simde_float32, INT32_MIN)) && (v < HEDLEY_STATIC_CAST(simde_float32, INT32_MAX))) ? SIMDE_CONVERT_FTOI(int32_t, v) : INT32_MIN; #else return SIMDE_CONVERT_FTOI(int32_t, v); #endif #endif #endif } #define simde_mm_cvttss_si32(a) simde_mm_cvtt_ss2si((a)) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtt_ss2si(a) simde_mm_cvtt_ss2si((a)) # define _mm_cvttss_si32(a) simde_mm_cvtt_ss2si((a)) #endif SIMDE_FUNCTION_ATTRIBUTES int64_t simde_mm_cvttss_si64 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_ARCH_AMD64) && !defined(_MSC_VER) #if defined(__PGI) return _mm_cvttss_si64x(a); #else return _mm_cvttss_si64(a); #endif #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return SIMDE_CONVERT_FTOI(int64_t, vgetq_lane_f32(a_.neon_f32, 0)); #else return SIMDE_CONVERT_FTOI(int64_t, a_.f32[0]); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvttss_si64(a) simde_mm_cvttss_si64((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpord_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpord_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpord_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(simde_math_isnanf) r_.u32[0] = (simde_math_isnanf(simde_mm_cvtss_f32(a)) || simde_math_isnanf(simde_mm_cvtss_f32(b))) ? UINT32_C(0) : ~UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpord_ss(a, b) simde_mm_cmpord_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_div_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_div_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) r_.neon_f32 = vdivq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x4_t recip0 = vrecpeq_f32(b_.neon_f32); float32x4_t recip1 = vmulq_f32(recip0, vrecpsq_f32(recip0, b_.neon_f32)); r_.neon_f32 = vmulq_f32(a_.neon_f32, recip1); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_div(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) r_.altivec_f32 = vec_div(a_.altivec_f32, b_.altivec_f32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.f32 = a_.f32 / b_.f32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = a_.f32[i] / b_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_div_ps(a, b) simde_mm_div_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_div_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_div_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_div_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32_t value = vgetq_lane_f32(simde__m128_to_private(simde_mm_div_ps(a, b)).neon_f32, 0); r_.neon_f32 = vsetq_lane_f32(value, a_.neon_f32, 0); #else r_.f32[0] = a_.f32[0] / b_.f32[0]; SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = a_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_div_ss(a, b) simde_mm_div_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int16_t simde_mm_extract_pi16 (simde__m64 a, const int imm8) SIMDE_REQUIRE_CONSTANT_RANGE(imm8, 0, 3) { simde__m64_private a_ = simde__m64_to_private(a); return a_.i16[imm8]; } #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) && !defined(HEDLEY_PGI_VERSION) # if defined(SIMDE_BUG_CLANG_44589) # define simde_mm_extract_pi16(a, imm8) ( \ HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wvector-conversion\"") \ HEDLEY_STATIC_CAST(int16_t, _mm_extract_pi16((a), (imm8))) \ HEDLEY_DIAGNOSTIC_POP \ ) # else # define simde_mm_extract_pi16(a, imm8) HEDLEY_STATIC_CAST(int16_t, _mm_extract_pi16(a, imm8)) # endif #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) # define simde_mm_extract_pi16(a, imm8) vget_lane_s16(simde__m64_to_private(a).neon_i16, imm8) #endif #define simde_m_pextrw(a, imm8) simde_mm_extract_pi16(a, imm8) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_extract_pi16(a, imm8) simde_mm_extract_pi16((a), (imm8)) # define _m_pextrw(a, imm8) simde_mm_extract_pi16((a), (imm8)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_insert_pi16 (simde__m64 a, int16_t i, const int imm8) SIMDE_REQUIRE_CONSTANT_RANGE(imm8, 0, 3) { simde__m64_private r_, a_ = simde__m64_to_private(a); r_.i64[0] = a_.i64[0]; r_.i16[imm8] = i; return simde__m64_from_private(r_); } #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) && !defined(__PGI) # if defined(SIMDE_BUG_CLANG_44589) # define ssimde_mm_insert_pi16(a, i, imm8) ( \ HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wvector-conversion\"") \ (_mm_insert_pi16((a), (i), (imm8))) \ HEDLEY_DIAGNOSTIC_POP \ ) # else # define simde_mm_insert_pi16(a, i, imm8) _mm_insert_pi16(a, i, imm8) # endif #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) # define simde_mm_insert_pi16(a, i, imm8) simde__m64_from_neon_i16(vset_lane_s16((i), simde__m64_to_neon_i16(a), (imm8))) #endif #define simde_m_pinsrw(a, i, imm8) (simde_mm_insert_pi16(a, i, imm8)) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_insert_pi16(a, i, imm8) simde_mm_insert_pi16(a, i, imm8) # define _m_pinsrw(a, i, imm8) simde_mm_insert_pi16(a, i, imm8) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_load_ps (simde_float32 const mem_addr[HEDLEY_ARRAY_PARAM(4)]) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_load_ps(mem_addr); #else simde__m128_private r_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vld1q_f32(mem_addr); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) r_.altivec_f32 = vec_vsx_ld(0, mem_addr); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_ld(0, mem_addr); #else simde_memcpy(&r_, SIMDE_ALIGN_ASSUME_LIKE(mem_addr, simde__m128), sizeof(r_)); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_load_ps(mem_addr) simde_mm_load_ps(mem_addr) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_load1_ps (simde_float32 const* mem_addr) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_load_ps1(mem_addr); #else simde__m128_private r_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vld1q_dup_f32(mem_addr); #else r_ = simde__m128_to_private(simde_mm_set1_ps(*mem_addr)); #endif return simde__m128_from_private(r_); #endif } #define simde_mm_load_ps1(mem_addr) simde_mm_load1_ps(mem_addr) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_load_ps1(mem_addr) simde_mm_load1_ps(mem_addr) # define _mm_load1_ps(mem_addr) simde_mm_load1_ps(mem_addr) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_load_ss (simde_float32 const* mem_addr) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_load_ss(mem_addr); #else simde__m128_private r_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(*mem_addr, vdupq_n_f32(0), 0); #else r_.f32[0] = *mem_addr; r_.i32[1] = 0; r_.i32[2] = 0; r_.i32[3] = 0; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_load_ss(mem_addr) simde_mm_load_ss(mem_addr) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_loadh_pi (simde__m128 a, simde__m64 const* mem_addr) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_loadh_pi(a, HEDLEY_REINTERPRET_CAST(__m64 const*, mem_addr)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcombine_f32(vget_low_f32(a_.neon_f32), vld1_f32(HEDLEY_REINTERPRET_CAST(const float32_t*, mem_addr))); #else simde__m64_private b_ = *HEDLEY_REINTERPRET_CAST(simde__m64_private const*, mem_addr); r_.f32[0] = a_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = b_.f32[0]; r_.f32[3] = b_.f32[1]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #if HEDLEY_HAS_WARNING("-Wold-style-cast") #define _mm_loadh_pi(a, mem_addr) simde_mm_loadh_pi((a), HEDLEY_REINTERPRET_CAST(simde__m64 const*, (mem_addr))) #else #define _mm_loadh_pi(a, mem_addr) simde_mm_loadh_pi((a), (simde__m64 const*) (mem_addr)) #endif #endif /* The SSE documentation says that there are no alignment requirements for mem_addr. Unfortunately they used the __m64 type for the argument which is supposed to be 8-byte aligned, so some compilers (like clang with -Wcast-align) will generate a warning if you try to cast, say, a simde_float32* to a simde__m64* for this function. I think the choice of argument type is unfortunate, but I do think we need to stick to it here. If there is demand I can always add something like simde_x_mm_loadl_f32(simde__m128, simde_float32 mem_addr[2]) */ SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_loadl_pi (simde__m128 a, simde__m64 const* mem_addr) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_loadl_pi(a, HEDLEY_REINTERPRET_CAST(__m64 const*, mem_addr)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcombine_f32(vld1_f32( HEDLEY_REINTERPRET_CAST(const float32_t*, mem_addr)), vget_high_f32(a_.neon_f32)); #else simde__m64_private b_; simde_memcpy(&b_, mem_addr, sizeof(b_)); r_.i32[0] = b_.i32[0]; r_.i32[1] = b_.i32[1]; r_.i32[2] = a_.i32[2]; r_.i32[3] = a_.i32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #if HEDLEY_HAS_WARNING("-Wold-style-cast") #define _mm_loadl_pi(a, mem_addr) simde_mm_loadl_pi((a), HEDLEY_REINTERPRET_CAST(simde__m64 const*, (mem_addr))) #else #define _mm_loadl_pi(a, mem_addr) simde_mm_loadl_pi((a), (simde__m64 const*) (mem_addr)) #endif #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_loadr_ps (simde_float32 const mem_addr[HEDLEY_ARRAY_PARAM(4)]) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_loadr_ps(mem_addr); #else simde__m128_private r_, v_ = simde__m128_to_private(simde_mm_load_ps(mem_addr)); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vrev64q_f32(v_.neon_f32); r_.neon_f32 = vextq_f32(r_.neon_f32, r_.neon_f32, 2); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) && defined(__PPC64__) r_.altivec_f32 = vec_reve(v_.altivec_f32); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, v_.f32, v_.f32, 3, 2, 1, 0); #else r_.f32[0] = v_.f32[3]; r_.f32[1] = v_.f32[2]; r_.f32[2] = v_.f32[1]; r_.f32[3] = v_.f32[0]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_loadr_ps(mem_addr) simde_mm_loadr_ps(mem_addr) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_loadu_ps (simde_float32 const mem_addr[HEDLEY_ARRAY_PARAM(4)]) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_loadu_ps(mem_addr); #else simde__m128_private r_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vld1q_f32(HEDLEY_REINTERPRET_CAST(const float32_t*, mem_addr)); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_load(mem_addr); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) && defined(__PPC64__) r_.altivec_f32 = vec_vsx_ld(0, mem_addr); #else simde_memcpy(&r_, mem_addr, sizeof(r_)); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_loadu_ps(mem_addr) simde_mm_loadu_ps(mem_addr) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_maskmove_si64 (simde__m64 a, simde__m64 mask, int8_t* mem_addr) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) _mm_maskmove_si64(a, mask, HEDLEY_REINTERPRET_CAST(char*, mem_addr)); #else simde__m64_private a_ = simde__m64_to_private(a), mask_ = simde__m64_to_private(mask); SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(a_.i8) / sizeof(a_.i8[0])) ; i++) if (mask_.i8[i] < 0) mem_addr[i] = a_.i8[i]; #endif } #define simde_m_maskmovq(a, mask, mem_addr) simde_mm_maskmove_si64(a, mask, mem_addr) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_maskmove_si64(a, mask, mem_addr) simde_mm_maskmove_si64((a), (mask), SIMDE_CHECKED_REINTERPRET_CAST(int8_t*, char*, (mem_addr))) # define _m_maskmovq(a, mask, mem_addr) simde_mm_maskmove_si64((a), (mask), SIMDE_CHECKED_REINTERPRET_CAST(int8_t*, char*, (mem_addr))) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_max_pi16 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_max_pi16(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i16 = vmax_s16(a_.neon_i16, b_.neon_i16); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i16) / sizeof(r_.i16[0])) ; i++) { r_.i16[i] = (a_.i16[i] > b_.i16[i]) ? a_.i16[i] : b_.i16[i]; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pmaxsw(a, b) simde_mm_max_pi16(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_max_pi16(a, b) simde_mm_max_pi16(a, b) # define _m_pmaxsw(a, b) simde_mm_max_pi16(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_max_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_max_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) && defined(SIMDE_FAST_NANS) r_.neon_f32 = vmaxq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vbslq_f32(vcgtq_f32(a_.neon_f32, b_.neon_f32), a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) && defined(SIMDE_FAST_NANS) r_.wasm_v128 = wasm_f32x4_max(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_bitselect(a_.wasm_v128, b_.wasm_v128, wasm_f32x4_gt(a_.wasm_v128, b_.wasm_v128)); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) && defined(SIMDE_FAST_NANS) r_.altivec_f32 = vec_max(a_.altivec_f32, b_.altivec_f32); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_sel(b_.altivec_f32, a_.altivec_f32, vec_cmpgt(a_.altivec_f32, b_.altivec_f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = (a_.f32[i] > b_.f32[i]) ? a_.f32[i] : b_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_max_ps(a, b) simde_mm_max_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_max_pu8 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_max_pu8(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u8 = vmax_u8(a_.neon_u8, b_.neon_u8); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u8) / sizeof(r_.u8[0])) ; i++) { r_.u8[i] = (a_.u8[i] > b_.u8[i]) ? a_.u8[i] : b_.u8[i]; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pmaxub(a, b) simde_mm_max_pu8(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_max_pu8(a, b) simde_mm_max_pu8(a, b) # define _m_pmaxub(a, b) simde_mm_max_pu8(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_max_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_max_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_max_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32_t value = vgetq_lane_f32(maxq_f32(a_.neon_f32, b_.neon_f32), 0); r_.neon_f32 = vsetq_lane_f32(value, a_.neon_f32, 0); #else r_.f32[0] = (a_.f32[0] > b_.f32[0]) ? a_.f32[0] : b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_max_ss(a, b) simde_mm_max_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_min_pi16 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_min_pi16(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i16 = vmin_s16(a_.neon_i16, b_.neon_i16); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i16) / sizeof(r_.i16[0])) ; i++) { r_.i16[i] = (a_.i16[i] < b_.i16[i]) ? a_.i16[i] : b_.i16[i]; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pminsw(a, b) simde_mm_min_pi16(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_min_pi16(a, b) simde_mm_min_pi16(a, b) # define _m_pminsw(a, b) simde_mm_min_pi16(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_min_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_min_ps(a, b); #elif defined(SIMDE_FAST_NANS) && defined(SIMDE_ARM_NEON_A32V7_NATIVE) return simde__m128_from_neon_f32(vminq_f32(simde__m128_to_neon_f32(a), simde__m128_to_neon_f32(b))); #elif defined(SIMDE_WASM_SIMD128_NATIVE) simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_FAST_NANS) r_.wasm_v128 = wasm_f32x4_min(a_.wasm_v128, b_.wasm_v128); #else r_.wasm_v128 = wasm_v128_bitselect(a_.wasm_v128, b_.wasm_v128, wasm_f32x4_lt(a_.wasm_v128, b_.wasm_v128)); #endif return simde__m128_from_private(r_); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_FAST_NANS) r_.altivec_f32 = vec_min(a_.altivec_f32, b_.altivec_f32); #else r_.altivec_f32 = vec_sel(b_.altivec_f32, a_.altivec_f32, vec_cmpgt(b_.altivec_f32, a_.altivec_f32)); #endif return simde__m128_from_private(r_); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) simde__m128 mask = simde_mm_cmplt_ps(a, b); return simde_mm_or_ps(simde_mm_and_ps(mask, a), simde_mm_andnot_ps(mask, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = (a_.f32[i] < b_.f32[i]) ? a_.f32[i] : b_.f32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_min_ps(a, b) simde_mm_min_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_min_pu8 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_min_pu8(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u8 = vmin_u8(a_.neon_u8, b_.neon_u8); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u8) / sizeof(r_.u8[0])) ; i++) { r_.u8[i] = (a_.u8[i] < b_.u8[i]) ? a_.u8[i] : b_.u8[i]; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pminub(a, b) simde_mm_min_pu8(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_min_pu8(a, b) simde_mm_min_pu8(a, b) # define _m_pminub(a, b) simde_mm_min_pu8(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_min_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_min_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_min_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32_t value = vgetq_lane_f32(vminq_f32(a_.neon_f32, b_.neon_f32), 0); r_.neon_f32 = vsetq_lane_f32(value, a_.neon_f32, 0); #else r_.f32[0] = (a_.f32[0] < b_.f32[0]) ? a_.f32[0] : b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_min_ss(a, b) simde_mm_min_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_movehl_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_movehl_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x2_t a32 = vget_high_f32(a_.neon_f32); float32x2_t b32 = vget_high_f32(b_.neon_f32); r_.neon_f32 = vcombine_f32(b32, a32); #elif defined(SIMDE_POWER_ALTIVEC_P8_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_mergel(b_.altivec_i64, a_.altivec_i64)); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, b_.f32, 6, 7, 2, 3); #else r_.f32[0] = b_.f32[2]; r_.f32[1] = b_.f32[3]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_movehl_ps(a, b) simde_mm_movehl_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_movelh_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_movelh_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x2_t a10 = vget_low_f32(a_.neon_f32); float32x2_t b10 = vget_low_f32(b_.neon_f32); r_.neon_f32 = vcombine_f32(a10, b10); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, b_.f32, 0, 1, 4, 5); #elif defined(SIMDE_POWER_ALTIVEC_P8_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_mergeh(a_.altivec_i64, b_.altivec_i64)); #else r_.f32[0] = a_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = b_.f32[0]; r_.f32[3] = b_.f32[1]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_movelh_ps(a, b) simde_mm_movelh_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_movemask_pi8 (simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_movemask_pi8(a); #else simde__m64_private a_ = simde__m64_to_private(a); int r = 0; #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) uint8x8_t input = a_.neon_u8; const int8_t xr[8] = {-7, -6, -5, -4, -3, -2, -1, 0}; const uint8x8_t mask_and = vdup_n_u8(0x80); const int8x8_t mask_shift = vld1_s8(xr); const uint8x8_t mask_result = vshl_u8(vand_u8(input, mask_and), mask_shift); uint8x8_t lo = mask_result; r = vaddv_u8(lo); #else const size_t nmemb = sizeof(a_.i8) / sizeof(a_.i8[0]); SIMDE_VECTORIZE_REDUCTION(|:r) for (size_t i = 0 ; i < nmemb ; i++) { r |= (a_.u8[nmemb - 1 - i] >> 7) << (nmemb - 1 - i); } #endif return r; #endif } #define simde_m_pmovmskb(a) simde_mm_movemask_pi8(a) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_movemask_pi8(a) simde_mm_movemask_pi8(a) # define _m_pmovmskb(a) simde_mm_movemask_pi8(a) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_movemask_ps (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_movemask_ps(a); #else int r = 0; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) static const int32_t shift_amount[] = { 0, 1, 2, 3 }; const int32x4_t shift = vld1q_s32(shift_amount); uint32x4_t tmp = vshrq_n_u32(a_.neon_u32, 31); return HEDLEY_STATIC_CAST(int, vaddvq_u32(vshlq_u32(tmp, shift))); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) // Shift out everything but the sign bits with a 32-bit unsigned shift right. uint64x2_t high_bits = vreinterpretq_u64_u32(vshrq_n_u32(a_.neon_u32, 31)); // Merge the two pairs together with a 64-bit unsigned shift right + add. uint8x16_t paired = vreinterpretq_u8_u64(vsraq_n_u64(high_bits, high_bits, 31)); // Extract the result. return vgetq_lane_u8(paired, 0) | (vgetq_lane_u8(paired, 8) << 2); #else SIMDE_VECTORIZE_REDUCTION(|:r) for (size_t i = 0 ; i < sizeof(a_.u32) / sizeof(a_.u32[0]) ; i++) { r |= (a_.u32[i] >> ((sizeof(a_.u32[i]) * CHAR_BIT) - 1)) << i; } #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_movemask_ps(a) simde_mm_movemask_ps((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_mul_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_mul_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vmulq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_mul(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.f32 = a_.f32 * b_.f32; #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) r_.altivec_f32 = vec_mul(a_.altivec_f32, b_.altivec_f32); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = a_.f32[i] * b_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_mul_ps(a, b) simde_mm_mul_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_mul_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_mul_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_mul_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.f32[0] = a_.f32[0] * b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_mul_ss(a, b) simde_mm_mul_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_mulhi_pu16 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_mulhi_pu16(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) const uint32x4_t t1 = vmull_u16(a_.neon_u16, b_.neon_u16); const uint32x4_t t2 = vshrq_n_u32(t1, 16); const uint16x4_t t3 = vmovn_u32(t2); r_.neon_u16 = t3; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u16) / sizeof(r_.u16[0])) ; i++) { r_.u16[i] = HEDLEY_STATIC_CAST(uint16_t, ((HEDLEY_STATIC_CAST(uint32_t, a_.u16[i]) * HEDLEY_STATIC_CAST(uint32_t, b_.u16[i])) >> UINT32_C(16))); } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pmulhuw(a, b) simde_mm_mulhi_pu16(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_mulhi_pu16(a, b) simde_mm_mulhi_pu16(a, b) # define _m_pmulhuw(a, b) simde_mm_mulhi_pu16(a, b) #endif #if defined(SIMDE_X86_SSE_NATIVE) && defined(HEDLEY_GCC_VERSION) #define SIMDE_MM_HINT_NTA HEDLEY_STATIC_CAST(enum _mm_hint, 0) #define SIMDE_MM_HINT_T0 HEDLEY_STATIC_CAST(enum _mm_hint, 1) #define SIMDE_MM_HINT_T1 HEDLEY_STATIC_CAST(enum _mm_hint, 2) #define SIMDE_MM_HINT_T2 HEDLEY_STATIC_CAST(enum _mm_hint, 3) #define SIMDE_MM_HINT_ENTA HEDLEY_STATIC_CAST(enum _mm_hint, 4) #define SIMDE_MM_HINT_ET0 HEDLEY_STATIC_CAST(enum _mm_hint, 5) #define SIMDE_MM_HINT_ET1 HEDLEY_STATIC_CAST(enum _mm_hint, 6) #define SIMDE_MM_HINT_ET2 HEDLEY_STATIC_CAST(enum _mm_hint, 7) #else #define SIMDE_MM_HINT_NTA 0 #define SIMDE_MM_HINT_T0 1 #define SIMDE_MM_HINT_T1 2 #define SIMDE_MM_HINT_T2 3 #define SIMDE_MM_HINT_ENTA 4 #define SIMDE_MM_HINT_ET0 5 #define SIMDE_MM_HINT_ET1 6 #define SIMDE_MM_HINT_ET2 7 #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) HEDLEY_DIAGNOSTIC_PUSH #if HEDLEY_HAS_WARNING("-Wreserved-id-macro") _Pragma("clang diagnostic ignored \"-Wreserved-id-macro\"") #endif #undef _MM_HINT_NTA #define _MM_HINT_NTA SIMDE_MM_HINT_NTA #undef _MM_HINT_T0 #define _MM_HINT_T0 SIMDE_MM_HINT_T0 #undef _MM_HINT_T1 #define _MM_HINT_T1 SIMDE_MM_HINT_T1 #undef _MM_HINT_T2 #define _MM_HINT_T2 SIMDE_MM_HINT_T2 #undef _MM_HINT_ETNA #define _MM_HINT_ETNA SIMDE_MM_HINT_ETNA #undef _MM_HINT_ET0 #define _MM_HINT_ET0 SIMDE_MM_HINT_ET0 #undef _MM_HINT_ET1 #define _MM_HINT_ET1 SIMDE_MM_HINT_ET1 #undef _MM_HINT_ET1 #define _MM_HINT_ET2 SIMDE_MM_HINT_ET2 HEDLEY_DIAGNOSTIC_POP #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_prefetch (char const* p, int i) { #if defined(HEDLEY_GCC_VERSION) __builtin_prefetch(p); #else (void) p; #endif (void) i; } #if defined(SIMDE_X86_SSE_NATIVE) #if defined(__clang__) && !SIMDE_DETECT_CLANG_VERSION_CHECK(10,0,0) /* https://reviews.llvm.org/D71718 */ #define simde_mm_prefetch(p, i) \ (__extension__({ \ HEDLEY_DIAGNOSTIC_PUSH \ HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ _mm_prefetch((p), (i)); \ HEDLEY_DIAGNOSTIC_POP \ })) #else #define simde_mm_prefetch(p, i) _mm_prefetch(p, i) #endif #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _mm_prefetch(p, i) simde_mm_prefetch(p, i) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_negate_ps(simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return simde_mm_xor_ps(a, _mm_set1_ps(SIMDE_FLOAT32_C(-0.0))); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_POWER_ALTIVEC_P8_NATIVE) && \ (!defined(HEDLEY_GCC_VERSION) || HEDLEY_GCC_VERSION_CHECK(8,1,0)) r_.altivec_f32 = vec_neg(a_.altivec_f32); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vnegq_f32(a_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_neg(a_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P8_NATIVE) r_.altivec_f32 = vec_neg(a_.altivec_f32); #elif defined(SIMDE_VECTOR_NEGATE) r_.f32 = -a_.f32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = -a_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_rcp_ps (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_rcp_ps(a); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x4_t recip = vrecpeq_f32(a_.neon_f32); #if SIMDE_ACCURACY_PREFERENCE > 0 for (int i = 0; i < SIMDE_ACCURACY_PREFERENCE ; ++i) { recip = vmulq_f32(recip, vrecpsq_f32(recip, a_.neon_f32)); } #endif r_.neon_f32 = recip; #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_div(simde_mm_set1_ps(1.0f), a_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_re(a_.altivec_f32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_SCALAR) r_.f32 = 1.0f / a_.f32; #elif defined(SIMDE_IEEE754_STORAGE) /* https://stackoverflow.com/questions/12227126/division-as-multiply-and-lut-fast-float-division-reciprocal/12228234#12228234 */ SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { int32_t ix; simde_float32 fx = a_.f32[i]; simde_memcpy(&ix, &fx, sizeof(ix)); int32_t x = INT32_C(0x7EF311C3) - ix; simde_float32 temp; simde_memcpy(&temp, &x, sizeof(temp)); r_.f32[i] = temp * (SIMDE_FLOAT32_C(2.0) - temp * fx); } #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = 1.0f / a_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_rcp_ps(a) simde_mm_rcp_ps((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_rcp_ss (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_rcp_ss(a); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_rcp_ps(a)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); r_.f32[0] = 1.0f / a_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_rcp_ss(a) simde_mm_rcp_ss((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_rsqrt_ps (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_rsqrt_ps(a); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vrsqrteq_f32(a_.neon_f32); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_rsqrte(a_.altivec_f32); #elif defined(SIMDE_IEEE754_STORAGE) /* https://basesandframes.files.wordpress.com/2020/04/even_faster_math_functions_green_2020.pdf Pages 100 - 103 */ SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { #if SIMDE_ACCURACY_PREFERENCE <= 0 r_.i32[i] = INT32_C(0x5F37624F) - (a_.i32[i] >> 1); #else simde_float32 x = a_.f32[i]; simde_float32 xhalf = SIMDE_FLOAT32_C(0.5) * x; int32_t ix; simde_memcpy(&ix, &x, sizeof(ix)); #if SIMDE_ACCURACY_PREFERENCE == 1 ix = INT32_C(0x5F375A82) - (ix >> 1); #else ix = INT32_C(0x5F37599E) - (ix >> 1); #endif simde_memcpy(&x, &ix, sizeof(x)); #if SIMDE_ACCURACY_PREFERENCE >= 2 x = x * (SIMDE_FLOAT32_C(1.5008909) - xhalf * x * x); #endif x = x * (SIMDE_FLOAT32_C(1.5008909) - xhalf * x * x); r_.f32[i] = x; #endif } #elif defined(simde_math_sqrtf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = 1.0f / simde_math_sqrtf(a_.f32[i]); } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_rsqrt_ps(a) simde_mm_rsqrt_ps((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_rsqrt_ss (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_rsqrt_ss(a); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_rsqrt_ps(a)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(vgetq_lane_f32(simde_mm_rsqrt_ps(a).neon_f32, 0), a_.neon_f32, 0); #elif defined(SIMDE_IEEE754_STORAGE) { #if SIMDE_ACCURACY_PREFERENCE <= 0 r_.i32[0] = INT32_C(0x5F37624F) - (a_.i32[0] >> 1); #else simde_float32 x = a_.f32[0]; simde_float32 xhalf = SIMDE_FLOAT32_C(0.5) * x; int32_t ix; simde_memcpy(&ix, &x, sizeof(ix)); #if SIMDE_ACCURACY_PREFERENCE == 1 ix = INT32_C(0x5F375A82) - (ix >> 1); #else ix = INT32_C(0x5F37599E) - (ix >> 1); #endif simde_memcpy(&x, &ix, sizeof(x)); #if SIMDE_ACCURACY_PREFERENCE >= 2 x = x * (SIMDE_FLOAT32_C(1.5008909) - xhalf * x * x); #endif x = x * (SIMDE_FLOAT32_C(1.5008909) - xhalf * x * x); r_.f32[0] = x; #endif } r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #elif defined(simde_math_sqrtf) r_.f32[0] = 1.0f / simde_math_sqrtf(a_.f32[0]); r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_rsqrt_ss(a) simde_mm_rsqrt_ss((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_sad_pu8 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_sad_pu8(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint16x4_t t = vpaddl_u8(vabd_u8(a_.neon_u8, b_.neon_u8)); uint16_t r0 = t[0] + t[1] + t[2] + t[3]; r_.neon_u16 = vset_lane_u16(r0, vdup_n_u16(0), 0); #else uint16_t sum = 0; #if defined(SIMDE_HAVE_STDLIB_H) SIMDE_VECTORIZE_REDUCTION(+:sum) for (size_t i = 0 ; i < (sizeof(r_.u8) / sizeof(r_.u8[0])) ; i++) { sum += HEDLEY_STATIC_CAST(uint8_t, abs(a_.u8[i] - b_.u8[i])); } r_.i16[0] = HEDLEY_STATIC_CAST(int16_t, sum); r_.i16[1] = 0; r_.i16[2] = 0; r_.i16[3] = 0; #else HEDLEY_UNREACHABLE(); #endif #endif return simde__m64_from_private(r_); #endif } #define simde_m_psadbw(a, b) simde_mm_sad_pu8(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sad_pu8(a, b) simde_mm_sad_pu8(a, b) # define _m_psadbw(a, b) simde_mm_sad_pu8(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_set_ss (simde_float32 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_set_ss(a); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vsetq_lane_f32(a, vdupq_n_f32(SIMDE_FLOAT32_C(0.0)), 0); #else return simde_mm_set_ps(SIMDE_FLOAT32_C(0.0), SIMDE_FLOAT32_C(0.0), SIMDE_FLOAT32_C(0.0), a); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_set_ss(a) simde_mm_set_ss(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_setr_ps (simde_float32 e3, simde_float32 e2, simde_float32 e1, simde_float32 e0) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_setr_ps(e3, e2, e1, e0); #else return simde_mm_set_ps(e0, e1, e2, e3); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_setr_ps(e3, e2, e1, e0) simde_mm_setr_ps(e3, e2, e1, e0) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_setzero_ps (void) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_setzero_ps(); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vdupq_n_f32(SIMDE_FLOAT32_C(0.0)); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) return vec_splats(SIMDE_FLOAT32_C(0.0)); #else simde__m128 r; simde_memset(&r, 0, sizeof(r)); return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_setzero_ps() simde_mm_setzero_ps() #endif #if defined(SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_) HEDLEY_DIAGNOSTIC_PUSH SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_undefined_ps (void) { simde__m128_private r_; #if defined(SIMDE_HAVE_UNDEFINED128) r_.n = _mm_undefined_ps(); #elif !defined(SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_) r_ = simde__m128_to_private(simde_mm_setzero_ps()); #endif return simde__m128_from_private(r_); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_undefined_ps() simde_mm_undefined_ps() #endif #if defined(SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_) HEDLEY_DIAGNOSTIC_POP #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_setone_ps (void) { simde__m128 t = simde_mm_setzero_ps(); return simde_mm_cmpeq_ps(t, t); } SIMDE_FUNCTION_ATTRIBUTES void simde_mm_sfence (void) { /* TODO: Use Hedley. */ #if defined(SIMDE_X86_SSE_NATIVE) _mm_sfence(); #elif defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)) __atomic_thread_fence(__ATOMIC_SEQ_CST); #elif !defined(__INTEL_COMPILER) && defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(__STDC_NO_ATOMICS__) #if defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ < 9) __atomic_thread_fence(__ATOMIC_SEQ_CST); #else atomic_thread_fence(memory_order_seq_cst); #endif #elif defined(_MSC_VER) MemoryBarrier(); #elif HEDLEY_HAS_EXTENSION(c_atomic) __c11_atomic_thread_fence(__ATOMIC_SEQ_CST); #elif defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) __sync_synchronize(); #elif defined(_OPENMP) #pragma omp critical(simde_mm_sfence_) { } #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sfence() simde_mm_sfence() #endif #define SIMDE_MM_SHUFFLE(z, y, x, w) (((z) << 6) | ((y) << 4) | ((x) << 2) | (w)) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _MM_SHUFFLE(z, y, x, w) SIMDE_MM_SHUFFLE(z, y, x, w) #endif #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) && !defined(__PGI) # define simde_mm_shuffle_pi16(a, imm8) _mm_shuffle_pi16(a, imm8) #elif defined(SIMDE_SHUFFLE_VECTOR_) # define simde_mm_shuffle_pi16(a, imm8) (__extension__ ({ \ const simde__m64_private simde__tmp_a_ = simde__m64_to_private(a); \ simde__m64_from_private((simde__m64_private) { .i16 = \ SIMDE_SHUFFLE_VECTOR_(16, 8, \ (simde__tmp_a_).i16, \ (simde__tmp_a_).i16, \ (((imm8) ) & 3), \ (((imm8) >> 2) & 3), \ (((imm8) >> 4) & 3), \ (((imm8) >> 6) & 3)) }); })) #else SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_shuffle_pi16 (simde__m64 a, const int imm8) SIMDE_REQUIRE_CONSTANT_RANGE(imm8, 0, 255) { simde__m64_private r_; simde__m64_private a_ = simde__m64_to_private(a); for (size_t i = 0 ; i < sizeof(r_.i16) / sizeof(r_.i16[0]) ; i++) { r_.i16[i] = a_.i16[(imm8 >> (i * 2)) & 3]; } HEDLEY_DIAGNOSTIC_PUSH #if HEDLEY_HAS_WARNING("-Wconditional-uninitialized") # pragma clang diagnostic ignored "-Wconditional-uninitialized" #endif return simde__m64_from_private(r_); HEDLEY_DIAGNOSTIC_POP } #endif #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) && !defined(__PGI) # define simde_m_pshufw(a, imm8) _m_pshufw(a, imm8) #else # define simde_m_pshufw(a, imm8) simde_mm_shuffle_pi16(a, imm8) #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_shuffle_pi16(a, imm8) simde_mm_shuffle_pi16(a, imm8) # define _m_pshufw(a, imm8) simde_mm_shuffle_pi16(a, imm8) #endif #if defined(SIMDE_X86_SSE_NATIVE) && !defined(__PGI) # define simde_mm_shuffle_ps(a, b, imm8) _mm_shuffle_ps(a, b, imm8) #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) #define simde_mm_shuffle_ps(a, b, imm8) \ __extension__({ \ float32x4_t ret; \ ret = vmovq_n_f32( \ vgetq_lane_f32(a, (imm8) & (0x3))); \ ret = vsetq_lane_f32( \ vgetq_lane_f32(a, ((imm8) >> 2) & 0x3), \ ret, 1); \ ret = vsetq_lane_f32( \ vgetq_lane_f32(b, ((imm8) >> 4) & 0x3), \ ret, 2); \ ret = vsetq_lane_f32( \ vgetq_lane_f32(b, ((imm8) >> 6) & 0x3), \ ret, 3); \ }) #elif defined(SIMDE_SHUFFLE_VECTOR_) # define simde_mm_shuffle_ps(a, b, imm8) (__extension__ ({ \ simde__m128_from_private((simde__m128_private) { .f32 = \ SIMDE_SHUFFLE_VECTOR_(32, 16, \ simde__m128_to_private(a).f32, \ simde__m128_to_private(b).f32, \ (((imm8) ) & 3), \ (((imm8) >> 2) & 3), \ (((imm8) >> 4) & 3) + 4, \ (((imm8) >> 6) & 3) + 4) }); })) #else SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_shuffle_ps (simde__m128 a, simde__m128 b, const int imm8) SIMDE_REQUIRE_CONSTANT_RANGE(imm8, 0, 255) { simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.f32[0] = a_.f32[(imm8 >> 0) & 3]; r_.f32[1] = a_.f32[(imm8 >> 2) & 3]; r_.f32[2] = b_.f32[(imm8 >> 4) & 3]; r_.f32[3] = b_.f32[(imm8 >> 6) & 3]; return simde__m128_from_private(r_); } #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_shuffle_ps(a, b, imm8) simde_mm_shuffle_ps((a), (b), imm8) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_sqrt_ps (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_sqrt_ps(a); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) r_.neon_f32 = vsqrtq_f32(a_.neon_f32); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x4_t est = vrsqrteq_f32(a_.neon_f32); for (int i = 0 ; i <= SIMDE_ACCURACY_PREFERENCE ; i++) { est = vmulq_f32(vrsqrtsq_f32(vmulq_f32(a_.neon_f32, est), est), est); } r_.neon_f32 = vmulq_f32(a_.neon_f32, est); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_sqrt(a_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) r_.altivec_f32 = vec_sqrt(a_.altivec_f32); #elif defined(simde_math_sqrt) SIMDE_VECTORIZE for (size_t i = 0 ; i < sizeof(r_.f32) / sizeof(r_.f32[0]) ; i++) { r_.f32[i] = simde_math_sqrtf(a_.f32[i]); } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sqrt_ps(a) simde_mm_sqrt_ps((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_sqrt_ss (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_sqrt_ss(a); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_sqrt_ps(a)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32_t value = vgetq_lane_f32(simde__m128_to_private(simde_mm_sqrt_ps(a)).neon_f32, 0); r_.neon_f32 = vsetq_lane_f32(value, a_.neon_f32, 0); #elif defined(simde_math_sqrtf) r_.f32[0] = simde_math_sqrtf(a_.f32[0]); r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sqrt_ss(a) simde_mm_sqrt_ss((a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_store_ps (simde_float32 mem_addr[4], simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_store_ps(mem_addr, a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) vst1q_f32(mem_addr, a_.neon_f32); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) vec_st(a_.altivec_f32, 0, mem_addr); #elif defined(SIMDE_WASM_SIMD128_NATIVE) wasm_v128_store(mem_addr, a_.wasm_v128); #else simde_memcpy(mem_addr, &a_, sizeof(a)); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_store_ps(mem_addr, a) simde_mm_store_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_store1_ps (simde_float32 mem_addr[4], simde__m128 a) { simde_float32* mem_addr_ = SIMDE_ALIGN_ASSUME_LIKE(mem_addr, simde__m128); #if defined(SIMDE_X86_SSE_NATIVE) _mm_store_ps1(mem_addr_, a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) vst1q_f32(mem_addr_, vdupq_lane_f32(vget_low_f32(a_.neon_f32), 0)); #elif defined(SIMDE_WASM_SIMD128_NATIVE) wasm_v128_store(mem_addr_, wasm_v32x4_shuffle(a_.wasm_v128, a_.wasm_v128, 0, 0, 0, 0)); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) vec_st(vec_splat(a_.altivec_f32, 0), 0, mem_addr_); #elif defined(SIMDE_SHUFFLE_VECTOR_) simde__m128_private tmp_; tmp_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, a_.f32, 0, 0, 0, 0); simde_mm_store_ps(mem_addr_, tmp_.f32); #else SIMDE_VECTORIZE_ALIGNED(mem_addr_:16) for (size_t i = 0 ; i < sizeof(a_.f32) / sizeof(a_.f32[0]) ; i++) { mem_addr_[i] = a_.f32[0]; } #endif #endif } #define simde_mm_store_ps1(mem_addr, a) simde_mm_store1_ps(mem_addr, a) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_store_ps1(mem_addr, a) simde_mm_store1_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) # define _mm_store1_ps(mem_addr, a) simde_mm_store1_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_store_ss (simde_float32* mem_addr, simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_store_ss(mem_addr, a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) vst1q_lane_f32(mem_addr, a_.neon_f32, 0); #else *mem_addr = a_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_store_ss(mem_addr, a) simde_mm_store_ss(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_storeh_pi (simde__m64* mem_addr, simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_storeh_pi(HEDLEY_REINTERPRET_CAST(__m64*, mem_addr), a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) vst1_f32(HEDLEY_REINTERPRET_CAST(float32_t*, mem_addr), vget_high_f32(a_.neon_f32)); #else simde_memcpy(mem_addr, &(a_.m64[1]), sizeof(a_.m64[1])); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_storeh_pi(mem_addr, a) simde_mm_storeh_pi(mem_addr, (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_storel_pi (simde__m64* mem_addr, simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_storel_pi(HEDLEY_REINTERPRET_CAST(__m64*, mem_addr), a); #else simde__m64_private* dest_ = HEDLEY_REINTERPRET_CAST(simde__m64_private*, mem_addr); simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) dest_->neon_f32 = vget_low_f32(a_.neon_f32); #else dest_->f32[0] = a_.f32[0]; dest_->f32[1] = a_.f32[1]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_storel_pi(mem_addr, a) simde_mm_storel_pi(mem_addr, (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_storer_ps (simde_float32 mem_addr[4], simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_storer_ps(mem_addr, a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) vec_st(vec_reve(a_.altivec_f32), 0, mem_addr); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x4_t tmp = vrev64q_f32(a_.neon_f32); vst1q_f32(mem_addr, vextq_f32(tmp, tmp, 2)); #elif defined(SIMDE_SHUFFLE_VECTOR_) a_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, a_.f32, 3, 2, 1, 0); simde_mm_store_ps(mem_addr, simde__m128_from_private(a_)); #else SIMDE_VECTORIZE_ALIGNED(mem_addr:16) for (size_t i = 0 ; i < sizeof(a_.f32) / sizeof(a_.f32[0]) ; i++) { mem_addr[i] = a_.f32[((sizeof(a_.f32) / sizeof(a_.f32[0])) - 1) - i]; } #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_storer_ps(mem_addr, a) simde_mm_storer_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_storeu_ps (simde_float32 mem_addr[4], simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_storeu_ps(mem_addr, a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) vst1q_f32(mem_addr, a_.neon_f32); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) vec_vsx_st(a_.altivec_f32, 0, mem_addr); #else simde_memcpy(mem_addr, &a_, sizeof(a_)); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_storeu_ps(mem_addr, a) simde_mm_storeu_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_sub_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_sub_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsubq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_sub(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_sub(a_.altivec_f32, b_.altivec_f32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.f32 = a_.f32 - b_.f32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = a_.f32[i] - b_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sub_ps(a, b) simde_mm_sub_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_sub_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_sub_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_sub_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.f32[0] = a_.f32[0] - b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sub_ss(a, b) simde_mm_sub_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomieq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomieq_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_eq_b = vceqq_f32(a_.neon_f32, b_.neon_f32); r = !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_eq_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] == b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] == b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomieq_ss(a, b) simde_mm_ucomieq_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomige_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomige_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_ge_b = vcgeq_f32(a_.neon_f32, b_.neon_f32); r = !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_ge_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] >= b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] >= b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomige_ss(a, b) simde_mm_ucomige_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomigt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomigt_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_gt_b = vcgtq_f32(a_.neon_f32, b_.neon_f32); r = !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_gt_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] > b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] > b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomigt_ss(a, b) simde_mm_ucomigt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomile_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomile_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_le_b = vcleq_f32(a_.neon_f32, b_.neon_f32); r = !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_le_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] <= b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] <= b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomile_ss(a, b) simde_mm_ucomile_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomilt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomilt_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_lt_b = vcltq_f32(a_.neon_f32, b_.neon_f32); r = !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_lt_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] < b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] < b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomilt_ss(a, b) simde_mm_ucomilt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomineq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomineq_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_neq_b = vmvnq_u32(vceqq_f32(a_.neon_f32, b_.neon_f32)); r = !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_neq_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] != b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] != b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomineq_ss(a, b) simde_mm_ucomineq_ss((a), (b)) #endif #if defined(SIMDE_X86_SSE_NATIVE) # if defined(__has_builtin) # if __has_builtin(__builtin_ia32_undef128) # define SIMDE_HAVE_UNDEFINED128 # endif # elif !defined(__PGI) && !defined(SIMDE_BUG_GCC_REV_208793) && !defined(_MSC_VER) # define SIMDE_HAVE_UNDEFINED128 # endif #endif #if defined(SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_) HEDLEY_DIAGNOSTIC_PUSH SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_unpackhi_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_unpackhi_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) r_.neon_f32 = vzip2q_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x2_t a1 = vget_high_f32(a_.neon_f32); float32x2_t b1 = vget_high_f32(b_.neon_f32); float32x2x2_t result = vzip_f32(a1, b1); r_.neon_f32 = vcombine_f32(result.val[0], result.val[1]); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, b_.f32, 2, 6, 3, 7); #else r_.f32[0] = a_.f32[2]; r_.f32[1] = b_.f32[2]; r_.f32[2] = a_.f32[3]; r_.f32[3] = b_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_unpackhi_ps(a, b) simde_mm_unpackhi_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_unpacklo_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_unpacklo_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) r_.neon_f32 = vzip1q_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_mergeh(a_.altivec_f32, b_.altivec_f32); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, b_.f32, 0, 4, 1, 5); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x2_t a1 = vget_low_f32(a_.neon_f32); float32x2_t b1 = vget_low_f32(b_.neon_f32); float32x2x2_t result = vzip_f32(a1, b1); r_.neon_f32 = vcombine_f32(result.val[0], result.val[1]); #else r_.f32[0] = a_.f32[0]; r_.f32[1] = b_.f32[0]; r_.f32[2] = a_.f32[1]; r_.f32[3] = b_.f32[1]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_unpacklo_ps(a, b) simde_mm_unpacklo_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_stream_pi (simde__m64* mem_addr, simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) _mm_stream_pi(HEDLEY_REINTERPRET_CAST(__m64*, mem_addr), a); #else simde__m64_private* dest = HEDLEY_REINTERPRET_CAST(simde__m64_private*, mem_addr), a_ = simde__m64_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) dest->i64[0] = vget_lane_s64(a_.neon_i64, 0); #else dest->i64[0] = a_.i64[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_stream_pi(mem_addr, a) simde_mm_stream_pi(mem_addr, (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_stream_ps (simde_float32 mem_addr[4], simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_stream_ps(mem_addr, a); #elif HEDLEY_HAS_BUILTIN(__builtin_nontemporal_store) && defined(SIMDE_VECTOR_SUBSCRIPT_OPS) simde__m128_private a_ = simde__m128_to_private(a); __builtin_nontemporal_store(a_.f32, SIMDE_ALIGN_CAST(__typeof__(a_.f32)*, mem_addr)); #else simde_mm_store_ps(mem_addr, a); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_stream_ps(mem_addr, a) simde_mm_stream_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) #define SIMDE_MM_TRANSPOSE4_PS(row0, row1, row2, row3) \ do { \ float32x4x2_t ROW01 = vtrnq_f32(row0, row1); \ float32x4x2_t ROW23 = vtrnq_f32(row2, row3); \ row0 = vcombine_f32(vget_low_f32(ROW01.val[0]), \ vget_low_f32(ROW23.val[0])); \ row1 = vcombine_f32(vget_low_f32(ROW01.val[1]), \ vget_low_f32(ROW23.val[1])); \ row2 = vcombine_f32(vget_high_f32(ROW01.val[0]), \ vget_high_f32(ROW23.val[0])); \ row3 = vcombine_f32(vget_high_f32(ROW01.val[1]), \ vget_high_f32(ROW23.val[1])); \ } while (0) #else #define SIMDE_MM_TRANSPOSE4_PS(row0, row1, row2, row3) \ do { \ simde__m128 tmp3, tmp2, tmp1, tmp0; \ tmp0 = simde_mm_unpacklo_ps((row0), (row1)); \ tmp2 = simde_mm_unpacklo_ps((row2), (row3)); \ tmp1 = simde_mm_unpackhi_ps((row0), (row1)); \ tmp3 = simde_mm_unpackhi_ps((row2), (row3)); \ row0 = simde_mm_movelh_ps(tmp0, tmp2); \ row1 = simde_mm_movehl_ps(tmp2, tmp0); \ row2 = simde_mm_movelh_ps(tmp1, tmp3); \ row3 = simde_mm_movehl_ps(tmp3, tmp1); \ } while (0) #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _MM_TRANSPOSE4_PS(row0, row1, row2, row3) SIMDE_MM_TRANSPOSE4_PS(row0, row1, row2, row3) #endif SIMDE_END_DECLS_ HEDLEY_DIAGNOSTIC_POP #endif /* !defined(SIMDE_X86_SSE_H) */
helloworld.c
#include <stdio.h> #include <omp.h> int main(void) { int isHost = 1; #pragma omp target map(tofrom: isHost) { isHost = omp_is_initial_device(); printf("Hello world. %d\n", 100); for (int i =0; i<5; i++) { printf("Hello world. iteration %d\n", i); } } printf("Target region executed on the %s\n", isHost ? "host" : "device"); return isHost; }
ccode_c.c
// ----------------------------------------------------------------------- // Copyright 2019 Centrum Wiskunde & Informatica, Amsterdam // Author: Daniel M. Pelt // Contact: D.M.Pelt@cwi.nl // Website: http://dmpelt.github.io/foam_ct_phantom/ // License: MIT // This file is part of foam_ct_phantom, a Python package for generating // foam-like phantoms for CT. // ----------------------------------------------------------------------- #define _USE_MATH_DEFINES #include <math.h> #include <omp.h> #include <stdlib.h> #include <stdio.h> #include <limits.h> #ifdef _MSC_VER #define DECLDIR __declspec(dllexport) #else #define DECLDIR #endif #ifndef __MTWISTER_H #define __MTWISTER_H #define STATE_VECTOR_LENGTH 624 #define STATE_VECTOR_M 397 /* changes to STATE_VECTOR_LENGTH also require changes to this */ typedef struct tagMTRand { unsigned long mt[STATE_VECTOR_LENGTH]; int index; } MTRand; MTRand seedRand(unsigned long seed); unsigned long genRandLong(MTRand* rand); float genRand(MTRand* rand); void m_seedRand(MTRand* rand, unsigned long seed); #endif /* #ifndef __MTWISTER_H */ // OpenMP set number of threads DECLDIR void set_threads(const unsigned int nthrd){ omp_set_num_threads(nthrd); } MTRand randgen; DECLDIR void setseed(const unsigned int seed){ m_seedRand(&randgen, seed); } DECLDIR void drawnewpositions(float * const pos3, float * const ds, const unsigned int ntrials, const float zrange){ for(unsigned int i=0; i<ntrials; i++){ float x,y,z; while(1){ x = 2*genRand(&randgen)-1; y = 2*genRand(&randgen)-1; if(x*x + y*y<=1){ z = zrange*(2*genRand(&randgen)-1); break; } } pos3[3*i] = x; pos3[3*i+1] = y; pos3[3*i+2] = z; ds[i] = sqrtf(x*x + y*y)-1; } } int cmpfunc (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } DECLDIR unsigned int newsphere(float * const pos3, float * const ds, const float * const spheres, const unsigned int ntrials, const unsigned int nspheres, const float zrange, unsigned int * const updated, int * const tobeplaced){ const float nx = spheres[(nspheres-1)*5]; const float ny = spheres[(nspheres-1)*5+1]; const float nz = spheres[(nspheres-1)*5+2]; const float nsz = spheres[(nspheres-1)*5+3]; unsigned int nupdated = 0; unsigned int ntobeplaced = 0; int i; #pragma omp parallel for shared(nupdated, ntobeplaced) private(i) for(i=0; i<ntrials; i++){ float x = pos3[3*i]; float y = pos3[3*i+1]; float z = pos3[3*i+2]; float dsv = sqrtf((nx-x)*(nx-x) + (ny-y)*(ny-y) + (nz-z)*(nz-z)) - nsz; if(dsv<0){ #pragma omp critical (tobe) { tobeplaced[ntobeplaced] = i; ntobeplaced++; } }else{ if(dsv<-ds[i]){ ds[i] = -dsv; #pragma omp critical (upd) { updated[nupdated] = i; nupdated++; } } } } qsort(tobeplaced, ntobeplaced, sizeof(int), cmpfunc); float dsv, x, y, z; char cont = 1; for(i=0;i<ntobeplaced;i++){ do{ x = 2*genRand(&randgen)-1; y = 2*genRand(&randgen)-1; dsv = 1 - sqrtf(x*x + y*y); if(dsv<0){ continue; } z = zrange*(2*genRand(&randgen)-1); int j; char abort=0; #pragma omp parallel for private(j) firstprivate(abort) shared(dsv) for(j=0; j<nspheres; j++){ if(!abort){ const float dsn = sqrtf((spheres[5*j]-x)*(spheres[5*j]-x) + (spheres[5*j+1]-y)*(spheres[5*j+1]-y) + (spheres[5*j+2]-z)*(spheres[5*j+2]-z)) - spheres[5*j+3]; if(dsn<dsv){ #pragma omp critical { if(dsn<dsv) dsv = dsn; } } if (dsv<0) abort=1; } } }while(dsv<0); int k = tobeplaced[i]; pos3[3*k] = x; pos3[3*k+1] = y; pos3[3*k+2] = z; ds[k] = -dsv; updated[nupdated] = k; nupdated++; } return nupdated; } DECLDIR void genvol(const float * const spheres, const unsigned int nspheres, float * const vol, const unsigned int * const n, const float voxsize, const float * const c, const unsigned int supersampling, const unsigned int iz){ const unsigned int ninslc = n[0]*n[1]; int i; #pragma omp parallel for private(i) for(i=0; i<ninslc; i++){ vol[iz*ninslc+i] = 0; } for(unsigned int sz=0; sz<supersampling; sz++){ #pragma omp parallel { unsigned int * const temp = (unsigned int *) malloc(nspheres*sizeof(unsigned int)); long double * const dzs = (long double *) malloc(nspheres*sizeof(long double)); long double * const s2s = (long double *) malloc(nspheres*sizeof(long double)); for(unsigned int j=0; j<nspheres; j++){ s2s[j] = spheres[5*j+3]*spheres[5*j+3]; } long double z = c[2] + (iz+0.5)*voxsize - n[2]*voxsize/2 + sz*voxsize/supersampling - voxsize/2 + voxsize/(2*supersampling); unsigned int ntocheck=0; for(unsigned int j=0; j<nspheres; j++){ dzs[j] = (z-spheres[5*j+2])*(z-spheres[5*j+2]); if(dzs[j]<s2s[j]){ temp[ntocheck] = j; ntocheck++; } } #pragma omp for schedule(dynamic) private(i) for(i=0; i<ninslc; i++){ const unsigned int iy = i/n[0]; const unsigned int ix = i%n[0]; for(unsigned int sx=0; sx<supersampling; sx++){ const long double x = c[0] + (ix+0.5)*voxsize - n[0]*voxsize/2 + sx*voxsize/supersampling - voxsize/2 + voxsize/(2*supersampling); for(unsigned int sy=0; sy<supersampling; sy++){ const long double y = c[1] + (iy+0.5)*voxsize - n[1]*voxsize/2 + sy*voxsize/supersampling - voxsize/2 + voxsize/(2*supersampling); if(sqrtl(x*x+y*y)>1){ continue; } unsigned char found=0; long double s2,dx,dy,dz; for(unsigned int q=0; q<ntocheck; q++){ const unsigned int j = temp[q]; dx = (x-spheres[5*j])*(x-spheres[5*j]); if(dx+dzs[j] >= s2s[j]) continue; dy = (y-spheres[5*j+1])*(y-spheres[5*j+1]); if(dx+dy+dzs[j]<s2s[j]){ vol[iz*ninslc+i]+=spheres[5*j+4]; found=1; break; } } if(found==0){ vol[iz*ninslc+i]+=1; } } } } free(dzs); free(temp); free(s2s); } } #pragma omp parallel for private(i) for(i=0; i<ninslc; i++){ vol[iz*ninslc+i]/=supersampling*supersampling*supersampling; } } DECLDIR void genparproj(const float * const spheres, const unsigned int nspheres, float * const proj, const unsigned int * const n, const float pixsize, const float * const c, const float angle, const float * const rotc){ const unsigned int ntotal = n[0]*n[1]; const long double ca = cosl(angle); const long double sa = sinl(angle); int i; #pragma omp parallel for private(i) for(i=0; i<ntotal; i++){ const unsigned int ix = i % n[0]; const long double x = c[0] + (ix+0.5)*pixsize - n[0]*pixsize/2; const long double px = rotc[0] * ca + rotc[1] * sa; const long double dx = (x-px)*(x-px); if(dx>=1){ proj[i]=0; }else{ proj[i] = 2*sqrtl(1 - dx); } } const unsigned int nthr = omp_get_max_threads(); long double * const temp = (long double *) calloc(nthr*ntotal,sizeof(long double)); #pragma omp parallel { const unsigned int tidx = ntotal*omp_get_thread_num(); #pragma omp for schedule(dynamic) private(i) for(i=0; i<nspheres; i++){ const long double s2 = spheres[5*i+3]*spheres[5*i+3]; const long double py = spheres[5*i+2]; const long double px = (rotc[0] + spheres[5*i]) * ca + (rotc[1] + spheres[5*i+1]) * sa; const long double pyi = (py - c[1])/pixsize + 0.5*(n[1]-1); const long double pxi = (px - c[0])/pixsize + 0.5*(n[0]-1); const unsigned int sz = spheres[5*i+3]/pixsize + 1; int l = pxi-sz; int r = pxi+sz; int u = pyi-sz; int d = pyi+sz; if(l<0) l=0; if(r>=n[0]) r=n[0]-1; if(u<0) u=0; if(d>=n[1]) d=n[1]-1; for(unsigned int j=u; j<=d;j++){ const long double y = c[1] + (j+0.5)*pixsize - n[1]*pixsize/2; const long double dy = (y-spheres[5*i+2])*(y-spheres[5*i+2]); if(dy >= s2) continue; for(unsigned int k=l; k<=r; k++){ const long double x = c[0] + (k+0.5)*pixsize - n[0]*pixsize/2; const long double dx = (x-px)*(x-px); if(dx+dy<s2){ temp[tidx+j*n[0]+k] -= 2*(1-spheres[5*i+4])*sqrtl(s2 - dx - dy); } } } } } #pragma omp parallel for private(i) for(i=0; i<ntotal; i++){ long double tmpf = 0; for(unsigned int j=0;j<nthr;j++){ tmpf += temp[j*ntotal + i]; } proj[i] += tmpf; } free(temp); } DECLDIR void gen3dproj(const float * const spheres, const unsigned int nspheres, float * const proj, const unsigned int * const n, const float pixsize, const float maxz, const float * const rot, const unsigned int cutout, const float cutoff){ const unsigned int ntotal = n[0]*n[1]; int i; const unsigned int nthr = omp_get_max_threads(); long double * const temp = (long double *) calloc(nthr*ntotal,sizeof(long double)); long double * const mint = (long double *) malloc(nthr*ntotal*sizeof(long double)); #pragma omp parallel for private(i) for(i=0;i<nthr*ntotal;i++){ mint[i] = INFINITY; } #pragma omp parallel { const unsigned int tidx = ntotal*omp_get_thread_num(); #pragma omp for schedule(dynamic) private(i) for(i=0; i<nspheres; i++){ if(spheres[5*i+4]<cutoff) continue; const long double s2 = spheres[5*i+3]*spheres[5*i+3]; const long double px = spheres[5*i]; const long double pz = spheres[5*i+1]; const long double py = spheres[5*i+2]; const long double pyi = py/pixsize + 0.5*(n[1]-1); const long double pxi = px/pixsize + 0.5*(n[0]-1); const unsigned int sz = spheres[5*i+3]/pixsize + 1; int l = pxi-sz; int r = pxi+sz; int u = pyi-sz; int d = pyi+sz; if(l<0) l=0; if(r>=n[0]) r=n[0]-1; if(u<0) u=0; if(d>=n[1]) d=n[1]-1; for(unsigned int j=u; j<=d;j++){ const long double y = (j+0.5)*pixsize - n[1]*pixsize/2; const long double dy = (y-spheres[5*i+2])*(y-spheres[5*i+2]); if(dy >= s2) continue; for(unsigned int k=l; k<=r; k++){ const long double x = (k+0.5)*pixsize - n[0]*pixsize/2; const long double dx = (x-px)*(x-px); if(dx+dy<s2){ long double t = pz - sqrtl(s2 - dx - dy); long double rx = rot[0]*x + rot[1]*t + rot[2]*y; long double ry = rot[3]*x + rot[4]*t + rot[5]*y; long double rz = rot[6]*x + rot[7]*t + rot[8]*y; long double fac = 1; char reject = fabsl(rz)>maxz; if(!reject && cutout>0){ reject = rx<0 && ry<0 && rz<0; } if (reject){ fac = 0.75; t = pz + sqrtl(s2 - dx - dy); rx = rot[0]*x + rot[1]*t + rot[2]*y; ry = rot[3]*x + rot[4]*t + rot[5]*y; rz = rot[6]*x + rot[7]*t + rot[8]*y; reject = fabsl(rz)>maxz; if(!reject && cutout>0){ reject = rx<0 && ry<0 && rz<0; } if (reject){ continue; } } if(t < mint[tidx+j*n[0]+k]){ mint[tidx+j*n[0]+k] = t; temp[tidx+j*n[0]+k] = fac*sqrtl(s2 - dx - dy)/spheres[5*i+3]; } } } } } } #pragma omp parallel for private(i) for(i=0; i<ntotal; i++){ long double tmpf = temp[i]; long double cmint = mint[i]; for(unsigned int j=1;j<nthr;j++){ if(mint[j*ntotal + i]<cmint){ cmint = mint[j*ntotal + i]; tmpf = temp[j*ntotal + i]; } } proj[i] = tmpf; } free(temp); free(mint); } DECLDIR void genconeproj(const float * const spheres, const unsigned int nspheres, float * const proj, const unsigned int * const n, const float pixsize, const float zoff, const float sod, const float sdd){ const unsigned int ntotal = n[0]*n[1]; int i; #pragma omp parallel for schedule(dynamic) private(i) for(i=0; i<ntotal; i++){ long double tmp=0; const unsigned int ix = i % n[0]; const unsigned int iy = i / n[0]; const long double x = (ix+0.5)*pixsize - n[0]*pixsize/2; const long double y = (iy+0.5)*pixsize - n[1]*pixsize/2; // https://math.stackexchange.com/questions/2613781/line-cylinder-intersection // long double bxl, bxr, byl, byr, bzl, bzr; const long double x0 = -sod; const long double k = x/sdd; const long double l = y/sdd; const long double df = 1 - (x0*x0 - 1)*k*k; if(df>0){ const long double t1 = -(sqrtl(df)+x0)/(k*k+1); const long double t2 = (sqrtl(df)-x0)/(k*k+1); const long double dx = t2 - t1; const long double dy = k*dx; const long double dz = l*dx; tmp = sqrtl(dx*dx+dy*dy+dz*dz); }else{ proj[i]=0; continue; } const long double sz = sqrtl(1+k*k+l*l); const long double tx = 1/sz; const long double ty = k/sz; const long double tz = l/sz; // https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line for(unsigned int j=0; j<nspheres; j++){ const long double sz = spheres[5*j+2]-zoff; const long double sx = spheres[5*j]; const long double sy = spheres[5*j+1]; const long double s2 = spheres[5*j+3]*spheres[5*j+3]; const long double psz = (x0-sx)*tx - sy*ty - sz*tz; const long double pdx = x0-sx - psz*tx; const long double pdy = -sy - psz*ty; const long double pdz = -sz - psz*tz; const long double dist = pdx*pdx+pdy*pdy+pdz*pdz; if(dist<s2){ tmp -= 2*(1-spheres[5*j+4])*sqrtl(s2 - dist); } } proj[i] = tmp; } } DECLDIR void average2d(const float * const invol, float * const outvol, const unsigned int nx, const unsigned int ny, const unsigned int ss){ const unsigned int npix = nx*ny; int i; #pragma omp parallel for private(i) for(i=0; i<npix; i++){ const unsigned int ix = i % nx; const unsigned int iy = i / nx; long double tmp = 0; for(unsigned int y2=ss*iy;y2<ss*(iy+1);y2++){ for(unsigned int x2=ss*ix;x2<ss*(ix+1);x2++){ tmp += invol[y2*ss*nx + x2]; } } outvol[i] = tmp/(ss*ss); } } DECLDIR unsigned int gettouching(const float * const spheres, const unsigned int nspheres, const unsigned int i, const float cutoff, unsigned int * const indices){ const unsigned int nthr = omp_get_max_threads(); unsigned int * const js = (unsigned int *) malloc(nthr*nspheres*sizeof(unsigned int)); unsigned int * const njs = (unsigned int *) malloc(nthr*sizeof(unsigned int)); for(unsigned int j=0;j<nthr;j++) njs[j]=0; const float x = spheres[5*i]; const float y = spheres[5*i+1]; const float z = spheres[5*i+2]; const float s = spheres[5*i+3]; #pragma omp parallel { unsigned int tid = omp_get_thread_num(); unsigned int nj = 0; int j; #pragma omp for private(j) for(j=0; j<nspheres; j++){ if(i==j) continue; const float dst = sqrtf((spheres[5*j]-x)*(spheres[5*j]-x)+(spheres[5*j+1]-y)*(spheres[5*j+1]-y)+(spheres[5*j+2]-z)*(spheres[5*j+2]-z)) - spheres[5*j+3] - s; if(dst<cutoff){ js[tid*nspheres + nj] = j; nj++; } } njs[tid] = nj; } unsigned int nindices = 0; for(unsigned int j=0; j<nthr; j++){ for(unsigned int k=0; k<njs[j]; k++){ indices[nindices] = js[j*nspheres + k]; nindices++; } } free(js); free(njs); return nindices; } // Adapted from https://www.johndcook.com/blog/cpp_random_number_generation/ unsigned int poissonsmall(const float lambda){ float p = 1.0; const float L = expf(-lambda); unsigned int k = 0; do { k++; p *= genRand(&randgen); } while (p > L); return k - 1; } unsigned int poissonlarge(const float lambda){ // "Rejection method PA" from "The Computer Generation of Poisson Random Variables" by A. C. Atkinson // Journal of the Royal Statistical Society Series C (Applied Statistics) Vol. 28, No. 1. (1979) // The article is on pages 29-35. The algorithm given here is on page 32. float c = 0.767 - 3.36/lambda; float beta = M_PI/sqrtf(3.0*lambda); float alpha = beta*lambda; float k = logf(c) - lambda - logf(beta); for(;;) { float u = genRand(&randgen); float x = (alpha - logf((1.0 - u)/u))/beta; int n = (int) floor(x + 0.5); if (n < 0) continue; float v = genRand(&randgen); float y = alpha - beta*x; float temp = 1.0 + expf(y); float lhs = y + logf(v/(temp*temp)); float rhs = k + n*logf(lambda) - lgammaf(n+1); if (lhs <= rhs) return n; } } float poisson(const float lambda){ return (lambda < 30.0) ? poissonsmall(lambda) : poissonlarge(lambda); } DECLDIR void applypoisson(float * const proj, const unsigned int npix, const float flux, const float factor){ int i; #pragma omp parallel for private(i) for(i=0; i<npix; i++){ float tmp = poisson(flux*expf(-proj[i]*factor)); if(tmp<=0) tmp = 1; proj[i] = -logf(tmp/flux)/factor; } } /* An implementation of the MT19937 Algorithm for the Mersenne Twister * by Evan Sultanik. Based upon the pseudocode in: M. Matsumoto and * T. Nishimura, "Mersenne Twister: A 623-dimensionally * equidistributed uniform pseudorandom number generator," ACM * Transactions on Modeling and Computer Simulation Vol. 8, No. 1, * January pp.3-30 1998. * * http://www.sultanik.com/Mersenne_twister */ #define UPPER_MASK 0x80000000 #define LOWER_MASK 0x7fffffff #define TEMPERING_MASK_B 0x9d2c5680 #define TEMPERING_MASK_C 0xefc60000 inline void m_seedRand(MTRand* rand, unsigned long seed) { /* set initial seeds to mt[STATE_VECTOR_LENGTH] using the generator * from Line 25 of Table 1 in: Donald Knuth, "The Art of Computer * Programming," Vol. 2 (2nd Ed.) pp.102. */ rand->mt[0] = seed & 0xffffffff; for(rand->index=1; rand->index<STATE_VECTOR_LENGTH; rand->index++) { rand->mt[rand->index] = (6069 * rand->mt[rand->index-1]) & 0xffffffff; } } /** * Creates a new random number generator from a given seed. */ MTRand seedRand(unsigned long seed) { MTRand rand; m_seedRand(&rand, seed); return rand; } /** * Generates a pseudo-randomly generated long. */ unsigned long genRandLong(MTRand* rand) { unsigned long y; static unsigned long mag[2] = {0x0, 0x9908b0df}; /* mag[x] = x * 0x9908b0df for x = 0,1 */ if(rand->index >= STATE_VECTOR_LENGTH || rand->index < 0) { /* generate STATE_VECTOR_LENGTH words at a time */ int kk; if(rand->index >= STATE_VECTOR_LENGTH+1 || rand->index < 0) { m_seedRand(rand, 4357); } for(kk=0; kk<STATE_VECTOR_LENGTH-STATE_VECTOR_M; kk++) { y = (rand->mt[kk] & UPPER_MASK) | (rand->mt[kk+1] & LOWER_MASK); rand->mt[kk] = rand->mt[kk+STATE_VECTOR_M] ^ (y >> 1) ^ mag[y & 0x1]; } for(; kk<STATE_VECTOR_LENGTH-1; kk++) { y = (rand->mt[kk] & UPPER_MASK) | (rand->mt[kk+1] & LOWER_MASK); rand->mt[kk] = rand->mt[kk+(STATE_VECTOR_M-STATE_VECTOR_LENGTH)] ^ (y >> 1) ^ mag[y & 0x1]; } y = (rand->mt[STATE_VECTOR_LENGTH-1] & UPPER_MASK) | (rand->mt[0] & LOWER_MASK); rand->mt[STATE_VECTOR_LENGTH-1] = rand->mt[STATE_VECTOR_M-1] ^ (y >> 1) ^ mag[y & 0x1]; rand->index = 0; } y = rand->mt[rand->index++]; y ^= (y >> 11); y ^= (y << 7) & TEMPERING_MASK_B; y ^= (y << 15) & TEMPERING_MASK_C; y ^= (y >> 18); return y; } /** * Generates a pseudo-randomly generated double in the range [0..1]. */ float genRand(MTRand* rand) { return((float)genRandLong(rand) / (unsigned long)0xffffffff); } /** * Skip list implementation * Follows http://www.mathcs.emory.edu/~cheung/Courses/323/Syllabus/Map/skip-list-impl.html */ struct sknode { float val; unsigned int idx; struct sknode * left; struct sknode * right; struct sknode * up; struct sknode * down; }; void init_sknode(struct sknode * c){ c->right = NULL; c->left = NULL; c->up = NULL; c->down = NULL; } struct sknode * skhead = NULL; struct sknode * sktail = NULL; unsigned int skh = 1; unsigned int nskpool = 0; struct sknode * skpool = NULL; void clear_skiplist(){ struct sknode * cur; struct sknode * next; if (skpool) { for (unsigned int i=0; i<nskpool; i++){ cur = skpool[i].up; while (cur){ next = cur->up; free(cur); cur = next; } } free(skpool); skpool = NULL; } if (skhead) { cur = skhead; while (cur){ next = cur->down; free(cur); cur = next; } skhead = NULL; } if (sktail) { cur = sktail; while (cur){ next = cur->down; free(cur); cur = next; } sktail = NULL; } } MTRand skrand; struct sksort { unsigned int idx; float val; }; int skcompare(const void *a, const void *b){ struct sksort *aa = (struct sksort *)a; struct sksort *bb = (struct sksort *)b; return (aa->val > bb->val) - (aa->val < bb->val); } void insert_node_to_skiplist(struct sknode * node, struct sknode * prev){ while (1){ struct sknode * right = prev->right; prev->right = node; node->left = prev; node->right = right; right->left = node; if (genRand(&skrand)>0.5){ struct sknode * newnode = (struct sknode *) malloc(sizeof(struct sknode)); init_sknode(newnode); newnode->val = node->val; newnode->idx = node->idx; newnode->down = node; node->up = newnode; node = newnode; while(prev->up == NULL){ if (prev->left){ prev = prev->left; }else{ struct sknode * newhead = (struct sknode *) malloc(sizeof(struct sknode)); init_sknode(newhead); newhead->val = -INFINITY; newhead->down = skhead; skhead->up = newhead; skhead = newhead; struct sknode * newtail = (struct sknode *) malloc(sizeof(struct sknode)); init_sknode(newtail); newtail->val = INFINITY; newtail->down = sktail; sktail->up = newtail; sktail = newtail; skhead->right = sktail; sktail->left = skhead; break; } } prev = prev->up; }else{ break; } } } void add_idx_to_skiplist(const unsigned int * const idx, const unsigned int nidx){ struct sksort * sortlist = (struct sksort *) malloc(nidx * sizeof(struct sksort)); for (unsigned int i=0; i<nidx; i++){ sortlist[i].idx = idx[i]; sortlist[i].val = skpool[idx[i]].val; } qsort (sortlist, nidx, sizeof(struct sksort), skcompare); struct sknode * cur = skhead; unsigned char up_possible = 0; for (unsigned int i=0; i<nidx; i++){ float cv = sortlist[i].val; while (1){ while (cur->right->val < cv){ if (up_possible && cur->up){ cur = cur->up; }else{ cur = cur->right; } } up_possible = 0; if (cur->down){ cur = cur->down; }else{ break; } } insert_node_to_skiplist(skpool + sortlist[i].idx, cur); up_possible=1; } free(sortlist); } void remove_idx_from_skiplist(const unsigned int * const idx, const unsigned int nidx){ struct sknode * cur; struct sknode * next; for (unsigned int i=0; i<nidx; i++){ cur = skpool + idx[i]; cur->left->right = cur->right; cur->right->left = cur->left; cur = cur->up; if (cur) cur->down->up = NULL; while(cur){ cur->left->right = cur->right; cur->right->left = cur->left; next = cur->up; free(cur); cur = next; } } } DECLDIR void update_skiplist(const float * const sizes, const unsigned int * const idx, const unsigned int nidx){ remove_idx_from_skiplist(idx, nidx); for (unsigned int i=0; i<nidx; i++){ skpool[idx[i]].val = sizes[idx[i]]; } add_idx_to_skiplist(idx, nidx); } struct sknode * skiplist_iter; DECLDIR void reset_iter_skiplist(){ skiplist_iter = skhead; while(skiplist_iter->down){ skiplist_iter = skiplist_iter->down; } skiplist_iter = skiplist_iter->right; } DECLDIR int iter_skiplist(){ if (skiplist_iter->right){ skiplist_iter = skiplist_iter->right; return skiplist_iter->left->idx; }else{ return -1; } } DECLDIR void check_skiplist(){ float cur = -INFINITY; reset_iter_skiplist(); int idx = iter_skiplist(); while(idx!=-1){ if (skpool[idx].val<cur){ printf("SKIPLIST ERROR! %f < %f\n", skpool[idx].val, cur); } idx = iter_skiplist(); } } DECLDIR void init_skiplist(float * sizes, unsigned int ns){ clear_skiplist(); m_seedRand(&skrand, 12345); skhead = (struct sknode * ) malloc(sizeof(struct sknode)); init_sknode(skhead); skhead->val = -INFINITY; sktail = (struct sknode * ) malloc(sizeof(struct sknode)); init_sknode(sktail); sktail->val = INFINITY; skhead->right = sktail; sktail->left = skhead; skpool = (struct sknode * ) malloc(ns*sizeof(struct sknode)); nskpool = ns; for (unsigned int i=0; i<ns; i++){ skpool[i].idx = i; skpool[i].val = sizes[i]; init_sknode(skpool + i); } unsigned int *idx = (unsigned int *) malloc(ns*sizeof(unsigned int)); for (unsigned int i=0; i<ns ; i++){ idx[i] = i; } add_idx_to_skiplist(idx, ns); free(idx); }
hello.c
#include <stdio.h> #if defined (_OPENMP) #include <omp.h> #endif int main(int argc, char *argv[]) { int myrank=0; int mysize=1; #if defined (_OPENMP) #pragma omp parallel default(shared) private(myrank, mysize) { mysize = omp_get_num_threads(); myrank = omp_get_thread_num(); #endif printf("Hello from thread %d out of %d\n", myrank, mysize); #if defined (_OPENMP) } #endif return 0; }
papi_perf.h
#ifndef __PAPI_PERF_H__ #define __PAPI_PERF_H__ #include <mpi.h> #include <cassert> #include <pthread.h> //Only on systems with PAPI installed #ifdef PAPI #include <papi.h> #include <omp.h> #include <cstdio> #endif void init_papi() { #ifdef PAPI //Must call before PAPI_thread_init int retval = PAPI_library_init(PAPI_VER_CURRENT); if (retval != PAPI_VER_CURRENT){ printf("%s:%d::PAPI_library_init failed. %d\n", __FILE__,__LINE__,retval); exit(1); } //Set up multi-threading in PAPI. Call this only once. retval = PAPI_thread_init( (unsigned long (*)(void))(pthread_self) ); #endif } int papi_thread_flops( float *rtime, float *ptime, long long *flpops, float *mflops_total ) { #ifdef PAPI int maxt = omp_get_max_threads(); float real_time[maxt], proc_time[maxt], mflops[maxt]; long long flpins[maxt]; int retval = PAPI_OK; retval = PAPI_flops(&(real_time[maxt]), &(proc_time[maxt]), &(flpins[maxt]), &(mflops[maxt])); #pragma omp parallel { int retval; int t = omp_get_thread_num(); /* Collect the data into the variables passed in */ retval = PAPI_flops(&(real_time[t]), &(proc_time[t]), &(flpins[t]), &(mflops[t])); } int t; *flpops = 0; *mflops_total = 0.0; *rtime = 0.0; *ptime = 0.0; //Combine all threads' results. for(t = 0; t < maxt+1; t++) { //Use the maximum time, but they should be practically equal. if(real_time[t] > *rtime) *rtime = real_time[t]; if(proc_time[t] > *ptime) *ptime = proc_time[t]; *flpops += flpins[t]; //Overall MFLOPS/s is approximately the sum (assuming all threads have the same proc_time). *mflops_total += mflops[t]; } return retval; #else return -1; #endif } void papi_mpi_flop_start() { float global_real_time=0.0, global_proc_time=0.0, global_mflops=0.0; long long global_flpins = 0; #ifdef PAPI MPI_Barrier(MPI_COMM_WORLD); int retval; if (papi_thread_flops( &global_real_time, &global_proc_time, &global_flpins, &global_mflops) < PAPI_OK) { fprintf(stderr, "%s:%d ", __FILE__, __LINE__); fprintf(stderr, "PAPI_flips failed with return value = %d\n", retval); exit(1); } #endif } float papi_mpi_flop_stop() { float global_real_time=0.0, global_proc_time=0.0, global_mflops=0.0; long long global_flpins = 0; float total_global_mflops = -1.0; MPI_Barrier(MPI_COMM_WORLD); #ifdef PAPI int retval; if (papi_thread_flops( &global_real_time, &global_proc_time, &global_flpins, &global_mflops) < PAPI_OK) { fprintf(stderr, "%s:%d ", __FILE__, __LINE__); fprintf(stderr, "PAPI_flips failed with return value = %d\n", retval); exit(1); } MPI_Allreduce(&global_mflops, &total_global_mflops, 1, MPI_FLOAT, MPI_SUM, MPI_COMM_WORLD); #endif return total_global_mflops; } #endif
2mm.c
/** * 2mm.c: This file was adapted from PolyBench/GPU 1.0 test suite * to run on GPU with OpenMP 4.0 pragmas and OpenCL driver. * * http://www.cse.ohio-state.edu/~pouchet/software/polybench/GPU * * Contacts: Marcio M Pereira <mpereira@ic.unicamp.br> * Rafael Cardoso F Sousa <rafael.cardoso@students.ic.unicamp.br> * Luís Felipe Mattos <ra107822@students.ic.unicamp.br> */ #include <assert.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <unistd.h> #ifdef _OPENMP #include <omp.h> #endif #include "BenchmarksUtil.h" #define BENCHMARK_NAME "2MM" // define the error threshold for the results "not matching" #define ERROR_THRESHOLD 0.05 /* Problem size. */ #ifdef RUN_POLYBENCH_SIZE #define SIZE 2048 #elif RUN_TEST #define SIZE 1100 #elif RUN_BENCHMARK #define SIZE 9600 #else #define SIZE 1000 #endif #define NI SIZE #define NJ SIZE #define NK SIZE #define NL SIZE /* Can switch DATA_TYPE between float and double */ typedef float DATA_TYPE; void init_array(DATA_TYPE *A, DATA_TYPE *B, DATA_TYPE *C, DATA_TYPE *D) { int i, j; for (i = 0; i < NI; i++) { for (j = 0; j < NK; j++) { A[i * NI + j] = ((DATA_TYPE)i * j) / NI; } } for (i = 0; i < NK; i++) { for (j = 0; j < NJ; j++) { B[i * NK + j] = ((DATA_TYPE)i * (j + 1)) / NJ; } } for (i = 0; i < NL; i++) { for (j = 0; j < NJ; j++) { // C[i*NL + j] = ((DATA_TYPE) i*(j+3)) / NL; } } for (i = 0; i < NI; i++) { for (j = 0; j < NL; j++) { D[i * NL + j] = ((DATA_TYPE)i * (j + 2)) / NK; } } } int compareResults(DATA_TYPE *E, DATA_TYPE *E_GPU) { int i, j, fail; fail = 0; for (i = 0; i < NL; i++) { for (j = 0; j < NI; j++) { if (percentDiff(E[i * NI + j], E_GPU[i * NI + j]) > ERROR_THRESHOLD) { fail++; } } } // print results printf("Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f " "Percent: %d\n", ERROR_THRESHOLD, fail); return fail; } void mm2_cpu(DATA_TYPE *A, DATA_TYPE *B, DATA_TYPE *C, DATA_TYPE *D, DATA_TYPE *E) { int i, j, k; for (i = 0; i < NI; i++) { for (j = 0; j < NJ; j++) { C[i * NJ + j] = 0.0; for (k = 0; k < NK; ++k) { C[i * NJ + j] += A[i * NK + k] * B[k * NJ + j]; } } } for (i = 0; i < NI; i++) { for (j = 0; j < NL; j++) { E[i * NL + j] = 0.0; for (k = 0; k < NJ; ++k) { E[i * NL + j] += C[i * NJ + k] * D[k * NL + j]; } } } } void mm2_OMP(DATA_TYPE *A, DATA_TYPE *B, DATA_TYPE *C, DATA_TYPE *D, DATA_TYPE *E) { #pragma omp target teams map(from: E[:NI*NL], C[:NI*NJ]) map(to: A[:NI*NK], B[:NK*NJ], D[:NJ*NL]) device(DEVICE_ID) { #pragma omp distribute parallel for collapse(2) for (int i = 0; i < NI; i++) { for (int j = 0; j < NJ; j++) { C[i * NJ + j] = 0.0; for (int k = 0; k < NK; ++k) { C[i * NJ + j] += A[i * NK + k] * B[k * NJ + j]; } } } #pragma omp distribute parallel for collapse(2) for (int i = 0; i < NI; i++) { for (int j = 0; j < NL; j++) { E[i * NL + j] = 0.0; for (int k = 0; k < NJ; ++k) { E[i * NL + j] += C[i * NJ + k] * D[k * NL + j]; } } } } } int main(int argc, char **argv) { double t_start, t_end, t_start_GPU, t_end_GPU; int fail = 0; DATA_TYPE *C; DATA_TYPE *C_GPU; DATA_TYPE *A; DATA_TYPE *B; DATA_TYPE *D; DATA_TYPE *E; DATA_TYPE *E_GPU; C = (DATA_TYPE *)calloc(NI * NJ, sizeof(DATA_TYPE)); C_GPU = (DATA_TYPE *)calloc(NI * NJ, sizeof(DATA_TYPE)); A = (DATA_TYPE *)malloc(NI * NK * sizeof(DATA_TYPE)); B = (DATA_TYPE *)malloc(NK * NJ * sizeof(DATA_TYPE)); D = (DATA_TYPE *)malloc(NJ * NL * sizeof(DATA_TYPE)); E = (DATA_TYPE *)calloc(NI * NL, sizeof(DATA_TYPE)); E_GPU = (DATA_TYPE *)calloc(NI * NL, sizeof(DATA_TYPE)); /*fprintf( stdout, "<< Linear Algebra: 2 Matrix Multiplications (D=A.B; E=C.D) size: %d>>\n", SIZE);*/ printBenchmarkInfo(BENCHMARK_NAME, SIZE); init_array(A, B, C, D); t_start_GPU = rtclock(); mm2_OMP(A, B, C_GPU, D, E_GPU); t_end_GPU = rtclock(); fprintf(stdout, "GPU Runtime: %0.6lfs\n", t_end_GPU - t_start_GPU); #ifdef RUN_TEST t_start = rtclock(); mm2_cpu(A, B, C, D, E); t_end = rtclock(); fprintf(stdout, "CPU Runtime: %0.6lfs\n", t_end - t_start); fail += compareResults(C, C_GPU); fail += compareResults(E, E_GPU); #endif free(C); free(A); free(B); free(D); free(E); free(E_GPU); return fail; }
coloring_barenboim.h
#ifndef COLORING_BARENBOIM_H_ #define COLORING_BARENBOIM_H_ #include "coloring_common_barenboim_elkin.h" namespace GMS::Coloring { template <class CGraph> std::size_t one_shot_coloring(const CGraph &g, const VN &nodes_to_color, VC &coloring, VVC &palettes, VRS selectors, VC &chosen_color, VC &new_color, std::size_t n_colored) { std::size_t n = g.num_nodes(); // select a color #pragma omp parallel for schedule(dynamic, 16) for (std::size_t i = 0; i < nodes_to_color.size(); i++) { NodeId v = nodes_to_color[i]; if (coloring[v] != 0) { continue; } auto selector = selectors[omp_get_thread_num()]; chosen_color[v] = selector(palettes[v]); } // check if we can keep color int32_t n_newly_colored = 0; #pragma omp parallel for schedule(dynamic, 16) reduction(+ : n_newly_colored) for (std::size_t i = 0; i < nodes_to_color.size(); i++) { NodeId v = nodes_to_color[i]; if (coloring[v] != 0) { continue; } bool keep_color = true; // NodeId last_u = n; for (auto it = g.out_neigh(v).end() - 1; it != g.out_neigh(v).begin() - 1; it--) { NodeId u = *it; // for (NodeId u : std::make_reverse_iterator(g.out_neigh(v))) {} // assert(u < last_u && "u decreases strictly"); // last_u = u; // g.out_neigh(v) is sorted, so we can return early if (v >= u) { break; } // in a conflict, only keep the color if v has the higher ID if (v < u && chosen_color[v] == chosen_color[u]) { keep_color = false; break; } } if (keep_color) { coloring[v] = chosen_color[v]; new_color[v] = chosen_color[v]; n_newly_colored++; } } n_colored += n_newly_colored; // update palette #pragma omp parallel for schedule(dynamic, 16) for (std::size_t i = 0; i < nodes_to_color.size(); i++) { NodeId v = nodes_to_color[i]; if (coloring[v] != 0) { continue; } for (NodeId u : g.out_neigh(v)) { if (new_color[u] != 0) { remove_sorted(palettes[v], new_color[u]); } } } // set new_color and chosen_color to 0 after a vertex is colored #pragma omp parallel for schedule(dynamic, 16) for (std::size_t i = 0; i < nodes_to_color.size(); i++) { NodeId v = nodes_to_color[i]; if (chosen_color[v] != 0) { chosen_color[v] = 0; } if (new_color[v] != 0) { new_color[v] = 0; } } update_palettes(g, coloring, palettes); return n_colored; } template <class CGraph> int coloring_barenboim(const CGraph &g, VC &coloring, VN &g_nodes, std::size_t n_colored) { VRS selectors(omp_get_max_threads()); for (std::size_t i = 0; i < selectors.size(); i++) { selectors[i] = random_selector<>(); } std::size_t n = g.num_nodes(); VC chosen_color(n, 0); VC new_color(n, 0); ColorID delta = get_delta(g); VVC palettes = std::move(create_delta_plus_one_palettes(g, coloring, n, delta)); update_palettes(g, coloring, palettes); std::size_t iterations = std::ceil(std::log(delta) / std::log((double)16 / 15)); for (std::size_t i = 0; i < iterations && n_colored != n; i++) { n_colored = one_shot_coloring(g, g_nodes, coloring, palettes, selectors, chosen_color, new_color, n_colored); } if (n_colored == n) { return 0; } VN g_uncolored = std::move(get_uncolored(g_nodes, coloring)); const int32_t c = 1; // TODO const int32_t delta_hat = c * std::log(n); VN g_hi_nodes(0); VN g_lo_nodes(0); #pragma omp parallel { VN g_hi_local(0); VN g_lo_local(0); #pragma omp for schedule(dynamic, 16) for (std::size_t i = 0; i < g_uncolored.size(); i++) { NodeId v = g_uncolored[i]; int32_t uncolored_deg = 0; for (NodeId u : g.out_neigh(v)) { uncolored_deg += (coloring[u] == 0); } if (uncolored_deg > delta_hat) { g_hi_local.push_back(v); } else { g_lo_local.push_back(v); } } if (g_hi_local.size() > 0) { #pragma omp critical push_back_move_all(g_hi_local, g_hi_nodes); } if (g_lo_local.size() > 0) { #pragma omp critical push_back_move_all(g_lo_local, g_lo_nodes); } } std::sort(g_hi_nodes.begin(), g_hi_nodes.end()); std::sort(g_lo_nodes.begin(), g_lo_nodes.end()); iterations = std::ceil(5 * std::log(delta_hat) / std::log((double)4 / 3)); if (g_hi_nodes.size() > 0) { for (std::size_t i = 0; i < iterations && n_colored < n; i++) { n_colored = one_shot_coloring(g, g_hi_nodes, coloring, palettes, selectors, chosen_color, new_color, n_colored); } } if (g_lo_nodes.size() > 0) { for (std::size_t i = 0; i < iterations && n_colored < n; i++) { n_colored = one_shot_coloring(g, g_lo_nodes, coloring, palettes, selectors, chosen_color, new_color, n_colored); } } g_uncolored = std::move(get_uncolored(g_nodes, coloring)); while (n_colored < n) { n_colored = one_shot_coloring(g, g_uncolored, coloring, palettes, selectors, chosen_color, new_color, n_colored); } return n_colored; } template <class CGraph> int coloring_barenboim_subalgo_interface(const CGraph &g, VC &coloring) { std::size_t n = g.num_nodes(); VN g_uncolored = std::move(get_uncolored(g, coloring)); std::size_t n_colored = n - g_uncolored.size(); return coloring_barenboim(g, coloring, g_uncolored, n_colored); } template <class CGraph> int coloring_barenboim_direct_interface(const CGraph &g, VC &coloring) { std::size_t n = g.num_nodes(); VN g_uncolored = std::move(get_uncolored(g, coloring)); std::size_t n_colored = n - g_uncolored.size(); return coloring_barenboim(g, coloring, g_uncolored, n_colored); } } // namespace GMS::Coloring #endif // COLORING_BARENBOIM_H_
ark_brusselator1D_omp.c
/*--------------------------------------------------------------- * Programmer(s): Daniel R. Reynolds @ SMU *--------------------------------------------------------------- * LLNS/SMU Copyright Start * Copyright (c) 2015, Southern Methodist University and * Lawrence Livermore National Security * * This work was performed under the auspices of the U.S. Department * of Energy by Southern Methodist University and Lawrence Livermore * National Laboratory under Contract DE-AC52-07NA27344. * Produced at Southern Methodist University and the Lawrence * Livermore National Laboratory. * * All rights reserved. * For details, see the LICENSE file. * LLNS/SMU Copyright End *--------------------------------------------------------------- * Example problem: * * The following test simulates a brusselator problem from chemical * kinetics. This is n PDE system with 3 components, Y = [u,v,w], * satisfying the equations, * u_t = du*u_xx + a - (w+1)*u + v*u^2 * v_t = dv*v_xx + w*u - v*u^2 * w_t = dw*w_xx + (b-w)/ep - w*u * for t in [0, 80], x in [0, 1], with initial conditions * u(0,x) = a + 0.1*sin(pi*x) * v(0,x) = b/a + 0.1*sin(pi*x) * w(0,x) = b + 0.1*sin(pi*x), * and with stationary boundary conditions, i.e. * u_t(t,0) = u_t(t,1) = 0, * v_t(t,0) = v_t(t,1) = 0, * w_t(t,0) = w_t(t,1) = 0. * Note: these can also be implemented as Dirichlet boundary * conditions with values identical to the initial conditions. * * The spatial derivatives are computed using second-order * centered differences, with the data distributed over N points * on a uniform spatial grid. * * This program solves the problem with the DIRK method, using a * Newton iteration with the ARKBAND band linear solver, and a * user-supplied Jacobian routine. This example uses the OpenMP * vector kernel, and employs OpenMP threading within the * right-hand side and Jacobian construction functions. * * 100 outputs are printed at equal intervals, and run statistics * are printed at the end. *---------------------------------------------------------------*/ /* Header files */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <arkode/arkode.h> /* prototypes for ARKode fcts., consts. */ #include <nvector/nvector_openmp.h> /* OpenMP N_Vector types, fcts., macros */ #include <arkode/arkode_band.h> /* prototype for ARKBand solver */ #include <sundials/sundials_types.h> /* def. of type 'realtype' */ #ifdef _OPENMP #include <omp.h> /* OpenMP functions */ #endif /* accessor macros between (x,v) location and 1D NVector array */ #define IDX(x,v) (3*(x)+v) /* user data structure */ typedef struct { long int N; /* number of intervals */ int nthreads; /* number of OpenMP threads */ realtype dx; /* mesh spacing */ realtype a; /* constant forcing on u */ realtype b; /* steady-state value of w */ realtype du; /* diffusion coeff for u */ realtype dv; /* diffusion coeff for v */ realtype dw; /* diffusion coeff for w */ realtype ep; /* stiffness parameter */ } *UserData; /* User-supplied Functions Called by the Solver */ static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data); static int Jac(long int N, long int mu, long int ml, realtype t, N_Vector y, N_Vector fy, DlsMat J, void *user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3); /* Private helper functions */ static int LaplaceMatrix(realtype c, DlsMat Jac, UserData udata); static int ReactionJac(realtype c, N_Vector y, DlsMat Jac, UserData udata); /* Private function to check function return values */ static int check_flag(void *flagvalue, char *funcname, int opt); /* Main Program */ int main(int argc, char *argv[]) { /* general problem parameters */ realtype T0 = RCONST(0.0); /* initial time */ realtype Tf = RCONST(10.0); /* final time */ int Nt = 100; /* total number of output times */ int Nvar = 3; /* number of solution fields */ UserData udata = NULL; realtype *data; long int N = 201; /* spatial mesh size */ realtype a = 0.6; /* problem parameters */ realtype b = 2.0; realtype du = 0.025; realtype dv = 0.025; realtype dw = 0.025; realtype ep = 1.0e-5; /* stiffness parameter */ realtype reltol = 1.0e-6; /* tolerances */ realtype abstol = 1.0e-10; long int NEQ, i; /* general problem variables */ int flag; /* reusable error-checking flag */ N_Vector y = NULL; /* empty vector for storing solution */ N_Vector umask = NULL; /* empty mask vectors for viewing solution components */ N_Vector vmask = NULL; N_Vector wmask = NULL; void *arkode_mem = NULL; /* empty ARKode memory structure */ realtype pi, t, dTout, tout, u, v, w; FILE *FID, *UFID, *VFID, *WFID; int iout, num_threads; long int nst, nst_a, nfe, nfi, nsetups, nje, nfeLS, nni, ncfn, netf; /* allocate udata structure */ udata = (UserData) malloc(sizeof(*udata)); if (check_flag((void *) udata, "malloc", 2)) return 1; /* set the number of threads to use */ num_threads = 1; /* default value */ #ifdef _OPENMP num_threads = omp_get_max_threads(); /* overwrite with OMP_NUM_THREADS environment variable */ #endif if (argc > 1) /* overwrite with command line value, if supplied */ num_threads = strtol(argv[1], NULL, 0); /* store the inputs in the UserData structure */ udata->N = N; udata->a = a; udata->b = b; udata->du = du; udata->dv = dv; udata->dw = dw; udata->ep = ep; udata->nthreads = num_threads; /* set total allocated vector length */ NEQ = Nvar*udata->N; /* Initial problem output */ printf("\n1D Brusselator PDE test problem:\n"); printf(" N = %li, NEQ = %li\n", udata->N, NEQ); printf(" num_threads = %i\n", num_threads); printf(" problem parameters: a = %g, b = %g, ep = %g\n", udata->a, udata->b, udata->ep); printf(" diffusion coefficients: du = %g, dv = %g, dw = %g\n", udata->du, udata->dv, udata->dw); printf(" reltol = %.1e, abstol = %.1e\n\n", reltol, abstol); /* Initialize data structures */ y = N_VNew_OpenMP(NEQ, num_threads); /* Create vector for solution */ if (check_flag((void *)y, "N_VNew_OpenMP", 0)) return 1; udata->dx = RCONST(1.0)/(N-1); /* set spatial mesh spacing */ data = N_VGetArrayPointer(y); /* Access data array for new NVector y */ if (check_flag((void *)data, "N_VGetArrayPointer", 0)) return 1; umask = N_VNew_OpenMP(NEQ, num_threads); /* Create vector masks */ if (check_flag((void *)umask, "N_VNew_OpenMP", 0)) return 1; vmask = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)vmask, "N_VNew_OpenMP", 0)) return 1; wmask = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)wmask, "N_VNew_OpenMP", 0)) return 1; /* Set initial conditions into y */ pi = RCONST(4.0)*atan(RCONST(1.0)); for (i=0; i<N; i++) { data[IDX(i,0)] = a + RCONST(0.1)*sin(pi*i*udata->dx); /* u */ data[IDX(i,1)] = b/a + RCONST(0.1)*sin(pi*i*udata->dx); /* v */ data[IDX(i,2)] = b + RCONST(0.1)*sin(pi*i*udata->dx); /* w */ } /* Set mask array values for each solution component */ N_VConst(0.0, umask); data = N_VGetArrayPointer(umask); if (check_flag((void *) data, "N_VGetArrayPointer", 0)) return 1; for (i=0; i<N; i++) data[IDX(i,0)] = RCONST(1.0); N_VConst(0.0, vmask); data = N_VGetArrayPointer(vmask); if (check_flag((void *) data, "N_VGetArrayPointer", 0)) return 1; for (i=0; i<N; i++) data[IDX(i,1)] = RCONST(1.0); N_VConst(0.0, wmask); data = N_VGetArrayPointer(wmask); if (check_flag((void *) data, "N_VGetArrayPointer", 0)) return 1; for (i=0; i<N; i++) data[IDX(i,2)] = RCONST(1.0); /* Create the solver memory */ arkode_mem = ARKodeCreate(); if (check_flag((void *)arkode_mem, "ARKodeCreate", 0)) return 1; /* Call ARKodeInit to initialize the integrator memory and specify the hand-side side function in y'=f(t,y), the inital time T0, and the initial dependent variable vector y. Note: since this problem is fully implicit, we set f_E to NULL and f_I to f. */ flag = ARKodeInit(arkode_mem, NULL, f, T0, y); if (check_flag(&flag, "ARKodeInit", 1)) return 1; /* Set routines */ flag = ARKodeSetUserData(arkode_mem, (void *) udata); /* Pass udata to user functions */ if (check_flag(&flag, "ARKodeSetUserData", 1)) return 1; flag = ARKodeSStolerances(arkode_mem, reltol, abstol); /* Specify tolerances */ if (check_flag(&flag, "ARKodeSStolerances", 1)) return 1; /* Linear solver specification */ flag = ARKBand(arkode_mem, NEQ, 4, 4); /* Specify the band linear solver */ if (check_flag(&flag, "ARKBand", 1)) return 1; flag = ARKDlsSetBandJacFn(arkode_mem, Jac); /* Set the Jacobian routine */ if (check_flag(&flag, "ARKDlsSetBandJacFn", 1)) return 1; /* output spatial mesh to disk */ FID=fopen("bruss_mesh.txt","w"); for (i=0; i<N; i++) fprintf(FID," %.16e\n", udata->dx*i); fclose(FID); /* Open output stream for results, access data arrays */ UFID=fopen("bruss_u.txt","w"); VFID=fopen("bruss_v.txt","w"); WFID=fopen("bruss_w.txt","w"); /* output initial condition to disk */ data = N_VGetArrayPointer(y); if (check_flag((void *)data, "N_VGetArrayPointer", 0)) return 1; for (i=0; i<N; i++) fprintf(UFID," %.16e", data[IDX(i,0)]); for (i=0; i<N; i++) fprintf(VFID," %.16e", data[IDX(i,1)]); for (i=0; i<N; i++) fprintf(WFID," %.16e", data[IDX(i,2)]); fprintf(UFID,"\n"); fprintf(VFID,"\n"); fprintf(WFID,"\n"); /* Main time-stepping loop: calls ARKode to perform the integration, then prints results. Stops when the final time has been reached */ t = T0; dTout = (Tf-T0)/Nt; tout = T0+dTout; printf(" t ||u||_rms ||v||_rms ||w||_rms\n"); printf(" ----------------------------------------------\n"); for (iout=0; iout<Nt; iout++) { flag = ARKode(arkode_mem, tout, y, &t, ARK_NORMAL); /* call integrator */ if (check_flag(&flag, "ARKode", 1)) break; u = N_VWL2Norm(y,umask); /* access/print solution statistics */ u = sqrt(u*u/N); v = N_VWL2Norm(y,vmask); v = sqrt(v*v/N); w = N_VWL2Norm(y,wmask); w = sqrt(w*w/N); printf(" %10.6f %10.6f %10.6f %10.6f\n", t, u, v, w); if (flag >= 0) { /* successful solve: update output time */ tout += dTout; tout = (tout > Tf) ? Tf : tout; } else { /* unsuccessful solve: break */ fprintf(stderr,"Solver failure, stopping integration\n"); break; } /* output results to disk */ for (i=0; i<N; i++) fprintf(UFID," %.16e", data[IDX(i,0)]); for (i=0; i<N; i++) fprintf(VFID," %.16e", data[IDX(i,1)]); for (i=0; i<N; i++) fprintf(WFID," %.16e", data[IDX(i,2)]); fprintf(UFID,"\n"); fprintf(VFID,"\n"); fprintf(WFID,"\n"); } printf(" ----------------------------------------------\n"); fclose(UFID); fclose(VFID); fclose(WFID); /* Print some final statistics */ flag = ARKodeGetNumSteps(arkode_mem, &nst); check_flag(&flag, "ARKodeGetNumSteps", 1); flag = ARKodeGetNumStepAttempts(arkode_mem, &nst_a); check_flag(&flag, "ARKodeGetNumStepAttempts", 1); flag = ARKodeGetNumRhsEvals(arkode_mem, &nfe, &nfi); check_flag(&flag, "ARKodeGetNumRhsEvals", 1); flag = ARKodeGetNumLinSolvSetups(arkode_mem, &nsetups); check_flag(&flag, "ARKodeGetNumLinSolvSetups", 1); flag = ARKodeGetNumErrTestFails(arkode_mem, &netf); check_flag(&flag, "ARKodeGetNumErrTestFails", 1); flag = ARKodeGetNumNonlinSolvIters(arkode_mem, &nni); check_flag(&flag, "ARKodeGetNumNonlinSolvIters", 1); flag = ARKodeGetNumNonlinSolvConvFails(arkode_mem, &ncfn); check_flag(&flag, "ARKodeGetNumNonlinSolvConvFails", 1); flag = ARKDlsGetNumJacEvals(arkode_mem, &nje); check_flag(&flag, "ARKDlsGetNumJacEvals", 1); flag = ARKDlsGetNumRhsEvals(arkode_mem, &nfeLS); check_flag(&flag, "ARKDlsGetNumRhsEvals", 1); printf("\nFinal Solver Statistics:\n"); printf(" Internal solver steps = %li (attempted = %li)\n", nst, nst_a); printf(" Total RHS evals: Fe = %li, Fi = %li\n", nfe, nfi); printf(" Total linear solver setups = %li\n", nsetups); printf(" Total RHS evals for setting up the linear system = %li\n", nfeLS); printf(" Total number of Jacobian evaluations = %li\n", nje); printf(" Total number of Newton iterations = %li\n", nni); printf(" Total number of nonlinear solver convergence failures = %li\n", ncfn); printf(" Total number of error test failures = %li\n\n", netf); /* Clean up and return with successful completion */ N_VDestroy_OpenMP(y); /* Free vectors */ N_VDestroy_OpenMP(umask); N_VDestroy_OpenMP(vmask); N_VDestroy_OpenMP(wmask); free(udata); /* Free user data */ ARKodeFree(&arkode_mem); /* Free integrator memory */ return 0; } /*------------------------------- * Functions called by the solver *-------------------------------*/ /* f routine to compute the ODE RHS function f(t,y). */ static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data) { UserData udata = (UserData) user_data; /* access problem data */ long int N = udata->N; /* set variable shortcuts */ realtype a = udata->a; realtype b = udata->b; realtype ep = udata->ep; realtype du = udata->du; realtype dv = udata->dv; realtype dw = udata->dw; realtype dx = udata->dx; realtype *Ydata=NULL, *dYdata=NULL; realtype uconst, vconst, wconst, u, ul, ur, v, vl, vr, w, wl, wr; long int i; /* clear out ydot (to be careful) */ N_VConst(0.0, ydot); Ydata = N_VGetArrayPointer(y); /* access data arrays */ if (check_flag((void *)Ydata, "N_VGetArrayPointer", 0)) return 1; dYdata = N_VGetArrayPointer(ydot); if (check_flag((void *)dYdata, "N_VGetArrayPointer", 0)) return 1; N_VConst(0.0, ydot); /* initialize ydot to zero */ /* iterate over domain, computing all equations */ uconst = du/dx/dx; vconst = dv/dx/dx; wconst = dw/dx/dx; #pragma omp parallel for default(shared) private(i,u,ul,ur,v,vl,vr,w,wl,wr) schedule(static) num_threads(udata->nthreads) for (i=1; i<N-1; i++) { /* set shortcuts */ u = Ydata[IDX(i,0)]; ul = Ydata[IDX(i-1,0)]; ur = Ydata[IDX(i+1,0)]; v = Ydata[IDX(i,1)]; vl = Ydata[IDX(i-1,1)]; vr = Ydata[IDX(i+1,1)]; w = Ydata[IDX(i,2)]; wl = Ydata[IDX(i-1,2)]; wr = Ydata[IDX(i+1,2)]; /* u_t = du*u_xx + a - (w+1)*u + v*u^2 */ dYdata[IDX(i,0)] = (ul - RCONST(2.0)*u + ur)*uconst + a - (w+RCONST(1.0))*u + v*u*u; /* v_t = dv*v_xx + w*u - v*u^2 */ dYdata[IDX(i,1)] = (vl - RCONST(2.0)*v + vr)*vconst + w*u - v*u*u; /* w_t = dw*w_xx + (b-w)/ep - w*u */ dYdata[IDX(i,2)] = (wl - RCONST(2.0)*w + wr)*wconst + (b-w)/ep - w*u; } /* enforce stationary boundaries */ dYdata[IDX(0,0)] = dYdata[IDX(0,1)] = dYdata[IDX(0,2)] = 0.0; dYdata[IDX(N-1,0)] = dYdata[IDX(N-1,1)] = dYdata[IDX(N-1,2)] = 0.0; return 0; } /* Jacobian routine to compute J(t,y) = df/dy. */ static int Jac(long int M, long int mu, long int ml, realtype t, N_Vector y, N_Vector fy, DlsMat J, void *user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3) { UserData udata = (UserData) user_data; /* access problem data */ SetToZero(J); /* Initialize Jacobian to zero */ /* Fill in the Laplace matrix */ if (LaplaceMatrix(RCONST(1.0), J, udata)) { printf("Jacobian calculation error in calling LaplaceMatrix!\n"); return 1; } /* Add in the Jacobian of the reaction terms matrix */ if (ReactionJac(RCONST(1.0), y, J, udata)) { printf("Jacobian calculation error in calling ReactionJac!\n"); return 1; } return 0; } /*------------------------------- * Private helper functions *-------------------------------*/ /* Routine to compute the stiffness matrix from (L*y), scaled by the factor c. We add the result into Jac and do not erase what was already there */ static int LaplaceMatrix(realtype c, DlsMat Jac, UserData udata) { long int i; /* set shortcuts */ long int N = udata->N; realtype dx = udata->dx; /* iterate over intervals, filling in Jacobian entries */ #pragma omp parallel for default(shared) private(i) schedule(static) num_threads(udata->nthreads) for (i=1; i<N-1; i++) { /* Jacobian of (L*y) at this node */ BAND_ELEM(Jac,IDX(i,0),IDX(i-1,0)) += c*udata->du/dx/dx; BAND_ELEM(Jac,IDX(i,1),IDX(i-1,1)) += c*udata->dv/dx/dx; BAND_ELEM(Jac,IDX(i,2),IDX(i-1,2)) += c*udata->dw/dx/dx; BAND_ELEM(Jac,IDX(i,0),IDX(i,0)) += -c*RCONST(2.0)*udata->du/dx/dx; BAND_ELEM(Jac,IDX(i,1),IDX(i,1)) += -c*RCONST(2.0)*udata->dv/dx/dx; BAND_ELEM(Jac,IDX(i,2),IDX(i,2)) += -c*RCONST(2.0)*udata->dw/dx/dx; BAND_ELEM(Jac,IDX(i,0),IDX(i+1,0)) += c*udata->du/dx/dx; BAND_ELEM(Jac,IDX(i,1),IDX(i+1,1)) += c*udata->dv/dx/dx; BAND_ELEM(Jac,IDX(i,2),IDX(i+1,2)) += c*udata->dw/dx/dx; } return 0; } /* Routine to compute the Jacobian matrix from R(y), scaled by the factor c. We add the result into Jac and do not erase what was already there */ static int ReactionJac(realtype c, N_Vector y, DlsMat Jac, UserData udata) { long int N = udata->N; /* set shortcuts */ long int i; realtype u, v, w; realtype ep = udata->ep; realtype *Ydata = N_VGetArrayPointer(y); /* access solution array */ if (check_flag((void *)Ydata, "N_VGetArrayPointer", 0)) return 1; /* iterate over nodes, filling in Jacobian entries */ #pragma omp parallel for default(shared) private(i,u,v,w) schedule(static) num_threads(udata->nthreads) for (i=1; i<N-1; i++) { /* set nodal value shortcuts (shifted index due to start at first interior node) */ u = Ydata[IDX(i,0)]; v = Ydata[IDX(i,1)]; w = Ydata[IDX(i,2)]; /* all vars wrt u */ BAND_ELEM(Jac,IDX(i,0),IDX(i,0)) += c*(RCONST(2.0)*u*v-(w+RCONST(1.0))); BAND_ELEM(Jac,IDX(i,1),IDX(i,0)) += c*(w - RCONST(2.0)*u*v); BAND_ELEM(Jac,IDX(i,2),IDX(i,0)) += c*(-w); /* all vars wrt v */ BAND_ELEM(Jac,IDX(i,0),IDX(i,1)) += c*(u*u); BAND_ELEM(Jac,IDX(i,1),IDX(i,1)) += c*(-u*u); /* all vars wrt w */ BAND_ELEM(Jac,IDX(i,0),IDX(i,2)) += c*(-u); BAND_ELEM(Jac,IDX(i,1),IDX(i,2)) += c*(u); BAND_ELEM(Jac,IDX(i,2),IDX(i,2)) += c*(-RCONST(1.0)/ep - u); } return 0; } /* Check function return value... opt == 0 means SUNDIALS function allocates memory so check if returned NULL pointer opt == 1 means SUNDIALS function returns a flag so check if flag >= 0 opt == 2 means function allocates memory so check if returned NULL pointer */ static int check_flag(void *flagvalue, char *funcname, int opt) { int *errflag; /* Check if SUNDIALS function returned NULL pointer - no memory allocated */ if (opt == 0 && flagvalue == NULL) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return 1; } /* Check if flag < 0 */ else if (opt == 1) { errflag = (int *) flagvalue; if (*errflag < 0) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with flag = %d\n\n", funcname, *errflag); return 1; }} /* Check if function returned NULL pointer - no memory allocated */ else if (opt == 2 && flagvalue == NULL) { fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return 1; } return 0; } /*---- end of file ----*/
omp2.c
// note not doing O0 below as to ensure we get tbaa // TODO: %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O1 -disable-llvm-optzns %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -S | %clang -fopenmp -x ir - -o %s.out && %s.out // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O1 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O2 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O3 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi // note not doing O0 below as to ensure we get tbaa // TODO: %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O1 -Xclang -disable-llvm-optzns %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -enzyme-inline=1 -S | %clang -fopenmp -x ir - -o %s.out && %s.out // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O1 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -enzyme-inline=1 -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O2 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -enzyme-inline=1 -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O3 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -enzyme-inline=1 -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi #include <stdio.h> #include <math.h> #include <assert.h> #include "test_utils.h" double __enzyme_autodiff(void*, ...); /* void omp(float& a, int N) { #define N 20 #pragma omp parallel for for (int i=0; i<N; i++) { //a[i] *= a[i]; (&a)[i] *= (&a)[i]; } #undef N (&a)[0] = 0; } */ void omp(float* a, int N, int M) { #pragma omp parallel for #pragma nounroll for (unsigned int i=M; i<N; i++) { //a[i] *= a[i]; a[i] *= a[i]; } a[0] = 0; } int main(int argc, char** argv) { int N = 20; int M = 10; float a[N]; for(int i=0; i<N; i++) { a[i] = i+1; } float d_a[N]; for(int i=0; i<N; i++) d_a[i] = 1.0f; //omp(*a, N); printf("ran omp\n"); __enzyme_autodiff((void*)omp, a, d_a, N, M); for(int i=0; i<N; i++) { printf("a[%d]=%f d_a[%d]=%f\n", i, a[i], i, d_a[i]); } //APPROX_EQ(da, 17711.0*2, 1e-10); //APPROX_EQ(db, 17711.0*2, 1e-10); //printf("hello! %f, res2 %f, da: %f, db: %f\n", ret, ret, da,db); APPROX_EQ(d_a[0], 0.0f, 1e-10); for(int i=1; i<N; i++) { if (i < M) { APPROX_EQ(d_a[i], 1.0f, 1e-10); } else { APPROX_EQ(d_a[i], 2.0f*(i+1), 1e-10); } } return 0; }
kiss_fft.c
/* Copyright (c) 2003-2010, Mark Borgerding All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "_kiss_fft_guts.h" /* The guts header contains all the multiplication and addition macros that are defined for fixed or floating point complex numbers. It also delares the kf_ internal functions. */ static void kf_bfly2( kiss_fft_cpx *Fout, const size_t fstride, const kiss_fft_cfg st, int m) { kiss_fft_cpx *Fout2; kiss_fft_cpx *tw1 = st->twiddles; kiss_fft_cpx t; Fout2 = Fout + m; do { C_FIXDIV(*Fout, 2); C_FIXDIV(*Fout2, 2); C_MUL(t, *Fout2, *tw1); tw1 += fstride; C_SUB(*Fout2, *Fout, t); C_ADDTO(*Fout, t); ++Fout2; ++Fout; } while (--m); } static void kf_bfly4( kiss_fft_cpx *Fout, const size_t fstride, const kiss_fft_cfg st, const size_t m) { kiss_fft_cpx *tw1, *tw2, *tw3; kiss_fft_cpx scratch[6]; size_t k = m; const size_t m2 = 2 * m; const size_t m3 = 3 * m; tw3 = tw2 = tw1 = st->twiddles; do { C_FIXDIV(*Fout, 4); C_FIXDIV(Fout[m], 4); C_FIXDIV(Fout[m2], 4); C_FIXDIV(Fout[m3], 4); C_MUL(scratch[0], Fout[m], *tw1); C_MUL(scratch[1], Fout[m2], *tw2); C_MUL(scratch[2], Fout[m3], *tw3); C_SUB(scratch[5], *Fout, scratch[1]); C_ADDTO(*Fout, scratch[1]); C_ADD(scratch[3], scratch[0], scratch[2]); C_SUB(scratch[4], scratch[0], scratch[2]); C_SUB(Fout[m2], *Fout, scratch[3]); tw1 += fstride; tw2 += fstride * 2; tw3 += fstride * 3; C_ADDTO(*Fout, scratch[3]); if (st->inverse) { Fout[m].r = scratch[5].r - scratch[4].i; Fout[m].i = scratch[5].i + scratch[4].r; Fout[m3].r = scratch[5].r + scratch[4].i; Fout[m3].i = scratch[5].i - scratch[4].r; } else { Fout[m].r = scratch[5].r + scratch[4].i; Fout[m].i = scratch[5].i - scratch[4].r; Fout[m3].r = scratch[5].r - scratch[4].i; Fout[m3].i = scratch[5].i + scratch[4].r; } ++Fout; } while (--k); } static void kf_bfly3( kiss_fft_cpx *Fout, const size_t fstride, const kiss_fft_cfg st, size_t m) { size_t k = m; const size_t m2 = 2 * m; kiss_fft_cpx *tw1, *tw2; kiss_fft_cpx scratch[5]; kiss_fft_cpx epi3; epi3 = st->twiddles[fstride * m]; tw1 = tw2 = st->twiddles; do { C_FIXDIV(*Fout, 3); C_FIXDIV(Fout[m], 3); C_FIXDIV(Fout[m2], 3); C_MUL(scratch[1], Fout[m], *tw1); C_MUL(scratch[2], Fout[m2], *tw2); C_ADD(scratch[3], scratch[1], scratch[2]); C_SUB(scratch[0], scratch[1], scratch[2]); tw1 += fstride; tw2 += fstride * 2; Fout[m].r = Fout->r - HALF_OF(scratch[3].r); Fout[m].i = Fout->i - HALF_OF(scratch[3].i); C_MULBYSCALAR(scratch[0], epi3.i); C_ADDTO(*Fout, scratch[3]); Fout[m2].r = Fout[m].r + scratch[0].i; Fout[m2].i = Fout[m].i - scratch[0].r; Fout[m].r -= scratch[0].i; Fout[m].i += scratch[0].r; ++Fout; } while (--k); } static void kf_bfly5( kiss_fft_cpx *Fout, const size_t fstride, const kiss_fft_cfg st, int m) { kiss_fft_cpx *Fout0, *Fout1, *Fout2, *Fout3, *Fout4; int u; kiss_fft_cpx scratch[13]; kiss_fft_cpx *twiddles = st->twiddles; kiss_fft_cpx *tw; kiss_fft_cpx ya, yb; ya = twiddles[fstride * m]; yb = twiddles[fstride * 2 * m]; Fout0 = Fout; Fout1 = Fout0 + m; Fout2 = Fout0 + 2 * m; Fout3 = Fout0 + 3 * m; Fout4 = Fout0 + 4 * m; tw = st->twiddles; for (u = 0; u < m; ++u) { C_FIXDIV(*Fout0, 5); C_FIXDIV(*Fout1, 5); C_FIXDIV(*Fout2, 5); C_FIXDIV(*Fout3, 5); C_FIXDIV(*Fout4, 5); scratch[0] = *Fout0; C_MUL(scratch[1], *Fout1, tw[u * fstride]); C_MUL(scratch[2], *Fout2, tw[2 * u * fstride]); C_MUL(scratch[3], *Fout3, tw[3 * u * fstride]); C_MUL(scratch[4], *Fout4, tw[4 * u * fstride]); C_ADD(scratch[7], scratch[1], scratch[4]); C_SUB(scratch[10], scratch[1], scratch[4]); C_ADD(scratch[8], scratch[2], scratch[3]); C_SUB(scratch[9], scratch[2], scratch[3]); Fout0->r += scratch[7].r + scratch[8].r; Fout0->i += scratch[7].i + scratch[8].i; scratch[5].r = scratch[0].r + S_MUL(scratch[7].r, ya.r) + S_MUL(scratch[8].r, yb.r); scratch[5].i = scratch[0].i + S_MUL(scratch[7].i, ya.r) + S_MUL(scratch[8].i, yb.r); scratch[6].r = S_MUL(scratch[10].i, ya.i) + S_MUL(scratch[9].i, yb.i); scratch[6].i = -S_MUL(scratch[10].r, ya.i) - S_MUL(scratch[9].r, yb.i); C_SUB(*Fout1, scratch[5], scratch[6]); C_ADD(*Fout4, scratch[5], scratch[6]); scratch[11].r = scratch[0].r + S_MUL(scratch[7].r, yb.r) + S_MUL(scratch[8].r, ya.r); scratch[11].i = scratch[0].i + S_MUL(scratch[7].i, yb.r) + S_MUL(scratch[8].i, ya.r); scratch[12].r = -S_MUL(scratch[10].i, yb.i) + S_MUL(scratch[9].i, ya.i); scratch[12].i = S_MUL(scratch[10].r, yb.i) - S_MUL(scratch[9].r, ya.i); C_ADD(*Fout2, scratch[11], scratch[12]); C_SUB(*Fout3, scratch[11], scratch[12]); ++Fout0; ++Fout1; ++Fout2; ++Fout3; ++Fout4; } } /* perform the butterfly for one stage of a mixed radix FFT */ static void kf_bfly_generic( kiss_fft_cpx *Fout, const size_t fstride, const kiss_fft_cfg st, int m, int p) { int u, k, q1, q; kiss_fft_cpx *twiddles = st->twiddles; kiss_fft_cpx t; int Norig = st->nfft; kiss_fft_cpx *scratch = (kiss_fft_cpx *)KISS_FFT_TMP_ALLOC(sizeof(kiss_fft_cpx) * p); for (u = 0; u < m; ++u) { k = u; for (q1 = 0; q1 < p; ++q1) { scratch[q1] = Fout[k]; C_FIXDIV(scratch[q1], p); k += m; } k = u; for (q1 = 0; q1 < p; ++q1) { int twidx = 0; Fout[k] = scratch[0]; for (q = 1; q < p; ++q) { twidx += fstride * k; if (twidx >= Norig) twidx -= Norig; C_MUL(t, scratch[q], twiddles[twidx]); C_ADDTO(Fout[k], t); } k += m; } } KISS_FFT_TMP_FREE(scratch); } static void kf_work( kiss_fft_cpx *Fout, const kiss_fft_cpx *f, const size_t fstride, int in_stride, int *factors, const kiss_fft_cfg st) { kiss_fft_cpx *Fout_beg = Fout; const int p = *factors++; /* the radix */ const int m = *factors++; /* stage's fft length/p */ const kiss_fft_cpx *Fout_end = Fout + p * m; #ifdef _OPENMP // use openmp extensions at the // top-level (not recursive) if (fstride == 1 && p <= 5) { int k; // execute the p different work units in different threads #pragma omp parallel for for (k = 0; k < p; ++k) kf_work(Fout + k * m, f + fstride * in_stride * k, fstride * p, in_stride, factors, st); // all threads have joined by this point switch (p) { case 2: kf_bfly2(Fout, fstride, st, m); break; case 3: kf_bfly3(Fout, fstride, st, m); break; case 4: kf_bfly4(Fout, fstride, st, m); break; case 5: kf_bfly5(Fout, fstride, st, m); break; default: kf_bfly_generic(Fout, fstride, st, m, p); break; } return; } #endif if (m == 1) { do { *Fout = *f; f += fstride * in_stride; } while (++Fout != Fout_end); } else { do { // recursive call: // DFT of size m*p performed by doing // p instances of smaller DFTs of size m, // each one takes a decimated version of the input kf_work(Fout, f, fstride * p, in_stride, factors, st); f += fstride * in_stride; } while ((Fout += m) != Fout_end); } Fout = Fout_beg; // recombine the p smaller DFTs switch (p) { case 2: kf_bfly2(Fout, fstride, st, m); break; case 3: kf_bfly3(Fout, fstride, st, m); break; case 4: kf_bfly4(Fout, fstride, st, m); break; case 5: kf_bfly5(Fout, fstride, st, m); break; default: kf_bfly_generic(Fout, fstride, st, m, p); break; } } /* facbuf is populated by p1,m1,p2,m2, ... where p[i] * m[i] = m[i-1] m0 = n */ static void kf_factor(int n, int *facbuf) { int p = 4; double floor_sqrt; floor_sqrt = floor(sqrt((double)n)); /*factor out powers of 4, powers of 2, then any remaining primes */ do { while (n % p) { switch (p) { case 4: p = 2; break; case 2: p = 3; break; default: p += 2; break; } if (p > floor_sqrt) p = n; /* no more factors, skip to end */ } n /= p; *facbuf++ = p; *facbuf++ = n; } while (n > 1); } /* * * User-callable function to allocate all necessary storage space for the fft. * * The return value is a contiguous block of memory, allocated with malloc. As such, * It can be freed with free(), rather than a kiss_fft-specific function. * */ kiss_fft_cfg kiss_fft_alloc(int nfft, int inverse_fft, void *mem, size_t *lenmem) { kiss_fft_cfg st = NULL; size_t memneeded = sizeof(struct kiss_fft_state) + sizeof(kiss_fft_cpx) * (nfft - 1); /* twiddle factors*/ if (lenmem == NULL) { st = (kiss_fft_cfg)KISS_FFT_MALLOC(memneeded); } else { if (mem != NULL && *lenmem >= memneeded) st = (kiss_fft_cfg)mem; *lenmem = memneeded; } if (st) { int i; st->nfft = nfft; st->inverse = inverse_fft; for (i = 0; i < nfft; ++i) { const double pi = 3.141592653589793238462643383279502884197169399375105820974944; double phase = -2 * pi * i / nfft; if (st->inverse) phase *= -1; kf_cexp(st->twiddles + i, phase); } kf_factor(nfft, st->factors); } return st; } void kiss_fft_stride(kiss_fft_cfg st, const kiss_fft_cpx *fin, kiss_fft_cpx *fout, int in_stride) { if (fin == fout) { //NOTE: this is not really an in-place FFT algorithm. //It just performs an out-of-place FFT into a temp buffer kiss_fft_cpx *tmpbuf = (kiss_fft_cpx *)KISS_FFT_TMP_ALLOC(sizeof(kiss_fft_cpx) * st->nfft); kf_work(tmpbuf, fin, 1, in_stride, st->factors, st); memcpy(fout, tmpbuf, sizeof(kiss_fft_cpx) * st->nfft); KISS_FFT_TMP_FREE(tmpbuf); } else { kf_work(fout, fin, 1, in_stride, st->factors, st); } } void kiss_fft(kiss_fft_cfg cfg, const kiss_fft_cpx *fin, kiss_fft_cpx *fout) { kiss_fft_stride(cfg, fin, fout, 1); } void kiss_fft_cleanup(void) { // nothing needed any more } int kiss_fft_next_fast_size(int n) { while (1) { int m = n; while ((m % 2) == 0) m /= 2; while ((m % 3) == 0) m /= 3; while ((m % 5) == 0) m /= 5; if (m <= 1) break; /* n is completely factorable by twos, threes, and fives */ n++; } return n; }
triad.c
/******************************************************************************* * Copyright 2021 UChicago Argonne, LLC. * (c.f. AUTHORS, LICENSE) * * This file is part of the NRM Benchmarks project. * For more info, see https://github.com/anlsys/nrm-benchmarks * * SPDX-License-Identifier: BSD-3-Clause ******************************************************************************/ #include "config.h" #include "nrm-benchmarks.h" #include <nrm.h> static double *a, *b, *c; static struct nrm_context *context; static struct nrm_scope *region_scope, **thread_scope; int main(int argc, char **argv) { /* configuration parameters: * - array size in number of double elements * - number of times to run through the benchmark */ size_t array_size; long int times; double scalar = 3.0; /* needed for performance measurement */ int64_t sumtime = 0, mintime = INT64_MAX, maxtime = 0; nrmb_time_t start, end; size_t memory_size; int num_threads; /* retrieve the size of the allocation and the number of time * to loop through the kernel. */ assert(argc == 3); array_size = strtoull(argv[1], NULL, 0); assert(!errno); times = strtol(argv[2], NULL, 0); assert(!errno); /* ensure that OpenMP is giving us the right number of threads */ #pragma omp parallel #pragma omp master num_threads = omp_get_num_threads(); int err = 0; #pragma omp parallel #pragma omp atomic err++; assert(num_threads == err); err = 0; /* allocate the arrays and initialize them. Note that we expect the * first-touch policy of Linux to result in the arrays being properly * balanced between threads/numa-nodes */ memory_size = array_size * sizeof(double); a = malloc(memory_size); b = malloc(memory_size); c = malloc(memory_size); #pragma omp parallel for for(size_t i = 0; i < array_size; i++) { a[i] = 1.0; b[i] = 2.0; c[i] = 0.0; } /* NRM Context init */ context = nrm_ctxt_create(); nrm_init(context, argv[0], 0, 0); /* one run of the benchmark for free, warms up the memory */ #pragma omp parallel for for(size_t i = 0; i < array_size; i++) c[i] = a[i] + scalar*b[i]; /* this version of the benchmarks reports one progress each time it goes * through the entire array. */ /* Create scopes */ region_scope = nrm_scope_create(); thread_scope = malloc(num_threads*sizeof(nrm_scope_t*)); for (int i = 0; i < num_threads; i++) { thread_scope[i] = nrm_scope_create(); } /* Get master process scope */ nrm_scope_threadshared(region_scope); nrm_send_progress(context, 1, region_scope); for(long int iter = 0; iter < times; iter++) { int64_t time; nrmb_gettime(&start); /* the actual benchmark */ #pragma omp parallel for for(size_t i = 0; i < array_size; i++) { c[i] = a[i] + scalar*b[i]; /* Get scopes */ nrm_scope_threadshared(region_scope); nrm_scope_threadprivate(thread_scope[omp_get_thread_num()]); nrm_send_progress(context, 1, thread_scope[omp_get_thread_num()]); } nrmb_gettime(&end); nrm_send_progress(context, 1, region_scope); time = nrmb_timediff(&start, &end); sumtime += time; mintime = NRMB_MIN(time, mintime); maxtime = NRMB_MAX(time, maxtime); } nrm_fini(context); nrm_ctxt_delete(context); /* Delete scopes */ nrm_scope_delete(region_scope); for (int i = 0; i < num_threads; i++) { nrm_scope_delete(thread_scope[i]); } /* compute stats */ /* report the configuration and timings */ fprintf(stdout, "NRM Benchmarks: %s\n", argv[0]); fprintf(stdout, "Version: %s\n", PACKAGE_VERSION); fprintf(stdout, "Description: one progress per iteration, Triad benchmark\n"); fprintf(stdout, "Array size: %zu (elements).\n", array_size); fprintf(stdout, "Memory per array: %.1f MiB.\n", (double) memory_size /1024.0/1024.0); fprintf(stdout, "Kernel was executed: %ld times.\n", times); fprintf(stdout, "Number of threads: %d\n", num_threads); fprintf(stdout, "Time (s): avg: %11.6f min: %11.6f max: %11.6f\n", 1.0E-09 * sumtime/times, 1.0E-09 * mintime, 1.0E-09 * maxtime); fprintf(stdout, "Perf (MiB/s): avg: %12.6f best: %12.6f\n", (3.0E-06 * memory_size)/ (1.0E-09 * sumtime/times), (3.0E-06 * memory_size)/ (1.0E-09 * mintime)); /* validate the benchmark: minimum about of bits should be different. */ err = 0; for(size_t i = 0; i < array_size && err == 0; i++) err = err || !nrmb_check_double(7.0, c[i], 2); if(err) fprintf(stdout, "VALIDATION FAILED!!!!\n"); else fprintf(stdout, "VALIDATION PASSED!!!!\n"); return err; }
HDAA_fmt_plug.c
/* HTTP Digest access authentication patch for john * * Written by Romain Raboin. OMP and intrinsics support by magnum * * This software is Copyright (c) 2008 Romain Raboin - romain.raboin at * gmail.com, and Copyright (c) 2012 magnum and it is hereby released to * the general public under the following terms: Redistribution and * use in source and binary forms, with or without modification, are * permitted. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_HDAA; #elif FMT_REGISTERS_H john_register_one(&fmt_HDAA); #else #include <stdint.h> #include <string.h> #ifdef __MMX__ #include <mmintrin.h> #endif #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "md5.h" #if !ARCH_LITTLE_ENDIAN // For now, neuter this format from SIMD building. // Someone else can port to BE at a later date. #undef SIMD_COEF_32 #undef SIMD_PARA_MD5 #endif #include "simd-intrinsics.h" #define ALGORITHM_NAME "MD5 " MD5_ALGORITHM_NAME #if !FAST_FORMATS_OMP #undef _OPENMP #endif #if defined(_OPENMP) #include <omp.h> #endif #include "memdbg.h" #define FORMAT_LABEL "hdaa" #define FORMAT_NAME "HTTP Digest access authentication" #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH 0 #define PLAINTEXT_LENGTH 32 #define CIPHERTEXT_LENGTH 32 #define BINARY_SIZE 16 #define BINARY_ALIGN 4 #define SALT_SIZE sizeof(reqinfo_t) #define SALT_ALIGN sizeof(size_t) #if defined(_OPENMP) static unsigned int omp_t = 1; #ifdef SIMD_COEF_32 #ifndef OMP_SCALE #define OMP_SCALE 256 #endif #else #ifndef OMP_SCALE #define OMP_SCALE 64 #endif #endif #endif #ifdef SIMD_COEF_32 #define NBKEYS (SIMD_COEF_32 * SIMD_PARA_MD5) #define MIN_KEYS_PER_CRYPT NBKEYS #define MAX_KEYS_PER_CRYPT NBKEYS #define GETPOS(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i)&60)*SIMD_COEF_32 + ((i)&3) + (unsigned int)index/SIMD_COEF_32*64*SIMD_COEF_32 ) #define GETOUTPOS(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i)&0x1c)*SIMD_COEF_32 + ((i)&3) + (unsigned int)index/SIMD_COEF_32*16*SIMD_COEF_32 ) #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif #define SEPARATOR '$' #define FORMAT_TAG "$response$" #define TAG_LENGTH (sizeof(FORMAT_TAG)-1) #define SIZE_TAB 12 // This is 8 x 64 bytes, so in MMX/SSE2 we support up to 9 limbs of MD5 #define HTMP 512 typedef struct { size_t h1tmplen; size_t h3tmplen; char h1tmp[HTMP]; char h3tmp[HTMP]; } reqinfo_t; /* digest authentication scheme : h1 = md5(user:realm:password) h2 = md5(method:digestURI) response = h3 = md5(h1:nonce:nonceCount:ClientNonce:qop:h2) */ /* request information */ enum e_req { R_RESPONSE, R_USER, R_REALM, R_METHOD, R_URI, R_NONCE, R_NONCECOUNT, R_CLIENTNONCE, R_QOP }; /* response:user:realm:method:uri:nonce:nonceCount:ClientNonce:qop */ static struct fmt_tests tests[] = { {"$response$679066476e67b5c7c4e88f04be567f8b$user$myrealm$GET$/$8c12bd8f728afe56d45a0ce846b70e5a$00000001$4b61913cec32e2c9$auth", "nocode"}, {"$response$faa6cb7d676e5b7c17fcbf966436aa0c$moi$myrealm$GET$/$af32592775d27b1cd06356b3a0db9ddf$00000001$8e1d49754a25aea7$auth", "kikou"}, {"$response$56940f87f1f53ade8b7d3c5a102c2bf3$usrx$teN__chars$GET$/4TLHS1TMN9cfsbqSUAdTG3CRq7qtXMptnYfn7mIIi3HRKOMhOks56e$2c0366dcbc$00000001$0153$auth", "passWOrd"}, {"$response$8663faf2337dbcb2c52882807592ec2c$user$myrealm$GET$/$8c12bd8f728afe56d45a0ce846b70e5a$", "pass"}, {"$response$8663faf2337dbcb2c52882807592ec2c$user$myrealm$GET$/$8c12bd8f728afe56d45a0ce846b70e5a", "pass"}, {NULL} }; /* used by set_key */ static char (*saved_plain)[PLAINTEXT_LENGTH + 1]; #ifdef SIMD_COEF_32 #define LIMBS 9 static unsigned char *saved_key[LIMBS]; static unsigned int *interm_key; static unsigned int *crypt_key; #else static int (*saved_len); static unsigned char (*crypt_key)[BINARY_SIZE]; #endif /* Store information about the request ()*/ static reqinfo_t *rinfo = NULL; static void init(struct fmt_main *self) { #ifdef SIMD_COEF_32 int i; #endif #if defined (_OPENMP) omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif #ifdef SIMD_COEF_32 for (i = 0; i < LIMBS; i++) saved_key[i] = mem_calloc_align(self->params.max_keys_per_crypt, 64, MEM_ALIGN_SIMD); interm_key = mem_calloc_align(self->params.max_keys_per_crypt, 16, MEM_ALIGN_SIMD); crypt_key = mem_calloc_align(self->params.max_keys_per_crypt, 16, MEM_ALIGN_SIMD); #else saved_len = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_len)); crypt_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_key)); #endif saved_plain = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_plain)); } static void done(void) { #ifdef SIMD_COEF_32 int i; #endif MEM_FREE(saved_plain); MEM_FREE(crypt_key); #ifdef SIMD_COEF_32 MEM_FREE(interm_key); for (i = 0; i < LIMBS; i++) MEM_FREE(saved_key[i]); #else MEM_FREE(saved_len); #endif } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy, *keeptr, *p; if (strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH) != 0) return 0; ctcopy = strdup(ciphertext); keeptr = ctcopy; ctcopy += TAG_LENGTH; if ((p = strtokm(ctcopy, "$")) == NULL) /* hash */ goto err; if (!ishexlc(p) || strlen(p) != 32) goto err; if ((p = strtokm(NULL, "$")) == NULL) /* user */ goto err; if ((p = strtokm(NULL, "$")) == NULL) /* realm */ goto err; if ((p = strtokm(NULL, "$")) == NULL) /* method */ goto err; if ((p = strtokm(NULL, "$")) == NULL) /* uri */ goto err; if ((p = strtokm(NULL, "$")) == NULL) /* nonce */ goto err; if ((p = strtokm(NULL, "$")) == NULL) /* End of legacy HDAA or noncecount */ goto end_hdaa_legacy; if ((p = strtokm(NULL, "$")) == NULL) /* clientnonce */ goto err; if (!ishexlc(p) ) goto err; if ((p = strtokm(NULL, "$")) == NULL) /* qop */ goto err; if ((p = strtokm(NULL, "$")) != NULL) goto err; end_hdaa_legacy: MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } // Normalize shorter hashes, to allow with or without trailing '$' character. static char *split(char *ciphertext, int index, struct fmt_main *self) { char *cp; if (strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH)) return ciphertext; cp = ciphertext + TAG_LENGTH; cp = strchr(cp, '$'); if (!cp) return ciphertext; cp = strchr(cp+1, '$'); if (!cp) return ciphertext; cp = strchr(cp+1, '$'); if (!cp) return ciphertext; cp = strchr(cp+1, '$'); if (!cp) return ciphertext; cp = strchr(cp+1, '$'); if (!cp) return ciphertext; // now if we have $binary_hash$ then we remove the last '$' char if (strlen(cp) == 1 + BINARY_SIZE*2 + 1) { static char out[256]; strnzcpy(out, ciphertext, sizeof(out)); out[strlen(out)-1] = 0; return out; } return ciphertext; } static void set_salt(void *salt) { rinfo = salt; } static void set_key(char *key, int index) { strcpy(saved_plain[index], key); #ifndef SIMD_COEF_32 saved_len[index] = -1; #endif } static char *get_key(int index) { return saved_plain[index]; } static int cmp_all(void *binary, int count) { #ifdef SIMD_COEF_32 unsigned int x,y=0; #ifdef _OPENMP for (; y < SIMD_PARA_MD5 * omp_t; y++) #else for (; y < SIMD_PARA_MD5; y++) #endif for (x = 0; x < SIMD_COEF_32; x++) { if ( ((uint32_t*)binary)[0] == ((uint32_t*)crypt_key)[y*SIMD_COEF_32*4+x] ) return 1; } return 0; #else int index; for (index = 0; index < count; index++) if (!(memcmp(binary, crypt_key[index], BINARY_SIZE))) return 1; return 0; #endif } static int cmp_one(void *binary, int index) { #ifdef SIMD_COEF_32 unsigned int i,x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; for (i=0;i<(BINARY_SIZE/4);i++) if ( ((uint32_t*)binary)[i] != ((uint32_t*)crypt_key)[y*SIMD_COEF_32*4+i*SIMD_COEF_32+x] ) return 0; return 1; #else return !(memcmp(binary, crypt_key[index], BINARY_SIZE)); #endif } static int cmp_exact(char *source, int index) { return 1; } /* convert hash from binary to ascii */ #ifdef SIMD_COEF_32 // This code should be rewritten in intrinsics, reading from // MMX or SSE2 output buffers and writing to MMX/SSE2 input buffers. inline static void sse_bin2ascii(unsigned char *conv, unsigned char *src) { unsigned int index; for (index = 0; index < NBKEYS; index++) { unsigned int i, j = 0; for (i = 0; i < BINARY_SIZE; i += 2) { unsigned int t; t = (src[GETOUTPOS((i + 1), index)] & 0x0f); t <<= 12; t |= (src[GETOUTPOS((i + 1), index)] & 0xf0); t <<= 4; t |= (src[GETOUTPOS(i, index)] & 0x0f); t <<= 8; t |= ((src[GETOUTPOS(i, index)] & 0xf0) >> 4); t += 0x06060606; t += ((((t >> 4) & 0x01010101) * 0x27) + 0x2a2a2a2a); *(unsigned int*)&conv[GETPOS(j, index)] = t; j+=4; } } } #endif /* SIMD_COEF_32 */ #ifdef __MMX__ inline static void bin2ascii(__m64 *conv, __m64 *src) { unsigned int i = 0; while (i != 4) { __m64 l; __m64 r; __m64 t; __m64 u; __m64 v; /* 32 bits to 64 bits */ t = _mm_set1_pi32(0x0f0f0f0f); /* Bit-wise AND the 64-bit values in M1 and M2. */ u = _mm_and_si64(_mm_srli_si64(src[(i / 2)], 4), t); v = _mm_and_si64(src[(i / 2)], t); /* interleaving */ l = _mm_unpacklo_pi8(u, v); r = _mm_unpackhi_pi8(u, v); t = _mm_set1_pi32(0x06060606); l = _mm_add_pi32(l, t); r = _mm_add_pi32(r, t); t = _mm_set1_pi32(0x01010101); /* u = (l << 4) & t */ u = _mm_and_si64(_mm_srli_si64(l, 4), t); /* v = (r << 4) & t */ v = _mm_and_si64(_mm_srli_si64(r, 4), t); t = _mm_set1_pi32(0x00270027); /* Multiply four 16-bit values in M1 by four 16-bit values in M2 and produce the low 16 bits of the results. */ u = _mm_mullo_pi16(u, t); v = _mm_mullo_pi16(v, t); t = _mm_set1_pi32(0x2a2a2a2a); u = _mm_add_pi32(u, t); v = _mm_add_pi32(v, t); conv[(i++)] = _mm_add_pi32(l, u); conv[(i++)] = _mm_add_pi32(r, v); } __asm__ __volatile__("emms"); } #else inline static void bin2ascii(uint32_t *conv, uint32_t *source) { unsigned char *src = (unsigned char*)source; unsigned int i; unsigned int j = 0; uint32_t t = 0; for (i = 0; i < BINARY_SIZE; i += 2) { #if (ARCH_LITTLE_ENDIAN == 0) t = (src[i] & 0xf0); t *= 0x10; t += (src[i] & 0x0f); t *= 0x1000; t += (src[(i + 1)] & 0xf0); t *= 0x10; t += (src[(i + 1)] & 0x0f); #else t = (src[(i + 1)] & 0x0f); t *= 0x1000; t += (src[(i + 1)] & 0xf0); t *= 0x10; t += (src[i] & 0x0f); t *= 0x100; t += ((src[i] & 0xf0) >> 4); #endif t += 0x06060606; t += ((((t >> 4) & 0x01010101) * 0x27) + 0x2a2a2a2a); conv[(j++)] = t; } } #endif /* MMX */ #if SIMD_COEF_32 inline static void crypt_done(unsigned const int *source, unsigned int *dest, int index) { unsigned int i; unsigned const int *s = &source[(index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*4*SIMD_COEF_32]; unsigned int *d = &dest[(index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*4*SIMD_COEF_32]; for (i = 0; i < BINARY_SIZE / 4; i++) { *d = *s; s += SIMD_COEF_32; d += SIMD_COEF_32; } } #endif static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; #if SIMD_COEF_32 #if defined(_OPENMP) #define ti (thread*NBKEYS+index) int thread; #pragma omp parallel for for (thread = 0; thread < (count+NBKEYS-1)/NBKEYS; thread++) #else #define thread 0 #define ti index #endif { static unsigned int crypt_len[NBKEYS]; unsigned int index, i, shortest, longest; for (index = 0; index < NBKEYS; index++) { int len; char temp; const char *key; key = rinfo->h1tmp; for (len = 0; len < rinfo->h1tmplen; len += 4, key += 4) *(uint32_t*)&saved_key[len>>6][GETPOS(len, ti)] = *(uint32_t*)key; len = rinfo->h1tmplen; key = (char*)&saved_plain[ti]; while((temp = *key++)) { saved_key[len>>6][GETPOS(len, ti)] = temp; len++; } saved_key[len>>6][GETPOS(len, ti)] = 0x80; // Clean rest of this buffer i = len; while (++i & 3) saved_key[i>>6][GETPOS(i, ti)] = 0; for (; i < (((len+8)>>6)+1)*64; i += 4) *(uint32_t*)&saved_key[i>>6][GETPOS(i, ti)] = 0; ((unsigned int *)saved_key[(len+8)>>6])[14*SIMD_COEF_32 + (ti&(SIMD_COEF_32-1)) + (ti/SIMD_COEF_32)*16*SIMD_COEF_32] = len << 3; } SIMDmd5body(&saved_key[0][thread*64*NBKEYS], &crypt_key[thread*4*NBKEYS], NULL, SSEi_MIXED_IN); sse_bin2ascii((unsigned char*)&saved_key[0][thread*64*NBKEYS], (unsigned char*)&crypt_key[thread*4*NBKEYS]); longest = 0; shortest = HTMP; for (index = 0; index < NBKEYS; index++) { const char *key; int i, len; len = CIPHERTEXT_LENGTH - 1; key = rinfo->h3tmp + CIPHERTEXT_LENGTH; // Copy a char at a time until aligned at destination while (++len & 3) saved_key[len>>6][GETPOS(len, ti)] = *key++; // ...then a word at a time. This is a good boost, we are copying over 100 bytes. for (;len < rinfo->h3tmplen; len += 4, key += 4) *(uint32_t*)&saved_key[len>>6][GETPOS(len, ti)] = *(uint32_t*)key; len = rinfo->h3tmplen; saved_key[len>>6][GETPOS(len, ti)] = 0x80; // Clean rest of this buffer i = len; while (++i & 3) saved_key[i>>6][GETPOS(i, ti)] = 0; //for (; i < (((len+8)>>6)+1)*64; i += 4) for (; i <= crypt_len[index]; i += 4) *(uint32_t*)&saved_key[i>>6][GETPOS(i, ti)] = 0; ((unsigned int *)saved_key[(len+8)>>6])[14*SIMD_COEF_32 + (ti&(SIMD_COEF_32-1)) + (ti/SIMD_COEF_32)*16*SIMD_COEF_32] = len << 3; crypt_len[index] = len; if (len > longest) longest = len; if (len < shortest) shortest = len; } // First limb SIMDmd5body(&saved_key[0][thread*64*NBKEYS], &interm_key[thread*4*NBKEYS], NULL, SSEi_MIXED_IN); // Copy any output that is done now if (shortest < 56) { if (longest < 56) memcpy(&crypt_key[thread*4*NBKEYS], &interm_key[thread*4*NBKEYS], 16*NBKEYS); else for (index = 0; index < NBKEYS; index++) if (crypt_len[index] < 56) crypt_done(interm_key, crypt_key, ti); } // Do the rest of the limbs for (i = 1; i < (((longest + 8) >> 6) + 1); i++) { SIMDmd5body(&saved_key[i][thread*64*NBKEYS], &interm_key[thread*4*NBKEYS], &interm_key[thread*4*NBKEYS], SSEi_RELOAD|SSEi_MIXED_IN); // Copy any output that is done now if (shortest < i*64+56) { if (shortest > (i-1)*64+55 && longest < i*64+56) memcpy(&crypt_key[thread*4*NBKEYS], &interm_key[thread*4*NBKEYS], 16*NBKEYS); else for (index = 0; index < NBKEYS; index++) if (((crypt_len[index] + 8) >> 6) == i) crypt_done(interm_key, crypt_key, ti); } } } #undef thread #undef ti #else int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { MD5_CTX ctx; int len; #ifdef _OPENMP char h3tmp[HTMP]; char h1tmp[HTMP]; #else char *h3tmp; char *h1tmp; #endif size_t tmp; #ifdef __MMX__ __m64 h1[BINARY_SIZE / sizeof(__m64)]; __m64 conv[CIPHERTEXT_LENGTH / sizeof(__m64) + 1]; #else uint32_t h1[BINARY_SIZE / sizeof(uint32_t)]; uint32_t conv[(CIPHERTEXT_LENGTH / sizeof(uint32_t)) + 1]; #endif tmp = rinfo->h1tmplen; if ((len = saved_len[index]) < 0) len = saved_len[index] = strlen(saved_plain[index]); #ifdef _OPENMP memcpy(h1tmp, rinfo->h1tmp, tmp); memcpy(h3tmp + CIPHERTEXT_LENGTH, rinfo->h3tmp + CIPHERTEXT_LENGTH, rinfo->h3tmplen - CIPHERTEXT_LENGTH); #else h3tmp = rinfo->h3tmp; h1tmp = rinfo->h1tmp; #endif memcpy(&h1tmp[tmp], saved_plain[index], len); MD5_Init(&ctx); MD5_Update(&ctx, h1tmp, len + tmp); MD5_Final((unsigned char*)h1, &ctx); bin2ascii(conv, h1); memcpy(h3tmp, conv, CIPHERTEXT_LENGTH); MD5_Init(&ctx); MD5_Update(&ctx, h3tmp, rinfo->h3tmplen); MD5_Final(crypt_key[index], &ctx); } #endif return count; } static char *mystrndup(const char *s, size_t n) { size_t tmp; size_t size; char *ret; for (tmp = 0; s[tmp] != 0 && tmp <= n; tmp++); size = n; if (tmp < size) size = tmp; if ((ret = mem_alloc(sizeof(char) * size + 1)) == NULL) return NULL; memmove(ret, s, size); ret[size] = 0; return ret; } static size_t reqlen(char *str) { size_t len; for (len = 0; str[len] != 0 && str[len] != SEPARATOR; len++); return len; } static void *get_salt(char *ciphertext) { int nb; int i; char *request[SIZE_TAB]; char *str; static reqinfo_t *r; #ifdef __MMX__ __m64 h2[BINARY_SIZE / sizeof(__m64)]; __m64 conv[CIPHERTEXT_LENGTH / sizeof(__m64) + 1]; #else unsigned int h2[BINARY_SIZE / sizeof(unsigned int)]; uint32_t conv[(CIPHERTEXT_LENGTH / sizeof(uint32_t)) + 1]; #endif MD5_CTX ctx; /* parse the password string */ if (!r) r = mem_alloc_tiny(sizeof(*r), SALT_ALIGN); memset(r, 0, sizeof(*r)); for (nb = 0, i = 1; ciphertext[i] != 0; i++) { if (ciphertext[i] == SEPARATOR) { i++; request[nb] = mystrndup(&ciphertext[i], reqlen(&ciphertext[i])); nb++; if (!ciphertext[i]) break; } } while (nb < SIZE_TAB) { request[nb++] = NULL; } /* calculate h2 (h2 = md5(method:digestURI))*/ str = mem_alloc(strlen(request[R_METHOD]) + strlen(request[R_URI]) + 2); sprintf(str, "%s:%s", request[R_METHOD], request[R_URI]); MD5_Init(&ctx); MD5_Update(&ctx, str, strlen(str)); MD5_Final((unsigned char*)h2, &ctx); memset(conv, 0, CIPHERTEXT_LENGTH + 1); bin2ascii(conv, h2); MEM_FREE(str); /* create a part of h1 (h1tmp = request:realm:)*/ snprintf(r->h1tmp, HTMP - PLAINTEXT_LENGTH, "%s:%s:", request[R_USER], request[R_REALM]); /* create a part of h3 (h3tmp = nonce:noncecount:clientnonce:qop:h2)*/ if (request[R_CLIENTNONCE] == NULL) snprintf(&r->h3tmp[CIPHERTEXT_LENGTH], HTMP - CIPHERTEXT_LENGTH, ":%s:%s", request[R_NONCE], (char*)conv); else snprintf(&r->h3tmp[CIPHERTEXT_LENGTH], HTMP - CIPHERTEXT_LENGTH, ":%s:%s:%s:%s:%s", request[R_NONCE], request[R_NONCECOUNT], request[R_CLIENTNONCE], request[R_QOP], (char*)conv); r->h1tmplen = strlen(r->h1tmp); r->h3tmplen = strlen(&r->h3tmp[CIPHERTEXT_LENGTH]) + CIPHERTEXT_LENGTH; for (nb=0; nb < SIZE_TAB; ++nb) { MEM_FREE(request[nb]); } return r; } /* convert response to binary form */ static void *get_binary(char *ciphertext) { static unsigned int realcipher[BINARY_SIZE / sizeof(int)]; int i; ciphertext += TAG_LENGTH; for (i = 0; i < BINARY_SIZE; i++) { ((unsigned char*)realcipher)[i] = atoi16[ARCH_INDEX(ciphertext[i * 2])] * 16 + atoi16[ARCH_INDEX(ciphertext[i * 2 + 1])]; } return (void*) realcipher; } #define COMMON_GET_HASH_SIMD32 4 #define COMMON_GET_HASH_VAR crypt_key #include "common-get-hash.h" struct fmt_main fmt_HDAA = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, #ifdef _OPENMP FMT_OMP | FMT_OMP_BAD | #endif FMT_CASE | FMT_8_BIT, { NULL }, { FORMAT_TAG }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { #define COMMON_GET_HASH_LINK #include "common-get-hash.h" }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
equation_groupnorm.c
/****************************************************************************** * Copyright (c) Intel Corporation - All rights reserved. * * This file is part of the LIBXSMM library. * * * * For information on the license, see the LICENSE file. * * Further information: https://github.com/hfp/libxsmm/ * * SPDX-License-Identifier: BSD-3-Clause * ******************************************************************************/ /* Evangelos Georganas (Intel Corp.) ******************************************************************************/ #include <libxsmm.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <math.h> #include <omp.h> #define ALIGNDOWN(N, A) ((N) & ~((A)-1)) #define USE_VECTORIZED_PATH 1 float upconvert_bf16(libxsmm_bfloat16 x) { union libxsmm_bfloat16_hp bf16_hp; bf16_hp.i[1] = x; bf16_hp.i[0] = 0; return bf16_hp.f; } void tpp_groupnorm_fwd_fp32(long NP, long CP, long HW, long CB, long G, long num_HW_blocks, float *pinp, float *pgamma, float *pbeta, float *mean, float *var, float *pout, libxsmm_matrix_eqn_function func10, libxsmm_meltwfunction_unary reduce_HW_kernel, libxsmm_meltwfunction_unary reduce_rows_kernel, libxsmm_meltwfunction_unary reduce_groups_kernel, libxsmm_meltwfunction_unary all_zero_G_kernel, libxsmm_meltwfunction_unary all_zero_kernel, libxsmm_meltwfunction_binary add_kernel, float eps) { LIBXSMM_VLA_DECL(4, float, inp, pinp, CP, HW, CB); /* [NP, CP, HW, CB] */ LIBXSMM_VLA_DECL(4, float, out, pout, CP, HW, CB); LIBXSMM_VLA_DECL(2, float, gamma, pgamma, CB); /* [CP,CB] */ LIBXSMM_VLA_DECL(2, float, beta, pbeta, CB); /* [CP,CB] */ int np, group_size; group_size = (CP*CB)/G; if (group_size <= CB){ int cp; #pragma omp parallel for collapse(2) for(np = 0; np < NP; np++){ for (cp = 0; cp < CP; cp++){ LIBXSMM_ALIGNED(float tmp[2*CB], 64); LIBXSMM_ALIGNED(float sum_X[G], 64); LIBXSMM_ALIGNED(float sum_X2[G], 64); LIBXSMM_ALIGNED(float s[CB], 64); LIBXSMM_ALIGNED(float b[CB], 64); int i, j, hwb, g; libxsmm_matrix_eqn_param eqn_param; libxsmm_meltw_unary_param m_reduce_groups_params, v_reduce_groups_params, reduce_HW_params; libxsmm_meltw_unary_param all_zero_param; libxsmm_meltw_binary_param add_param; libxsmm_matrix_arg arg_array[5]; all_zero_param.out.primary = tmp; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = &tmp[CB]; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = sum_X; all_zero_G_kernel(&all_zero_param); all_zero_param.out.primary = sum_X2; all_zero_G_kernel(&all_zero_param); /*************************** Process entire block code *****************************/ LIBXSMM_ALIGNED(float new_tmp[2*CB], 64); reduce_HW_params.out.primary = new_tmp; /* [2*CB] */ for(hwb=0; hwb < num_HW_blocks; hwb++){ reduce_HW_params.in.primary = &LIBXSMM_VLA_ACCESS(4, inp, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); /* [HW_block, CB] -----> [2 * CB] */ reduce_HW_kernel(&reduce_HW_params); add_param.in0.primary = tmp; add_param.in1.primary = new_tmp; add_param.out.primary = tmp; add_kernel(&add_param); add_param.in0.primary = &tmp[CB]; add_param.in1.primary = &new_tmp[CB]; add_param.out.primary = &tmp[CB]; add_kernel(&add_param); /* for (cb = 0; cb < 2*CB; cb++) { */ /* tmp[cb] += new_tmp[cb]; */ /* } */ } for(i=0; i < CB; i += group_size){ g = (cp*CB + i)/group_size; /* determine current group */ m_reduce_groups_params.in.primary = &tmp[i]; m_reduce_groups_params.out.primary = &sum_X[g]; v_reduce_groups_params.in.primary = &tmp[CB + i]; v_reduce_groups_params.out.primary = &sum_X2[g]; reduce_groups_kernel(&m_reduce_groups_params); reduce_groups_kernel(&v_reduce_groups_params); mean[np*G + g] = sum_X[g] / ((float)group_size * HW); var[np*G + g] = (sum_X2[g] / ((float)group_size * HW)) - (mean[np*G + g]*mean[np*G + g]); /* var = E[X^2] - (E[X])^2 */ for(j = 0; j < group_size; j++){ s[i + j] = 1.0f / ((float)sqrt(var[np*G + g] + eps)); /* 1/sqrt(var(X) + eps) */ b[i + j] = -1 * mean[np*G + g] * s[i + j]; /* -E[X]/sqrt(var(X) + eps) */ } } arg_array[1].primary = s; /* [CB] */ arg_array[2].primary = b; /* [CB] */ arg_array[3].primary = &LIBXSMM_VLA_ACCESS(2, gamma, cp, 0, CB); /* [CB] */ arg_array[4].primary = &LIBXSMM_VLA_ACCESS(2, beta, cp, 0, CB); /* [CB] */ for(hwb=0; hwb < num_HW_blocks; hwb++){ arg_array[0].primary = &LIBXSMM_VLA_ACCESS(4, inp, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); /* [HW, CB] */ eqn_param.inputs = arg_array; eqn_param.output.primary = &LIBXSMM_VLA_ACCESS(4, out, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); /* [HW, CB] */ func10(&eqn_param); /* Normalization equation -> y = ((s*x + b)*gamma + beta) */ } } } } else{ /* Case when group_size > CB */ #pragma omp parallel for for(np = 0; np < NP; np++){ LIBXSMM_ALIGNED(float tmp[2*CB], 64); LIBXSMM_ALIGNED(float sum_X[G], 64); LIBXSMM_ALIGNED(float sum_X2[G], 64); LIBXSMM_ALIGNED(float s[CP*CB], 64); LIBXSMM_ALIGNED(float b[CP*CB], 64); int i, j, cp, hwb, g; float m, v; libxsmm_matrix_eqn_param eqn_param; libxsmm_meltw_unary_param m_reduce_rows_params, v_reduce_rows_params, m_reduce_groups_params, v_reduce_groups_params, reduce_HW_params; libxsmm_meltw_unary_param all_zero_param; libxsmm_meltw_binary_param add_param; libxsmm_matrix_arg arg_array[5]; all_zero_param.out.primary = sum_X; all_zero_G_kernel(&all_zero_param); all_zero_param.out.primary = sum_X2; all_zero_G_kernel(&all_zero_param); LIBXSMM_ALIGNED(float new_tmp[2*CB], 64); for (cp = 0; cp < CP; cp++){ /* [cp, HW, CB] */ all_zero_param.out.primary = tmp; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = &tmp[CB]; all_zero_kernel(&all_zero_param); /* for (cb = 0; cb < 2*CB; cb++) { */ /* tmp[cb] = 0.0f; */ /* } */ reduce_HW_params.out.primary = new_tmp; /* [2*CB] */ for(hwb=0; hwb < num_HW_blocks; hwb++){ reduce_HW_params.in.primary = &LIBXSMM_VLA_ACCESS(4, inp, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); /* [HW, CB] -----> [2 * CB] */ reduce_HW_kernel(&reduce_HW_params); add_param.in0.primary = tmp; add_param.in1.primary = new_tmp; add_param.out.primary = tmp; add_kernel(&add_param); add_param.in0.primary = &tmp[CB]; add_param.in1.primary = &new_tmp[CB]; add_param.out.primary = &tmp[CB]; add_kernel(&add_param); /* #pragma omp simd */ /* for (cb = 0; cb < 2*CB; cb++) { */ /* tmp[cb] += new_tmp[cb]; */ /* } */ } if (group_size >= CB){ /* Group size >= block size (Ex.- CP = 4, CB = 16, G = 2, group_size = 32) */ g = (cp*CB)/group_size; /* determine current group */ m_reduce_rows_params.in.primary = tmp; m_reduce_rows_params.out.primary = &m; v_reduce_rows_params.in.primary = &tmp[CB]; v_reduce_rows_params.out.primary = &v; reduce_rows_kernel(&m_reduce_rows_params); reduce_rows_kernel(&v_reduce_rows_params); sum_X[g] += m; sum_X2[g] += v; } else{ /* Group size < block size (Ex.- CP = 4, CB = 16, G = 32, group_size = 2) */ for(i=0; i < CB; i += group_size){ m_reduce_groups_params.in.primary = &tmp[i]; m_reduce_groups_params.out.primary = &sum_X[cp*(CB/group_size) + (i/group_size)]; v_reduce_groups_params.in.primary = &tmp[CB + i]; v_reduce_groups_params.out.primary = &sum_X2[cp*(CB/group_size) + (i/group_size)]; reduce_groups_kernel(&m_reduce_groups_params); reduce_groups_kernel(&v_reduce_groups_params); } } } for(g = 0; g < G; g++){ /* mean and variance calculation */ mean[np*G + g] = sum_X[g] / ((float)group_size * HW); var[np*G + g] = (sum_X2[g] / ((float)group_size * HW)) - (mean[np*G + g]*mean[np*G + g]); /* var = E[X^2] - (E[X])^2 */ for(j = 0; j < group_size; j++){ s[g*group_size + j] = 1.0f / ((float)sqrt(var[np*G + g] + eps)); /* 1/sqrt(var(X) + eps) */ b[g*group_size + j] = -1 * mean[np*G + g] * s[g*group_size + j]; /* -E[X]/sqrt(var(X) + eps) */ } } for (cp = 0; cp < CP; cp++){ arg_array[1].primary = &s[cp*CB]; /* [CB] */ arg_array[2].primary = &b[cp*CB]; /* [CB] */ arg_array[3].primary = &LIBXSMM_VLA_ACCESS(2, gamma, cp, 0, CB); /* [CB] */ arg_array[4].primary = &LIBXSMM_VLA_ACCESS(2, beta, cp, 0, CB); /* [CB] */ for(hwb=0; hwb < num_HW_blocks; hwb++){ arg_array[0].primary = &LIBXSMM_VLA_ACCESS(4, inp, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); /* [HW, CB] */ eqn_param.inputs = arg_array; eqn_param.output.primary = &LIBXSMM_VLA_ACCESS(4, out, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); /* [HW,CB] */ func10(&eqn_param); /* Normalization equation -> y = ((s*x + b)*gamma + beta) */ } } } } } void tpp_groupnorm_fwd_bf16(long NP, long CP, long HW, long CB, long G, long num_HW_blocks, libxsmm_bfloat16 *pinp, libxsmm_bfloat16 *pgamma, libxsmm_bfloat16 *pbeta, float *mean, float *var, libxsmm_bfloat16 *pout, libxsmm_matrix_eqn_function func10, libxsmm_meltwfunction_unary reduce_HW_kernel, libxsmm_meltwfunction_unary reduce_rows_kernel, libxsmm_meltwfunction_unary reduce_groups_kernel, libxsmm_meltwfunction_unary all_zero_G_kernel, libxsmm_meltwfunction_unary all_zero_kernel, libxsmm_meltwfunction_binary add_kernel, float eps) { LIBXSMM_VLA_DECL(4, libxsmm_bfloat16, inp, pinp, CP, HW, CB); /* [NP, CP, HW, CB] */ LIBXSMM_VLA_DECL(4, libxsmm_bfloat16, out, pout, CP, HW, CB); LIBXSMM_VLA_DECL(2, libxsmm_bfloat16, gamma, pgamma, CB); LIBXSMM_VLA_DECL(2, libxsmm_bfloat16, beta, pbeta, CB); int np, group_size; group_size = (CP*CB)/G; if (group_size <= CB){ int cp; #pragma omp parallel for collapse(2) for(np = 0; np < NP; np++){ for (cp = 0; cp < CP; cp++){ LIBXSMM_ALIGNED(float tmp[2*CB], 64); LIBXSMM_ALIGNED(float sum_X[G], 64); LIBXSMM_ALIGNED(float sum_X2[G], 64); LIBXSMM_ALIGNED(float s[CB], 64); LIBXSMM_ALIGNED(float b[CB], 64); int i, j, hwb, g; libxsmm_matrix_eqn_param eqn_param; libxsmm_meltw_unary_param m_reduce_groups_params, v_reduce_groups_params, reduce_HW_params; libxsmm_meltw_unary_param all_zero_param; libxsmm_meltw_binary_param add_param; libxsmm_matrix_arg arg_array[5]; all_zero_param.out.primary = tmp; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = &tmp[CB]; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = sum_X; all_zero_G_kernel(&all_zero_param); all_zero_param.out.primary = sum_X2; all_zero_G_kernel(&all_zero_param); /*************************** Process entire block code *****************************/ LIBXSMM_ALIGNED(float new_tmp[2*CB], 64); reduce_HW_params.out.primary = new_tmp; /* [2*CB] */ for(hwb=0; hwb < num_HW_blocks; hwb++){ reduce_HW_params.in.primary = &LIBXSMM_VLA_ACCESS(4, inp, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); /* [HW_block, CB] -----> [2 * CB] */ reduce_HW_kernel(&reduce_HW_params); add_param.in0.primary = tmp; add_param.in1.primary = new_tmp; add_param.out.primary = tmp; add_kernel(&add_param); add_param.in0.primary = &tmp[CB]; add_param.in1.primary = &new_tmp[CB]; add_param.out.primary = &tmp[CB]; add_kernel(&add_param); /* for (cb = 0; cb < 2*CB; cb++) { */ /* tmp[cb] += new_tmp[cb]; */ /* } */ } for(i=0; i < CB; i += group_size){ g = (cp*CB + i)/group_size; /* determine current group */ m_reduce_groups_params.in.primary = &tmp[i]; m_reduce_groups_params.out.primary = &sum_X[g]; v_reduce_groups_params.in.primary = &tmp[CB + i]; v_reduce_groups_params.out.primary = &sum_X2[g]; reduce_groups_kernel(&m_reduce_groups_params); reduce_groups_kernel(&v_reduce_groups_params); mean[np*G + g] = sum_X[g] / ((float)group_size * HW); var[np*G + g] = (sum_X2[g] / ((float)group_size * HW)) - (mean[np*G + g]*mean[np*G + g]); /* var = E[X^2] - (E[X])^2 */ for(j = 0; j < group_size; j++){ s[i + j] = 1.0f / ((float)sqrt(var[np*G + g] + eps)); /* 1/sqrt(var(X) + eps) */ b[i + j] = -1 * mean[np*G + g] * s[i + j]; /* -E[X]/sqrt(var(X) + eps) */ } } arg_array[1].primary = s; /* [CB] */ arg_array[2].primary = b; /* [CB] */ arg_array[3].primary = &LIBXSMM_VLA_ACCESS(2, gamma, cp, 0, CB); /* [CB] */ arg_array[4].primary = &LIBXSMM_VLA_ACCESS(2, beta, cp, 0, CB); /* [CB] */ for(hwb=0; hwb < num_HW_blocks; hwb++){ arg_array[0].primary = &LIBXSMM_VLA_ACCESS(4, inp, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); /* [HW, CB] */ eqn_param.inputs = arg_array; eqn_param.output.primary = &LIBXSMM_VLA_ACCESS(4, out, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); /* [HW, CB] */ func10(&eqn_param); /* Normalization equation -> y = ((s*x + b)*gamma + beta) */ } } } } else{ #pragma omp parallel for for(np = 0; np < NP; np++){ LIBXSMM_ALIGNED(float tmp[2*CB], 64); LIBXSMM_ALIGNED(float sum_X[G], 64); LIBXSMM_ALIGNED(float sum_X2[G], 64); LIBXSMM_ALIGNED(float s[CP*CB], 64); LIBXSMM_ALIGNED(float b[CP*CB], 64); int i, j, cp, g, hwb; float m, v; libxsmm_matrix_eqn_param eqn_param; libxsmm_meltw_unary_param m_reduce_rows_params, m_reduce_groups_params, v_reduce_rows_params, v_reduce_groups_params, reduce_HW_params; libxsmm_meltw_unary_param all_zero_param; libxsmm_meltw_binary_param add_param; libxsmm_matrix_arg arg_array[5]; all_zero_param.out.primary = sum_X; all_zero_G_kernel(&all_zero_param); all_zero_param.out.primary = sum_X2; all_zero_G_kernel(&all_zero_param); LIBXSMM_ALIGNED(float new_tmp[2*CB], 64); for (cp = 0; cp < CP; cp++){ /* [cp, HW, CB] */ all_zero_param.out.primary = tmp; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = &tmp[CB]; all_zero_kernel(&all_zero_param); /* #pragma omp simd */ /* for (cb = 0; cb < 2*CB; cb++) { */ /* tmp[cb] = 0.0f; */ /* } */ reduce_HW_params.out.primary = new_tmp; /* [2*CB] */ for(hwb=0; hwb < num_HW_blocks; hwb++){ reduce_HW_params.in.primary = &LIBXSMM_VLA_ACCESS(4, inp, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); /* [HW, CB] -----> [2 * CB] */ reduce_HW_kernel(&reduce_HW_params); add_param.in0.primary = tmp; add_param.in1.primary = new_tmp; add_param.out.primary = tmp; add_kernel(&add_param); add_param.in0.primary = &tmp[CB]; add_param.in1.primary = &new_tmp[CB]; add_param.out.primary = &tmp[CB]; add_kernel(&add_param); /* #pragma omp simd for (cb = 0; cb < 2*CB; cb++) { tmp[cb] += new_tmp[cb]; } */ } if (group_size >= CB){ /* Group size >= block size (Ex.- CP = 4, CB = 16, G = 2, group_size = 32) */ g = (cp*CB)/group_size; /* determine current group */ m_reduce_rows_params.in.primary = tmp; m_reduce_rows_params.out.primary = &m; v_reduce_rows_params.in.primary = &tmp[CB]; v_reduce_rows_params.out.primary = &v; reduce_rows_kernel(&m_reduce_rows_params); reduce_rows_kernel(&v_reduce_rows_params); sum_X[g] += m; sum_X2[g] += v; } else{ /* Group size < block size (Ex.- CP = 4, CB = 16, G = 32, group_size = 2) */ for(i=0; i < CB; i += group_size){ m_reduce_groups_params.in.primary = &tmp[i]; m_reduce_groups_params.out.primary = &sum_X[cp*(CB/group_size) + (i/group_size)]; v_reduce_groups_params.in.primary = &tmp[CB + i]; v_reduce_groups_params.out.primary = &sum_X2[cp*(CB/group_size) + (i/group_size)]; reduce_groups_kernel(&m_reduce_groups_params); reduce_groups_kernel(&v_reduce_groups_params); } } } for(g = 0; g < G; g++){ /* mean and variance calculation */ mean[np*G + g] = sum_X[g] / ((float)group_size * HW); var[np*G + g] = (sum_X2[g] / ((float)group_size * HW)) - (mean[np*G + g]*mean[np*G + g]); /* var = E[X^2] - (E[X])^2 */ for(j = 0; j < group_size; j++){ s[g*group_size + j] = 1.0f / ((float)sqrt(var[np*G + g] + eps)); /* 1/sqrt(var(X) + eps) */ b[g*group_size + j] = -1 * mean[np*G + g] * s[g*group_size + j]; /* -E[X]/sqrt(var(X) + eps) */ } } for (cp = 0; cp < CP; cp++){ arg_array[1].primary = &s[cp*CB]; /* [CB] */ arg_array[2].primary = &b[cp*CB]; /* [CB] */ arg_array[3].primary = &LIBXSMM_VLA_ACCESS(2, gamma, cp, 0, CB); /* [CB] */ arg_array[4].primary = &LIBXSMM_VLA_ACCESS(2, beta, cp, 0, CB); /* [CB] */ for(hwb=0; hwb < num_HW_blocks; hwb++){ arg_array[0].primary = &LIBXSMM_VLA_ACCESS(4, inp, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); /* [HW, CB] */ eqn_param.inputs = arg_array; eqn_param.output.primary = &LIBXSMM_VLA_ACCESS(4, out, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); /* [HW,CB] */ func10(&eqn_param); /* Normalization equation -> y = ((s*x + b)*gamma + beta) */ } } } } } void tpp_groupnorm_bwd_fp32(long NP, long CP, long HW, long CB, long G, long num_HW_blocks, float *pdout, float *pinp, float *mean, float *var, float *pgamma, float *pdin, float *pdgamma, float *pdbeta, libxsmm_matrix_eqn_function dgamma_func, libxsmm_matrix_eqn_function dbeta_func, libxsmm_matrix_eqn_function db_func, libxsmm_matrix_eqn_function ds_func, libxsmm_matrix_eqn_function din_func, libxsmm_meltwfunction_unary all_zero_kernel, libxsmm_meltwfunction_binary add_kernel, float eps) { int group_size; group_size = (CP*CB)/G; const float scale = 1.0f / ((float)group_size * HW); LIBXSMM_VLA_DECL(4, float, din, pdin, CP, HW, CB); LIBXSMM_VLA_DECL(4, float, inp, pinp, CP, HW, CB); LIBXSMM_VLA_DECL(4, float, dout, pdout, CP, HW, CB); LIBXSMM_VLA_DECL(2, float, gamma, pgamma, CB); LIBXSMM_VLA_DECL(2, float, dgamma, pdgamma, CB); LIBXSMM_VLA_DECL(2, float, dbeta, pdbeta, CB); LIBXSMM_ALIGNED(float dgamma_NP[NP*CP*CB], 64); LIBXSMM_ALIGNED(float dbeta_NP[NP*CP*CB], 64); if (group_size <= CB){ #pragma omp parallel { LIBXSMM_ALIGNED(float a[CB], 64); LIBXSMM_ALIGNED(float b[CB], 64); LIBXSMM_ALIGNED(float c[CB], 64); LIBXSMM_ALIGNED(float ds[CB], 64); LIBXSMM_ALIGNED(float db[CB], 64); int np, cp; #pragma omp for collapse(2) for (np = 0; np < NP; np++){ for (cp = 0; cp < CP; cp++) { int j, g, hwb, lg; libxsmm_matrix_eqn_param eqn_param; libxsmm_meltw_unary_param all_zero_param; libxsmm_matrix_arg arg_array[10]; eqn_param.inputs = arg_array; /* for(j = 0; j < CB; j++){ dgamma_NP[np*CP*CB + cp*CB + j] = 0.0f; dbeta_NP[np*CP*CB + cp*CB + j] = 0.0f; } */ all_zero_param.out.primary = &dgamma_NP[np*CP*CB + cp*CB]; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = &dbeta_NP[np*CP*CB + cp*CB]; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = ds; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = db; all_zero_kernel(&all_zero_param); for(g = (cp*CB)/group_size; g < ((cp+1)*CB)/group_size; g++){ /* compute a and b for each channel from group means and variance */ lg = g - (cp*CB)/group_size; for(j = 0; j < group_size; j++){ a[lg*group_size + j] = 1.0f / ((float)sqrt(var[np*G + g] + eps)); b[lg*group_size + j] = -a[lg*group_size + j]*mean[np*G + g]; } } arg_array[1].primary = a; arg_array[2].primary = b; arg_array[4].primary = &dgamma_NP[np*CP*CB + cp*CB]; arg_array[5].primary = &dbeta_NP[np*CP*CB + cp*CB]; arg_array[6].primary = &LIBXSMM_VLA_ACCESS(2, gamma, cp, 0, CB); arg_array[8].primary = ds; arg_array[9].primary = db; for(hwb=0; hwb < num_HW_blocks; hwb++){ arg_array[0].primary = &LIBXSMM_VLA_ACCESS(4, inp, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); arg_array[3].primary = &LIBXSMM_VLA_ACCESS(4, dout, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); eqn_param.output.primary = ds; ds_func(&eqn_param); eqn_param.output.primary = db; db_func(&eqn_param); eqn_param.output.primary = &dgamma_NP[np*CP*CB + cp*CB]; dgamma_func(&eqn_param); eqn_param.output.primary = &dbeta_NP[np*CP*CB + cp*CB]; dbeta_func(&eqn_param); } /* b = (db * mean[nb] - ds) * a * a * a * scale; */ /* c = -b * mean[nb] - db * a * scale; */ for(g = (cp*CB)/group_size; g < ((cp+1)*CB)/group_size; g++){ /* compute b and c for each channel from group means and variance */ lg = g - (cp*CB)/group_size; float gds = 0.0f; float gdb = 0.0f; for(j = 0; j < group_size; j++){ gds += ds[lg*group_size + j]; /* Group ds and db calculation */ gdb += db[lg*group_size + j]; } for(j = 0; j < group_size; j++){ b[lg*group_size + j] = (gdb * mean[np*G + g] - gds) * a[lg*group_size + j] * a[lg*group_size + j] * a[lg*group_size + j] * scale; c[lg*group_size + j] = -b[lg*group_size + j] * mean[np*G + g] - gdb * a[lg*group_size + j] * scale; } } arg_array[1].primary = a; arg_array[2].primary = b; arg_array[6].primary = &LIBXSMM_VLA_ACCESS(2, gamma, cp, 0, CB); arg_array[7].primary = c; for(hwb=0; hwb < num_HW_blocks; hwb++){ arg_array[0].primary = &LIBXSMM_VLA_ACCESS(4, inp, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); arg_array[3].primary = &LIBXSMM_VLA_ACCESS(4, dout, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); eqn_param.output.primary = &LIBXSMM_VLA_ACCESS(4, din, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); din_func(&eqn_param); } } } #pragma omp for for (cp = 0; cp < CP; cp++) { for (np=0; np < NP; np++ ) { int cb; for(cb = 0; cb < CB; cb++){ LIBXSMM_VLA_ACCESS(2, dgamma, cp, cb, CB) += dgamma_NP[np*CP*CB + cp*CB + cb]; LIBXSMM_VLA_ACCESS(2, dbeta, cp, cb, CB) += dbeta_NP[np*CP*CB + cp*CB + cb]; } } } } } else{ #pragma omp parallel { LIBXSMM_ALIGNED(float a[CP*CB], 64); LIBXSMM_ALIGNED(float b[CP*CB], 64); LIBXSMM_ALIGNED(float c[CP*CB], 64); LIBXSMM_ALIGNED(float ds[CP*CB], 64); LIBXSMM_ALIGNED(float db[CP*CB], 64); int np; #pragma omp for for (np = 0; np < NP; np++) { int j, g, cp, hwb; libxsmm_matrix_eqn_param eqn_param; libxsmm_meltw_unary_param all_zero_param; libxsmm_matrix_arg arg_array[10]; eqn_param.inputs = arg_array; /* for(j = 0; j < CP*CB; j++){ */ /* dgamma_NP[np*CP*CB + j] = 0.0f; */ /* dbeta_NP[np*CP*CB + j] = 0.0f; */ /* } */ for (cp = 0; cp < CP; cp++) { all_zero_param.out.primary = &dgamma_NP[np*CP*CB + cp*CB]; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = &dbeta_NP[np*CP*CB + cp*CB]; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = &ds[cp*CB]; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = &db[cp*CB]; all_zero_kernel(&all_zero_param); } for(g = 0; g < G; g++){ /* compute a and b for each channel from group means and variance */ for(j = 0; j < group_size; j++){ a[g*group_size + j] = 1.0f / ((float)sqrt(var[np*G + g] + eps)); b[g*group_size + j] = -a[g*group_size + j]*mean[np*G + g]; } } for (cp = 0; cp < CP; cp++) { arg_array[1].primary = &a[cp*CB]; arg_array[2].primary = &b[cp*CB]; arg_array[4].primary = &dgamma_NP[np*CP*CB + cp*CB]; arg_array[5].primary = &dbeta_NP[np*CP*CB + cp*CB]; arg_array[6].primary = &LIBXSMM_VLA_ACCESS(2, gamma, cp, 0, CB); arg_array[8].primary = &ds[cp*CB]; arg_array[9].primary = &db[cp*CB]; for(hwb=0; hwb < num_HW_blocks; hwb++){ arg_array[0].primary = &LIBXSMM_VLA_ACCESS(4, inp, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); arg_array[3].primary = &LIBXSMM_VLA_ACCESS(4, dout, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); eqn_param.output.primary = &ds[cp*CB]; ds_func(&eqn_param); eqn_param.output.primary = &db[cp*CB]; db_func(&eqn_param); eqn_param.output.primary = &dgamma_NP[np*CP*CB + cp*CB]; dgamma_func(&eqn_param); eqn_param.output.primary = &dbeta_NP[np*CP*CB + cp*CB]; dbeta_func(&eqn_param); } } /* b = (db * mean[nb] - ds) * a * a * a * scale; */ /* c = -b * mean[nb] - db * a * scale; */ for(g = 0; g < G; g++){ /* compute b and c for each channel from group means and variance */ float gds = 0.0f; float gdb = 0.0f; for(j = 0; j < group_size; j++){ gds += ds[g*group_size + j]; /* Group ds and db calculation */ gdb += db[g*group_size + j]; } for(j = 0; j < group_size; j++){ b[g*group_size + j] = (gdb * mean[np*G + g] - gds) * a[g*group_size + j] * a[g*group_size + j] * a[g*group_size + j] * scale; c[g*group_size + j] = -b[g*group_size + j] * mean[np*G + g] - gdb * a[g*group_size + j] * scale; } } for (cp = 0; cp < CP; cp++) { arg_array[1].primary = &a[cp*CB]; arg_array[2].primary = &b[cp*CB]; arg_array[6].primary = &LIBXSMM_VLA_ACCESS(2, gamma, cp, 0, CB); arg_array[7].primary = &c[cp*CB]; for(hwb=0; hwb < num_HW_blocks; hwb++){ arg_array[0].primary = &LIBXSMM_VLA_ACCESS(4, inp, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); arg_array[3].primary = &LIBXSMM_VLA_ACCESS(4, dout, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); eqn_param.output.primary = &LIBXSMM_VLA_ACCESS(4, din, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); din_func(&eqn_param); } } } int cp; #pragma omp for for (cp = 0; cp < CP; cp++) { for (np=0; np < NP; np++ ) { int cb; for(cb = 0; cb < CB; cb++){ LIBXSMM_VLA_ACCESS(2, dgamma, cp, cb, CB) += dgamma_NP[np*CP*CB + cp*CB + cb]; LIBXSMM_VLA_ACCESS(2, dbeta, cp, cb, CB) += dbeta_NP[np*CP*CB + cp*CB + cb]; } } } } } } void tpp_groupnorm_bwd_bf16(long NP, long CP, long HW, long CB, long G, long num_HW_blocks, libxsmm_bfloat16 *pdout, libxsmm_bfloat16 *pinp, float *mean, float *var, libxsmm_bfloat16 *pgamma, libxsmm_bfloat16 *pdin, float *pdgamma, float *pdbeta, libxsmm_matrix_eqn_function dgamma_func, libxsmm_matrix_eqn_function dbeta_func, libxsmm_matrix_eqn_function db_func, libxsmm_matrix_eqn_function ds_func, libxsmm_matrix_eqn_function din_func, libxsmm_meltwfunction_unary all_zero_kernel, libxsmm_meltwfunction_binary add_kernel, float eps) { int group_size; group_size = (CP*CB)/G; const float scale = 1.0f / ((float)group_size*HW); LIBXSMM_VLA_DECL(4, libxsmm_bfloat16, din, pdin, CP, HW, CB); LIBXSMM_VLA_DECL(4, libxsmm_bfloat16, inp, pinp, CP, HW, CB); LIBXSMM_VLA_DECL(4, libxsmm_bfloat16, dout, pdout, CP, HW, CB); LIBXSMM_VLA_DECL(2, libxsmm_bfloat16, gamma, pgamma, CB); LIBXSMM_VLA_DECL(2, float, dgamma, pdgamma, CB); LIBXSMM_VLA_DECL(2, float, dbeta, pdbeta, CB); LIBXSMM_ALIGNED(float dgamma_NP[NP*CP*CB], 64); LIBXSMM_ALIGNED(float dbeta_NP[NP*CP*CB], 64); if (group_size <= CB){ #pragma omp parallel { LIBXSMM_ALIGNED(float a[CB], 64); LIBXSMM_ALIGNED(float b[CB], 64); LIBXSMM_ALIGNED(float c[CB], 64); LIBXSMM_ALIGNED(float ds[CB], 64); LIBXSMM_ALIGNED(float db[CB], 64); int np, cp; #pragma omp for collapse(2) for (np = 0; np < NP; np++){ for (cp = 0; cp < CP; cp++) { int j, g, hwb, lg; libxsmm_matrix_eqn_param eqn_param; libxsmm_meltw_unary_param all_zero_param; libxsmm_matrix_arg arg_array[10]; eqn_param.inputs = arg_array; all_zero_param.out.primary = &dgamma_NP[np*CP*CB + cp*CB]; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = &dbeta_NP[np*CP*CB + cp*CB]; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = ds; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = db; all_zero_kernel(&all_zero_param); for(g = (cp*CB)/group_size; g < ((cp+1)*CB)/group_size; g++){ /* compute a and b for each channel from group means and variance */ lg = g - (cp*CB)/group_size; for(j = 0; j < group_size; j++){ a[lg*group_size + j] = 1.0f / ((float)sqrt(var[np*G + g] + eps)); b[lg*group_size + j] = -a[lg*group_size + j]*mean[np*G + g]; } } arg_array[1].primary = a; arg_array[2].primary = b; arg_array[4].primary = &dgamma_NP[np*CP*CB + cp*CB]; arg_array[5].primary = &dbeta_NP[np*CP*CB + cp*CB]; arg_array[6].primary = &LIBXSMM_VLA_ACCESS(2, gamma, cp, 0, CB); arg_array[8].primary = ds; arg_array[9].primary = db; for(hwb=0; hwb < num_HW_blocks; hwb++){ arg_array[0].primary = &LIBXSMM_VLA_ACCESS(4, inp, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); arg_array[3].primary = &LIBXSMM_VLA_ACCESS(4, dout, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); eqn_param.output.primary = ds; ds_func(&eqn_param); eqn_param.output.primary = db; db_func(&eqn_param); eqn_param.output.primary = &dgamma_NP[np*CP*CB + cp*CB]; dgamma_func(&eqn_param); eqn_param.output.primary = &dbeta_NP[np*CP*CB + cp*CB]; dbeta_func(&eqn_param); } /* b = (db * mean[nb] - ds) * a * a * a * scale; */ /* c = -b * mean[nb] - db * a * scale; */ for(g = (cp*CB)/group_size; g < ((cp+1)*CB)/group_size; g++){ /* compute b and c for each channel from group means and variance */ lg = g - (cp*CB)/group_size; float gds = 0.0f; float gdb = 0.0f; for(j = 0; j < group_size; j++){ gds += ds[lg*group_size + j]; /* Group ds and db calculation */ gdb += db[lg*group_size + j]; } for(j = 0; j < group_size; j++){ b[lg*group_size + j] = (gdb * mean[np*G + g] - gds) * a[lg*group_size + j] * a[lg*group_size + j] * a[lg*group_size + j] * scale; c[lg*group_size + j] = -b[lg*group_size + j] * mean[np*G + g] - gdb * a[lg*group_size + j] * scale; } } arg_array[1].primary = a; arg_array[2].primary = b; arg_array[6].primary = &LIBXSMM_VLA_ACCESS(2, gamma, cp, 0, CB); arg_array[7].primary = c; for(hwb=0; hwb < num_HW_blocks; hwb++){ arg_array[0].primary = &LIBXSMM_VLA_ACCESS(4, inp, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); arg_array[3].primary = &LIBXSMM_VLA_ACCESS(4, dout, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); eqn_param.output.primary = &LIBXSMM_VLA_ACCESS(4, din, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); din_func(&eqn_param); } } } #pragma omp for for (cp = 0; cp < CP; cp++) { for (np=0; np < NP; np++ ) { int cb; for(cb = 0; cb < CB; cb++){ LIBXSMM_VLA_ACCESS(2, dgamma, cp, cb, CB) += dgamma_NP[np*CP*CB + cp*CB + cb]; LIBXSMM_VLA_ACCESS(2, dbeta, cp, cb, CB) += dbeta_NP[np*CP*CB + cp*CB + cb]; } } } } } else{ #pragma omp parallel { LIBXSMM_ALIGNED(float a[CP*CB], 64); LIBXSMM_ALIGNED(float b[CP*CB], 64); LIBXSMM_ALIGNED(float c[CP*CB], 64); LIBXSMM_ALIGNED(float ds[CP*CB], 64); LIBXSMM_ALIGNED(float db[CP*CB], 64); int np; #pragma omp for for (np = 0; np < NP; np++) { int j, g, cp, hwb; libxsmm_matrix_eqn_param eqn_param; libxsmm_meltw_unary_param all_zero_param; libxsmm_matrix_arg arg_array[10]; eqn_param.inputs = arg_array; for (cp = 0; cp < CP; cp++) { all_zero_param.out.primary = &dgamma_NP[np*CP*CB + cp*CB]; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = &dbeta_NP[np*CP*CB + cp*CB]; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = &ds[cp*CB]; all_zero_kernel(&all_zero_param); all_zero_param.out.primary = &db[cp*CB]; all_zero_kernel(&all_zero_param); } for(g = 0; g < G; g++){ /* compute a and b for each channel from group means and variance */ for(j = 0; j < group_size; j++){ a[g*group_size + j] = 1.0f / ((float)sqrt(var[np*G + g] + eps)); b[g*group_size + j] = -a[g*group_size + j]*mean[np*G + g]; } } for (cp = 0; cp < CP; cp++) { arg_array[1].primary = &a[cp*CB]; arg_array[2].primary = &b[cp*CB]; arg_array[4].primary = &dgamma_NP[np*CP*CB + cp*CB]; arg_array[5].primary = &dbeta_NP[np*CP*CB + cp*CB]; arg_array[6].primary = &LIBXSMM_VLA_ACCESS(2, gamma, cp, 0, CB); arg_array[8].primary = &ds[cp*CB]; arg_array[9].primary = &db[cp*CB]; for(hwb=0; hwb < num_HW_blocks; hwb++){ arg_array[0].primary = &LIBXSMM_VLA_ACCESS(4, inp, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); arg_array[3].primary = &LIBXSMM_VLA_ACCESS(4, dout, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); eqn_param.output.primary = &ds[cp*CB]; ds_func(&eqn_param); eqn_param.output.primary = &db[cp*CB]; db_func(&eqn_param); eqn_param.output.primary = &dgamma_NP[np*CP*CB + cp*CB]; dgamma_func(&eqn_param); eqn_param.output.primary = &dbeta_NP[np*CP*CB + cp*CB]; dbeta_func(&eqn_param); } } /* b = (db * mean[nb] - ds) * a * a * a * scale; */ /* c = -b * mean[nb] - db * a * scale; */ for(g = 0; g < G; g++){ /* compute b and c for each channel from group means and variance */ float gds = 0.0f; float gdb = 0.0f; for(j = 0; j < group_size; j++){ gds += ds[g*group_size + j]; /* Group ds and db calculation */ gdb += db[g*group_size + j]; } for(j = 0; j < group_size; j++){ b[g*group_size + j] = (gdb * mean[np*G + g] - gds) * a[g*group_size + j] * a[g*group_size + j] * a[g*group_size + j] * scale; c[g*group_size + j] = -b[g*group_size + j] * mean[np*G + g] - gdb * a[g*group_size + j] * scale; } } for (cp = 0; cp < CP; cp++) { arg_array[1].primary = &a[cp*CB]; arg_array[2].primary = &b[cp*CB]; arg_array[6].primary = &LIBXSMM_VLA_ACCESS(2, gamma, cp, 0, CB); arg_array[7].primary = &c[cp*CB]; for(hwb=0; hwb < num_HW_blocks; hwb++){ arg_array[0].primary = &LIBXSMM_VLA_ACCESS(4, inp, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); arg_array[3].primary = &LIBXSMM_VLA_ACCESS(4, dout, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); eqn_param.output.primary = &LIBXSMM_VLA_ACCESS(4, din, np, cp, hwb*(HW/num_HW_blocks), 0, CP, HW, CB); din_func(&eqn_param); } } } int cp; #pragma omp for for (cp = 0; cp < CP; cp++) { for (np=0; np < NP; np++ ) { int cb; for(cb = 0; cb < CB; cb++){ LIBXSMM_VLA_ACCESS(2, dgamma, cp, cb, CB) += dgamma_NP[np*CP*CB + cp*CB + cb]; LIBXSMM_VLA_ACCESS(2, dbeta, cp, cb, CB) += dbeta_NP[np*CP*CB + cp*CB + cb]; } } } } } } void scaler_groupnorm_fwd_fp32(long NP, long CP, long HW, long CB, long G, float *pinp, float *pgamma, float *pbeta, float *mean, float *var, float *pout, float eps){ LIBXSMM_VLA_DECL(4, float, inp, pinp, CP, HW, CB); /* [NP, CP, HW, CB] */ LIBXSMM_VLA_DECL(4, float, out, pout, CP, HW, CB); LIBXSMM_VLA_DECL(2, float, gamma, pgamma, CB); LIBXSMM_VLA_DECL(2, float, beta, pbeta, CB); int np, group_size; group_size = (CP*CB)/G; #pragma omp parallel for for(np = 0; np < NP; np++){ LIBXSMM_ALIGNED(float sum_X[G], 64); LIBXSMM_ALIGNED(float sum_X2[G], 64); LIBXSMM_ALIGNED(float s[CP*CB], 64); LIBXSMM_ALIGNED(float b[CP*CB], 64); int i, j, cp, cb, hw, g; float m, v, value; for(g = 0; g < G; g++){ sum_X[g] = 0.0f; sum_X2[g] = 0.0f; } for(cp = 0; cp < CP; cp++){ /* Size = CP*HW*CB*4 */ m = 0.0f; v = 0.0f; if (group_size >= CB){ /* Group size >= block size (Ex.- CP = 4, CB = 16, G = 2, group_size = 32) */ for(cb = 0; cb < CB; cb++){ for(hw = 0; hw < HW; hw++){ value = LIBXSMM_VLA_ACCESS(4, inp, np, cp, hw, cb, CP, HW, CB); m += value; v += (value*value); } } g = (cp*CB)/group_size; /* determine current group */ sum_X[g] += m; sum_X2[g] += v; } else{ for(i=0; i < CB; i += group_size){ /* Group size < block size (Ex.- CP = 4, CB = 16, G = 32, group_size = 2) */ for(j = 0; j < group_size; j++){ for(hw = 0; hw < HW; hw++){ value = LIBXSMM_VLA_ACCESS(4, inp, np, cp, hw, (i + j), CP, HW, CB); sum_X[cp*(CB/group_size) + (i/group_size)] += value; sum_X2[cp*(CB/group_size) + (i/group_size)] += (value*value); } } } } } for(g = 0; g < G; g++){ /* mean and variance calculation */ /* Size = 2*CP*CB*4 */ mean[np*G + g] = sum_X[g] / ((float)group_size * HW); var[np*G + g] = (sum_X2[g] / ((float)group_size * HW)) - (mean[np*G + g]*mean[np*G + g]); /* var = E[X^2] - (E[X])^2 [G] */ for(j = 0; j < group_size; j++){ s[g*group_size + j] = 1.0f / ((float)sqrt(var[np*G + g] + eps)); /* s = 1/sqrt(var(X) + eps) [CP, CB] */ b[g*group_size + j] = -1 * mean[np*G + g] * s[g*group_size + j]; /* b = -E[X]/sqrt(var(X) + eps) [CP, CB] */ } } for(cp = 0; cp < CP; cp++){ /* Size = 2*CP*HW*CB*4 + 2*CP*CB*4 */ for(cb = 0; cb < CB; cb++){ for(hw = 0; hw < HW; hw++){ value = LIBXSMM_VLA_ACCESS(4, inp, np, cp, hw, cb, CP, HW, CB); value = ((value * s[cp*CB + cb]) + b[cp*CB + cb]) * LIBXSMM_VLA_ACCESS(2, gamma, cp, cb, CB) + LIBXSMM_VLA_ACCESS(2, beta, cp, cb, CB); /* Normalization equation -> y = ((s*x + b)*gamma + beta) */ LIBXSMM_VLA_ACCESS(4, out, np, cp, hw, cb, CP, HW, CB) = value; } } } } /*End multithreading loop*/ } void scaler_groupnorm_bwd_fp32(long NP, long CP, long HW, long CB, long G, float *pdout, float *pinp, float *mean, float *var, float *pgamma, float *pdin, float *pdgamma, float *pdbeta, float eps) { int np, group_size; group_size = (CP*CB)/G; float scale = 1.0f / ((float)group_size * HW); LIBXSMM_VLA_DECL(4, float, din, pdin, CP, HW, CB); LIBXSMM_VLA_DECL(4, float, inp, pinp, CP, HW, CB); LIBXSMM_VLA_DECL(4, float, dout, pdout, CP, HW, CB); LIBXSMM_VLA_DECL(2, float, gamma, pgamma, CB); LIBXSMM_VLA_DECL(2, float, dgamma, pdgamma, CB); LIBXSMM_VLA_DECL(2, float, dbeta, pdbeta, CB); LIBXSMM_ALIGNED(float dgamma_NP[NP*CP*CB], 64); LIBXSMM_ALIGNED(float dbeta_NP[NP*CP*CB], 64); #pragma omp parallel for for(np = 0; np < NP; np++){ int j, cp, cb, hw, g; LIBXSMM_ALIGNED(float a[CP*CB], 64); LIBXSMM_ALIGNED(float b[CP*CB], 64); LIBXSMM_ALIGNED(float c[CP*CB], 64); LIBXSMM_ALIGNED(float ds[CP*CB], 64); LIBXSMM_ALIGNED(float db[CP*CB], 64); for(j = 0; j < CP*CB; j++){ dgamma_NP[np*CP*CB + j] = 0.0f; dbeta_NP[np*CP*CB + j] = 0.0f; } for(g = 0; g < G; g++){ /* compute a and b for each channel from group means and variance */ for(j = 0; j < group_size; j++){ a[g*group_size + j] = 1.0f / ((float)sqrt(var[np*G + g] + eps)); b[g*group_size + j] = -a[g*group_size + j]*mean[np*G + g]; ds[g*group_size + j] = 0.0f; db[g*group_size + j] = 0.0f; } } for (cp = 0; cp < CP; cp++) { /* dgamma += (a * inp + b) * dout , dbeta += dout, ds += dout * gamma * inp, db += dout * gamma */ /* Size = 2*CP*HW*CB*4 */ for (cb = 0; cb < CB; cb++) { for (hw = 0; hw < HW; hw++){ dgamma_NP[np*CP*CB + cp*CB + cb] += (a[cp*CB + cb] * LIBXSMM_VLA_ACCESS(4, inp, np, cp, hw, cb, CP, HW, CB) + b[cp*CB + cb]) * LIBXSMM_VLA_ACCESS(4, dout, np, cp, hw, cb, CP, HW, CB); dbeta_NP[np*CP*CB + cp*CB + cb] += LIBXSMM_VLA_ACCESS(4, dout, np, cp, hw, cb, CP, HW, CB); ds[cp*CB + cb] += LIBXSMM_VLA_ACCESS(4, dout, np, cp, hw, cb, CP, HW, CB) * LIBXSMM_VLA_ACCESS(2, gamma, cp, cb, CB) * LIBXSMM_VLA_ACCESS(4, inp, np, cp, hw, cb, CP, HW, CB); db[cp*CB + cb] += LIBXSMM_VLA_ACCESS(4, dout, np, cp, hw, cb, CP, HW, CB) * LIBXSMM_VLA_ACCESS(2, gamma, cp, cb, CB); } } } /* b = (db * mean[nb] - ds) * a * a * a * scale; */ /* c = -b * mean[nb] - db * a * scale; */ for(g = 0; g < G; g++){ /* compute b and c for each channel from group means and variance */ float gds = 0.0f; float gdb = 0.0f; for(j = 0; j < group_size; j++){ gds += ds[g*group_size + j]; /* Group ds and db calculation */ gdb += db[g*group_size + j]; } for(j = 0; j < group_size; j++){ b[g*group_size + j] = (gdb * mean[np*G + g] - gds) * a[g*group_size + j] * a[g*group_size + j] * a[g*group_size + j] * scale; c[g*group_size + j] = -b[g*group_size + j] * mean[np*G + g] - gdb * a[g*group_size + j] * scale; } } for (cp = 0; cp < CP; cp++) { /* din = dout * a * gamma + b * inp + c */ /* Size = 3*CP*HW*CB*4 */ for (cb = 0; cb < CB; cb++) { for (hw = 0; hw < HW; hw++){ LIBXSMM_VLA_ACCESS(4, din, np, cp, hw, cb, CP, HW, CB) = LIBXSMM_VLA_ACCESS(4, dout, np, cp, hw, cb, CP, HW, CB) * a[cp*CB + cb] * LIBXSMM_VLA_ACCESS(2, gamma, cp, cb, CB) + b[cp*CB + cb] * LIBXSMM_VLA_ACCESS(4, inp, np, cp, hw, cb, CP, HW, CB) + c[cp*CB + cb]; } } } } int cp; #pragma omp parallel for for (cp = 0; cp < CP; cp++) { for (np=0; np < NP; np++ ) { int cb; for(cb = 0; cb < CB; cb++){ LIBXSMM_VLA_ACCESS(2, dgamma, cp, cb, CB) += dgamma_NP[np*CP*CB + cp*CB + cb]; LIBXSMM_VLA_ACCESS(2, dbeta, cp, cb, CB) += dbeta_NP[np*CP*CB + cp*CB + cb]; } } } } int main( int argc, char* argv[] ) { libxsmm_blasint my_eqn10, my_eqn11, my_eqn12, my_eqn13, my_eqn14, my_eqn15; libxsmm_matrix_eqn_function func10, func11, func12, func13, func14, func15; libxsmm_meltw_unary_flags jit_reduce_flags = LIBXSMM_MELTW_FLAG_UNARY_NONE; libxsmm_meltw_unary_type unary_type; libxsmm_meltwfunction_unary reduce_rows_kernel, reduce_HW_kernel, reduce_groups_kernel; const float eps = FLT_EPSILON; libxsmm_blasint i, it, ld, tmp_ld, tmp_ld2; unsigned long long l_start, l_end; double l_total = 0, l_total2 = 0; double t_vec = 0, t_tpp = 0; libxsmm_matdiff_info norms_out; float *inp, *out, *dinp, *dout, *eqn_dinp, *eqn_dout, *dbeta, *eqn_dbeta, *dgamma, *eqn_dgamma, *eqn_out, *gamma, *beta, *cache_fl, *mean, *var; libxsmm_bfloat16 *bf16_inp, *bf16_out, *bf16_dinp, *bf16_dout, *bf16_eqn_dinp, *bf16_eqn_dout, *bf16_gamma, *bf16_beta, *bf16_eqn_out; int NP = 28; int CP = 2; int HW = 784; int CB = 64; int G = 1; long num_HW_blocks = 16; int datatype_mode = 0; int iters = 100; libxsmm_datatype in_dt = LIBXSMM_DATATYPE_F32; libxsmm_datatype out_dt = LIBXSMM_DATATYPE_F32; if ( argc > 1 ) NP = atoi(argv[1]); if ( argc > 2 ) CP = atoi(argv[2]); if ( argc > 3 ) HW = atoi(argv[3]); if ( argc > 4 ) CB = atoi(argv[4]); if ( argc > 5 ) G = atoi(argv[5]); if ( argc > 6 ) num_HW_blocks = atoi(argv[6]); if ( argc > 7 ) datatype_mode = atoi(argv[7]); if ( argc > 8 ) iters = atoi(argv[8]); if (datatype_mode == 0) { in_dt = LIBXSMM_DATATYPE_F32; out_dt = LIBXSMM_DATATYPE_F32; } else if (datatype_mode == 1) { in_dt = LIBXSMM_DATATYPE_BF16; out_dt = LIBXSMM_DATATYPE_BF16; } else { printf("ERROR: Supporting only FP32 and BF16 precisions...\n"); } inp = (float*) libxsmm_aligned_malloc( sizeof(float)*NP*CP*HW*CB, 2097152); out = (float*) libxsmm_aligned_malloc( sizeof(float)*NP*CP*HW*CB, 2097152); dinp = (float*) libxsmm_aligned_malloc( sizeof(float)*NP*CP*HW*CB, 2097152); dout = (float*) libxsmm_aligned_malloc( sizeof(float)*NP*CP*HW*CB, 2097152); dgamma = (float*) libxsmm_aligned_malloc( sizeof(float)*CP*CB, 2097152); dbeta = (float*) libxsmm_aligned_malloc( sizeof(float)*CP*CB, 2097152); eqn_dinp = (float*) libxsmm_aligned_malloc( sizeof(float)*NP*CP*HW*CB, 2097152); eqn_dout = (float*) libxsmm_aligned_malloc( sizeof(float)*NP*CP*HW*CB, 2097152); eqn_dgamma = (float*) libxsmm_aligned_malloc( sizeof(float)*CP*CB, 2097152); eqn_dbeta = (float*) libxsmm_aligned_malloc( sizeof(float)*CP*CB, 2097152); gamma = (float*) libxsmm_aligned_malloc( sizeof(float)*CP*CB, 2097152); beta = (float*) libxsmm_aligned_malloc( sizeof(float)*CP*CB, 2097152); mean = (float*) libxsmm_aligned_malloc( sizeof(float)*NP*G, 2097152); var = (float*) libxsmm_aligned_malloc( sizeof(float)*NP*G, 2097152); eqn_out = (float*) libxsmm_aligned_malloc( sizeof(float)*NP*CP*HW*CB, 2097152); cache_fl = (float*) libxsmm_aligned_malloc( sizeof(float)*1024*1024, 2097152); bf16_inp = (libxsmm_bfloat16*) libxsmm_aligned_malloc( sizeof(libxsmm_bfloat16)*NP*CP*HW*CB, 2097152); bf16_out = (libxsmm_bfloat16*) libxsmm_aligned_malloc( sizeof(libxsmm_bfloat16)*NP*CP*HW*CB, 2097152); bf16_dinp = (libxsmm_bfloat16*) libxsmm_aligned_malloc( sizeof(libxsmm_bfloat16)*NP*CP*HW*CB, 2097152); bf16_dout = (libxsmm_bfloat16*) libxsmm_aligned_malloc( sizeof(libxsmm_bfloat16)*NP*CP*HW*CB, 2097152); bf16_eqn_dinp = (libxsmm_bfloat16*) libxsmm_aligned_malloc( sizeof(libxsmm_bfloat16)*NP*CP*HW*CB, 2097152); bf16_eqn_dout = (libxsmm_bfloat16*) libxsmm_aligned_malloc( sizeof(libxsmm_bfloat16)*NP*CP*HW*CB, 2097152); bf16_gamma = (libxsmm_bfloat16*) libxsmm_aligned_malloc( sizeof(libxsmm_bfloat16)*CP*CB, 2097152); bf16_beta = (libxsmm_bfloat16*) libxsmm_aligned_malloc( sizeof(libxsmm_bfloat16)*CP*CB, 2097152); bf16_eqn_out = (libxsmm_bfloat16*) libxsmm_aligned_malloc( sizeof(libxsmm_bfloat16)*NP*CP*HW*CB, 2097152); libxsmm_init(); libxsmm_matdiff_clear(&norms_out); /* Initializing arrays */ for ( i = 0; i < NP*CP*HW*CB; ++i ) { inp[i] = (float)libxsmm_rng_f64(); out[i] = (float)libxsmm_rng_f64(); eqn_out[i] = out[i]; dinp[i] = (float)libxsmm_rng_f64(); dout[i] = (float)libxsmm_rng_f64(); eqn_dinp[i] = dinp[i]; eqn_dout[i] = dout[i]; libxsmm_rne_convert_fp32_bf16( &inp[i], &bf16_inp[i], 1 ); libxsmm_rne_convert_fp32_bf16( &out[i], &bf16_out[i], 1 ); libxsmm_rne_convert_fp32_bf16( &eqn_out[i], &bf16_eqn_out[i], 1 ); libxsmm_rne_convert_fp32_bf16( &dout[i], &bf16_dout[i], 1 ); libxsmm_rne_convert_fp32_bf16( &eqn_dout[i], &bf16_eqn_dout[i], 1 ); libxsmm_rne_convert_fp32_bf16( &dinp[i], &bf16_dinp[i], 1 ); libxsmm_rne_convert_fp32_bf16( &eqn_dinp[i], &bf16_eqn_dinp[i], 1 ); } for ( i = 0; i < CP*CB; ++i ) { gamma[i] = (float)libxsmm_rng_f64(); beta[i] = (float)libxsmm_rng_f64(); dbeta[i] = (float)libxsmm_rng_f64(); dgamma[i] = (float)libxsmm_rng_f64(); eqn_dbeta[i] = dbeta[i]; eqn_dgamma[i] = dgamma[i]; libxsmm_rne_convert_fp32_bf16( &gamma[i], &bf16_gamma[i], 1 ); libxsmm_rne_convert_fp32_bf16( &beta[i], &bf16_beta[i], 1 ); } for (i = 0; i < 1024 * 1024; i++ ) { cache_fl[i] = (float)libxsmm_rng_f64(); } libxsmm_blasint ldo = G; libxsmm_meltwfunction_unary all_zero_G_kernel = libxsmm_dispatch_meltw_unary(G, 1, NULL, &ldo, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_XOR); if ( all_zero_G_kernel == NULL) { fprintf( stderr, "JIT for initialization by unary all zero group copy kernel failed. Bailing...!\n"); exit(-1); } ldo = CB; libxsmm_meltwfunction_unary all_zero_kernel = libxsmm_dispatch_meltw_unary(CB, 1, NULL, &ldo, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_XOR); if ( all_zero_G_kernel == NULL) { fprintf( stderr, "JIT for initialization by unary all zero copy kernel failed. Bailing...!\n"); exit(-1); } libxsmm_meltwfunction_unary copy_kernel = libxsmm_dispatch_meltw_unary(CB, 1, &ldo, &ldo, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_IDENTITY); if ( copy_kernel == NULL) { fprintf( stderr, "JIT for initialization by copy kernel failed. Bailing...!\n"); exit(-1); } /* TPPs for reducing X and X2 in HW*/ ld = CB; tmp_ld = CB; unary_type = LIBXSMM_MELTW_TYPE_UNARY_REDUCE_X_X2_OP_ADD; jit_reduce_flags = LIBXSMM_MELTW_FLAG_UNARY_REDUCE_COLS; reduce_HW_kernel = libxsmm_dispatch_meltw_unary(CB, HW/num_HW_blocks, &ld, &tmp_ld, in_dt, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, jit_reduce_flags, unary_type); libxsmm_blasint group_size = (CP*CB)/G; libxsmm_meltwfunction_binary add_kernel = libxsmm_dispatch_meltw_binary(CB, 1, &ld, &ld, &ld, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_BINARY_NONE, LIBXSMM_MELTW_TYPE_BINARY_ADD); if ( add_kernel == NULL) { fprintf( stderr, "JIT for initialization of add kernel failed. Bailing...!\n"); exit(-1); } /* TPP for reducing groups */ ld = group_size; /* group_size = (CP*CB)/G */ tmp_ld = 1; unary_type = LIBXSMM_MELTW_TYPE_UNARY_REDUCE_X_OP_ADD; jit_reduce_flags = LIBXSMM_MELTW_FLAG_UNARY_REDUCE_ROWS; reduce_groups_kernel = libxsmm_dispatch_meltw_unary(group_size, 1, &ld, &tmp_ld, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, jit_reduce_flags, unary_type); ld = CB; tmp_ld = 1; unary_type = LIBXSMM_MELTW_TYPE_UNARY_REDUCE_X_OP_ADD; jit_reduce_flags = LIBXSMM_MELTW_FLAG_UNARY_REDUCE_ROWS; reduce_rows_kernel = libxsmm_dispatch_meltw_unary(CB, 1, &ld, &tmp_ld, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, jit_reduce_flags, unary_type); /* TPP for foward */ ld = CB; tmp_ld = 1; tmp_ld2 = 1; my_eqn10 = libxsmm_matrix_eqn_create(); /* y = (s*x + b)*gamma + beta */ libxsmm_matrix_eqn_push_back_ternary_op( my_eqn10, LIBXSMM_MELTW_TYPE_TERNARY_MULADD, LIBXSMM_MELTW_FLAG_TERNARY_BCAST_COL_IN_1 | LIBXSMM_MELTW_FLAG_TERNARY_BCAST_COL_IN_2 | LIBXSMM_MELTW_FLAG_TERNARY_REUSE_IN_2_AS_OUT, LIBXSMM_DATATYPE_F32 ); libxsmm_matrix_eqn_push_back_ternary_op( my_eqn10, LIBXSMM_MELTW_TYPE_TERNARY_MULADD, LIBXSMM_MELTW_FLAG_TERNARY_BCAST_COL_IN_1 | LIBXSMM_MELTW_FLAG_TERNARY_BCAST_COL_IN_2 | LIBXSMM_MELTW_FLAG_TERNARY_REUSE_IN_2_AS_OUT, LIBXSMM_DATATYPE_F32 ); libxsmm_matrix_eqn_push_back_arg( my_eqn10, CB, HW/num_HW_blocks, ld, 0, 0, in_dt ); /* x = [HW, CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn10, CB, 1, tmp_ld, 1, 0, LIBXSMM_DATATYPE_F32 ); /* s = [CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn10, CB, 1, tmp_ld, 2, 0, LIBXSMM_DATATYPE_F32 ); /* b = [CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn10, CB, 1, tmp_ld2, 3, 0, in_dt ); /* gamma = [CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn10, CB, 1, tmp_ld2, 4, 0, in_dt ); /* beta = [CB] */ func10 = libxsmm_dispatch_matrix_eqn( CB, HW/num_HW_blocks, &ld, out_dt, my_eqn10 ); /* y = [HW, CB] */ /* Check correctness */ if (datatype_mode == 0) { scaler_groupnorm_fwd_fp32(NP, CP, HW, CB, G, inp, gamma, beta, mean, var, out, eps); tpp_groupnorm_fwd_fp32(NP, CP, HW, CB, G, num_HW_blocks, inp, gamma, beta, mean, var, eqn_out, func10, reduce_HW_kernel, reduce_rows_kernel, reduce_groups_kernel, all_zero_G_kernel, all_zero_kernel, add_kernel, eps); } else if (datatype_mode == 1) { scaler_groupnorm_fwd_fp32(NP, CP, HW, CB, G, inp, gamma, beta, mean, var, out, eps); tpp_groupnorm_fwd_bf16(NP, CP, HW, CB, G, num_HW_blocks, bf16_inp, bf16_gamma, bf16_beta, mean, var, bf16_eqn_out, func10, reduce_HW_kernel, reduce_rows_kernel, reduce_groups_kernel, all_zero_G_kernel, all_zero_kernel, add_kernel, eps); for ( i = 0; i < NP*CP*HW*CB; ++i ) { /* out[i] = upconvert_bf16(bf16_out[i]); */ eqn_out[i] = upconvert_bf16(bf16_eqn_out[i]); } } /* compare */ printf("############################################\n"); if (datatype_mode == 0) { printf("# Correctness FP32 FWD Groupnorm - Output #\n"); } else { printf("# Correctness BF16 FWD Groupnorm - Output #\n"); } printf("############################################\n"); libxsmm_matdiff(&norms_out, LIBXSMM_DATATYPE_F32, NP*CP*HW*CB, 1, out, eqn_out, 0, 0); printf("L1 reference : %.25g\n", norms_out.l1_ref); printf("L1 test : %.25g\n", norms_out.l1_tst); printf("L2 abs.error : %.24f\n", norms_out.l2_abs); printf("L2 rel.error : %.24f\n", norms_out.l2_rel); printf("Linf abs.error: %.24f\n", norms_out.linf_abs); printf("Linf rel.error: %.24f\n", norms_out.linf_rel); printf("Check-norm : %.24f\n\n", norms_out.normf_rel); if (datatype_mode == 0) { scaler_groupnorm_fwd_fp32(NP, CP, HW, CB, G, inp, gamma, beta, mean, var, out, eps); l_start = libxsmm_timer_tick(); for (it = 0; it < iters; it++) { scaler_groupnorm_fwd_fp32(NP, CP, HW, CB, G, inp, gamma, beta, mean, var, out, eps); } l_end = libxsmm_timer_tick(); l_total = libxsmm_timer_duration(l_start, l_end); printf("Unit time FWD = %.5g\n", ((double)(l_total))); tpp_groupnorm_fwd_fp32(NP, CP, HW, CB, G, num_HW_blocks, inp, gamma, beta, mean, var, eqn_out, func10, reduce_HW_kernel, reduce_rows_kernel, reduce_groups_kernel, all_zero_G_kernel, all_zero_kernel, add_kernel, eps); l_start = libxsmm_timer_tick(); for (it = 0; it < iters; it++) { tpp_groupnorm_fwd_fp32(NP, CP, HW, CB, G, num_HW_blocks, inp, gamma, beta, mean, var, eqn_out, func10, reduce_HW_kernel, reduce_rows_kernel, reduce_groups_kernel, all_zero_G_kernel, all_zero_kernel, add_kernel, eps); } l_end = libxsmm_timer_tick(); l_total2 = libxsmm_timer_duration(l_start, l_end); printf("TPP groupnorm time FWD = %.5g\n", ((double)(l_total2))); printf("Speedup FWD is %.5g\n", l_total/l_total2); } else if (datatype_mode == 1) { scaler_groupnorm_fwd_fp32(NP, CP, HW, CB, G, inp, gamma, beta, mean, var, out, eps); l_start = libxsmm_timer_tick(); for (it = 0; it < iters; it++) { scaler_groupnorm_fwd_fp32(NP, CP, HW, CB, G, inp, gamma, beta, mean, var, out, eps); } l_end = libxsmm_timer_tick(); l_total = libxsmm_timer_duration(l_start, l_end); printf("Scaler FP32 groupnorm time FWD = %.5g\n", ((double)(l_total))); tpp_groupnorm_fwd_bf16(NP, CP, HW, CB, G, num_HW_blocks, bf16_inp, bf16_gamma, bf16_beta, mean, var, bf16_eqn_out, func10, reduce_HW_kernel, reduce_rows_kernel, reduce_groups_kernel, all_zero_G_kernel, all_zero_kernel, add_kernel, eps); l_start = libxsmm_timer_tick(); for (it = 0; it < iters; it++) { tpp_groupnorm_fwd_bf16(NP, CP, HW, CB, G, num_HW_blocks, bf16_inp, bf16_gamma, bf16_beta, mean, var, bf16_eqn_out, func10, reduce_HW_kernel, reduce_rows_kernel, reduce_groups_kernel, all_zero_G_kernel, all_zero_kernel, add_kernel, eps); } l_end = libxsmm_timer_tick(); l_total2 = libxsmm_timer_duration(l_start, l_end); printf("TPP BF16 groupnorm time FWD = %.5g\n", ((double)(l_total2))); printf("Speedup FWD is %.5g\n", l_total/l_total2); } t_tpp = l_total2; t_vec = l_total; /* Group norm equations */ /* Create MatEq for bwd layernorm */ ld = CB; tmp_ld2 = 1; /* dgamma function */ my_eqn11 = libxsmm_matrix_eqn_create(); /* dgamma = ((inp *a + b) * dout) + dgamma */ libxsmm_matrix_eqn_push_back_binary_op(my_eqn11, LIBXSMM_MELTW_TYPE_BINARY_ADD, LIBXSMM_MELTW_FLAG_BINARY_NONE, LIBXSMM_DATATYPE_F32); /* dgamma = ((inp *a + b) * dout) + dgamma */ libxsmm_matrix_eqn_push_back_unary_op(my_eqn11, LIBXSMM_MELTW_TYPE_UNARY_REDUCE_X_OP_ADD, LIBXSMM_MELTW_FLAG_UNARY_REDUCE_COLS, LIBXSMM_DATATYPE_F32); /* [HW, CB] -> [CB] */ libxsmm_matrix_eqn_push_back_binary_op(my_eqn11, LIBXSMM_MELTW_TYPE_BINARY_MUL, LIBXSMM_MELTW_FLAG_BINARY_NONE, LIBXSMM_DATATYPE_F32); /* ((inp *a + b) * dout) */ libxsmm_matrix_eqn_push_back_ternary_op( my_eqn11, LIBXSMM_MELTW_TYPE_TERNARY_MULADD, LIBXSMM_MELTW_FLAG_TERNARY_BCAST_COL_IN_1 | LIBXSMM_MELTW_FLAG_TERNARY_BCAST_COL_IN_2 | LIBXSMM_MELTW_FLAG_TERNARY_REUSE_IN_2_AS_OUT, LIBXSMM_DATATYPE_F32 ); libxsmm_matrix_eqn_push_back_arg( my_eqn11, CB, HW/num_HW_blocks, ld, 0, 0, in_dt ); /* inp [HW, CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn11, CB, 1, 1, 1, 0, LIBXSMM_DATATYPE_F32 ); /* a [CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn11, CB, 1, 1, 2, 0, LIBXSMM_DATATYPE_F32 ); /* b [CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn11, CB, HW/num_HW_blocks, ld, 3, 0, in_dt ); /* dout [HW, CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn11, CB, 1, 1, 4, 0, LIBXSMM_DATATYPE_F32 ); /* dgamma [CB] */ func11 = libxsmm_dispatch_matrix_eqn( CB, 1, &tmp_ld2, LIBXSMM_DATATYPE_F32, my_eqn11 ); /* dgamma [CB] */ /* dbeta function */ my_eqn12 = libxsmm_matrix_eqn_create(); /* dbeta [CB] = dout [HW, CB] + dbeta [CB] */ libxsmm_matrix_eqn_push_back_binary_op( my_eqn12, LIBXSMM_MELTW_TYPE_BINARY_ADD, LIBXSMM_MELTW_FLAG_BINARY_NONE, LIBXSMM_DATATYPE_F32 ); /* dbeta_tmp [HW, CB] */ libxsmm_matrix_eqn_push_back_unary_op(my_eqn12, LIBXSMM_MELTW_TYPE_UNARY_REDUCE_X_OP_ADD, LIBXSMM_MELTW_FLAG_UNARY_REDUCE_COLS, LIBXSMM_DATATYPE_F32); /* [HW, CB] -> [CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn12, CB, HW/num_HW_blocks, ld, 3, 0, in_dt ); /* dout [HW, CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn12, CB, 1, 1, 5, 0, LIBXSMM_DATATYPE_F32 ); /* dbeta [CB] */ func12 = libxsmm_dispatch_matrix_eqn( CB, 1, &tmp_ld2, LIBXSMM_DATATYPE_F32, my_eqn12 ); /* dbeta [CB] */ /* db new equation */ my_eqn13 = libxsmm_matrix_eqn_create(); /* db [CB] = (dout * gamma) [HW, CB] + db [CB]*/ libxsmm_matrix_eqn_push_back_binary_op(my_eqn13, LIBXSMM_MELTW_TYPE_BINARY_ADD, LIBXSMM_MELTW_FLAG_BINARY_NONE, LIBXSMM_DATATYPE_F32 ); /* db [CB] */ libxsmm_matrix_eqn_push_back_unary_op(my_eqn13, LIBXSMM_MELTW_TYPE_UNARY_REDUCE_X_OP_ADD, LIBXSMM_MELTW_FLAG_UNARY_REDUCE_COLS, LIBXSMM_DATATYPE_F32); /* [HW, CB] -> [CB] */ libxsmm_matrix_eqn_push_back_binary_op( my_eqn13, LIBXSMM_MELTW_TYPE_BINARY_MUL, LIBXSMM_MELTW_FLAG_BINARY_BCAST_COL_IN_1, LIBXSMM_DATATYPE_F32 ); libxsmm_matrix_eqn_push_back_arg( my_eqn13, CB, HW/num_HW_blocks, ld, 3, 0, in_dt ); /* dout [HW, CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn13, CB, 1, 1, 6, 0, in_dt ); /* gamma [CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn13, CB, 1, 1, 9, 0, LIBXSMM_DATATYPE_F32 ); /* db [CB] */ func13 = libxsmm_dispatch_matrix_eqn( CB, 1, &tmp_ld2, LIBXSMM_DATATYPE_F32, my_eqn13 ); /* db [CB] */ /* ds new equation */ my_eqn14 = libxsmm_matrix_eqn_create(); /* ds [CB] = ((dout * gamma) * inp) [HW, CB] + ds [CB] */ libxsmm_matrix_eqn_push_back_binary_op(my_eqn14, LIBXSMM_MELTW_TYPE_BINARY_ADD, LIBXSMM_MELTW_FLAG_BINARY_NONE, LIBXSMM_DATATYPE_F32 ); /* ds [CB] */ libxsmm_matrix_eqn_push_back_unary_op(my_eqn14, LIBXSMM_MELTW_TYPE_UNARY_REDUCE_X_OP_ADD, LIBXSMM_MELTW_FLAG_UNARY_REDUCE_COLS, LIBXSMM_DATATYPE_F32); /* [HW, CB] -> [CB] */ libxsmm_matrix_eqn_push_back_binary_op( my_eqn14, LIBXSMM_MELTW_TYPE_BINARY_MUL, LIBXSMM_MELTW_FLAG_BINARY_NONE, LIBXSMM_DATATYPE_F32 ); libxsmm_matrix_eqn_push_back_binary_op( my_eqn14, LIBXSMM_MELTW_TYPE_BINARY_MUL, LIBXSMM_MELTW_FLAG_BINARY_BCAST_COL_IN_1, LIBXSMM_DATATYPE_F32 ); /*(dout * gamma)*/ libxsmm_matrix_eqn_push_back_arg( my_eqn14, CB, HW/num_HW_blocks, ld, 3, 0, in_dt ); /* dout [HW, CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn14, CB, 1, 1, 6, 0, in_dt ); /* gamma [CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn14, CB, HW/num_HW_blocks, ld, 0, 0, in_dt ); /* inp [HW, CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn14, CB, 1, 1, 8, 0, LIBXSMM_DATATYPE_F32 ); /* ds [CB] */ func14 = libxsmm_dispatch_matrix_eqn( CB, 1, &tmp_ld2, LIBXSMM_DATATYPE_F32, my_eqn14 ); /* ds [CB] */ /* din equation */ my_eqn15 = libxsmm_matrix_eqn_create(); /* din = ((gamma * a) * dout) + (inp * b + c) */ libxsmm_matrix_eqn_push_back_ternary_op( my_eqn15, LIBXSMM_MELTW_TYPE_TERNARY_MULADD, LIBXSMM_MELTW_FLAG_TERNARY_BCAST_COL_IN_0 | LIBXSMM_MELTW_FLAG_TERNARY_REUSE_IN_2_AS_OUT, LIBXSMM_DATATYPE_F32 ); libxsmm_matrix_eqn_push_back_binary_op( my_eqn15, LIBXSMM_MELTW_TYPE_BINARY_MUL, LIBXSMM_MELTW_FLAG_BINARY_NONE, LIBXSMM_DATATYPE_F32 ); libxsmm_matrix_eqn_push_back_arg( my_eqn15, CB, 1, 1, 6, 0, in_dt ); /* gamma [CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn15, CB, 1, 1, 1, 0, LIBXSMM_DATATYPE_F32 ); /* a [CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn15, CB, HW/num_HW_blocks, ld, 3, 0, in_dt ); /* dout [HW, CB] */ libxsmm_matrix_eqn_push_back_ternary_op( my_eqn15, LIBXSMM_MELTW_TYPE_TERNARY_MULADD, LIBXSMM_MELTW_FLAG_TERNARY_BCAST_COL_IN_1 | LIBXSMM_MELTW_FLAG_TERNARY_BCAST_COL_IN_2 | LIBXSMM_MELTW_FLAG_TERNARY_REUSE_IN_2_AS_OUT, LIBXSMM_DATATYPE_F32 ); libxsmm_matrix_eqn_push_back_arg( my_eqn15, CB, HW/num_HW_blocks, ld, 0, 0, in_dt ); /* inp [HW, CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn15, CB, 1, 1, 2, 0, LIBXSMM_DATATYPE_F32 ); /* b [CB] */ libxsmm_matrix_eqn_push_back_arg( my_eqn15, CB, 1, 1, 7, 0, LIBXSMM_DATATYPE_F32 ); /* c [CB] */ func15 = libxsmm_dispatch_matrix_eqn( CB, HW/num_HW_blocks, &ld, in_dt, my_eqn15 ); /* din [HW, CB] */ if (datatype_mode == 0) { scaler_groupnorm_bwd_fp32(NP, CP, HW, CB, G, dout, inp, mean, var, gamma, dinp, dgamma, dbeta, eps); tpp_groupnorm_bwd_fp32(NP, CP, HW, CB, G, num_HW_blocks, eqn_dout, inp, mean, var, gamma, eqn_dinp, eqn_dgamma, eqn_dbeta, func11, func12, func13, func14, func15, all_zero_kernel, add_kernel, eps); } else if (datatype_mode == 1) { scaler_groupnorm_bwd_fp32(NP, CP, HW, CB, G, dout, inp, mean, var, gamma, dinp, dgamma, dbeta, eps); tpp_groupnorm_bwd_bf16(NP, CP, HW, CB, G, num_HW_blocks, bf16_dout, bf16_inp, mean, var, bf16_gamma, bf16_eqn_dinp, eqn_dgamma, eqn_dbeta, func11, func12, func13, func14, func15, all_zero_kernel, add_kernel, eps); for ( i = 0; i < NP*CP*HW*CB; ++i ) { /* dinp[i] = upconvert_bf16(bf16_dinp[i]); */ eqn_dinp[i] = upconvert_bf16(bf16_eqn_dinp[i]); } } /* compare */ printf("############################################\n"); if (datatype_mode == 0) { printf("# Correctness FP32 BWD Groupnorm - Dinput #\n"); } else { printf("# Correctness BF16 BWD Groupnorm - Dinput #\n"); } printf("############################################\n"); libxsmm_matdiff(&norms_out, LIBXSMM_DATATYPE_F32, NP*CP*HW*CB, 1, dinp, eqn_dinp, 0, 0); printf("L1 reference : %.25g\n", norms_out.l1_ref); printf("L1 test : %.25g\n", norms_out.l1_tst); printf("L2 abs.error : %.24f\n", norms_out.l2_abs); printf("L2 rel.error : %.24f\n", norms_out.l2_rel); printf("Linf abs.error: %.24f\n", norms_out.linf_abs); printf("Linf rel.error: %.24f\n", norms_out.linf_rel); printf("Check-norm : %.24f\n\n", norms_out.normf_rel); printf("###########################################\n"); if (datatype_mode == 0) { printf("# Correctness FP32 BWD Groupnorm - Dbeta #\n"); } else { printf("# Correctness BF16 BWD Groupnorm - Dbeta #\n"); } printf("###########################################\n"); libxsmm_matdiff(&norms_out, LIBXSMM_DATATYPE_F32, CP*CB, 1, dbeta, eqn_dbeta, 0, 0); printf("L1 reference : %.25g\n", norms_out.l1_ref); printf("L1 test : %.25g\n", norms_out.l1_tst); printf("L2 abs.error : %.24f\n", norms_out.l2_abs); printf("L2 rel.error : %.24f\n", norms_out.l2_rel); printf("Linf abs.error: %.24f\n", norms_out.linf_abs); printf("Linf rel.error: %.24f\n", norms_out.linf_rel); printf("Check-norm : %.24f\n\n", norms_out.normf_rel); printf("############################################\n"); if (datatype_mode == 0) { printf("# Correctness FP32 BWD Groupnorm - Dgamma #\n"); } else { printf("# Correctness BF16 BWD Groupnorm - Dgamma #\n"); } printf("############################################\n"); libxsmm_matdiff(&norms_out, LIBXSMM_DATATYPE_F32, CP*CB, 1, dgamma, eqn_dgamma, 0, 0); printf("L1 reference : %.25g\n", norms_out.l1_ref); printf("L1 test : %.25g\n", norms_out.l1_tst); printf("L2 abs.error : %.24f\n", norms_out.l2_abs); printf("L2 rel.error : %.24f\n", norms_out.l2_rel); printf("Linf abs.error: %.24f\n", norms_out.linf_abs); printf("Linf rel.error: %.24f\n", norms_out.linf_rel); printf("Check-norm : %.24f\n\n", norms_out.normf_rel); if (datatype_mode == 0) { scaler_groupnorm_bwd_fp32(NP, CP, HW, CB, G, dout, inp, mean, var, gamma, dinp, dgamma, dbeta, eps); l_start = libxsmm_timer_tick(); for (it = 0; it < iters; it++) { scaler_groupnorm_bwd_fp32(NP, CP, HW, CB, G, dout, inp, mean, var, gamma, dinp, dgamma, dbeta, eps); } l_end = libxsmm_timer_tick(); l_total = libxsmm_timer_duration(l_start, l_end); printf("Scaler groupnorm time BWD = %.5g\n", ((double)(l_total))); tpp_groupnorm_bwd_fp32(NP, CP, HW, CB, G, num_HW_blocks, eqn_dout, inp, mean, var, gamma, eqn_dinp, eqn_dgamma, eqn_dbeta, func11, func12, func13, func14, func15, all_zero_kernel, add_kernel, eps); l_start = libxsmm_timer_tick(); for (it = 0; it < iters; it++) { tpp_groupnorm_bwd_fp32(NP, CP, HW, CB, G, num_HW_blocks, eqn_dout, inp, mean, var, gamma, eqn_dinp, eqn_dgamma, eqn_dbeta, func11, func12, func13, func14, func15, all_zero_kernel, add_kernel, eps); } l_end = libxsmm_timer_tick(); l_total2 = libxsmm_timer_duration(l_start, l_end); printf("TPP groupnorm time BWD = %.5g\n", ((double)(l_total2))); printf("Speedup BWD is %.5g\n", l_total/l_total2); } else if (datatype_mode == 1) { scaler_groupnorm_bwd_fp32(NP, CP, HW, CB, G, dout, inp, mean, var, gamma, dinp, dgamma, dbeta, eps); l_start = libxsmm_timer_tick(); for (it = 0; it < iters; it++) { scaler_groupnorm_bwd_fp32(NP, CP, HW, CB, G, dout, inp, mean, var, gamma, dinp, dgamma, dbeta, eps); } l_end = libxsmm_timer_tick(); l_total = libxsmm_timer_duration(l_start, l_end); printf("Scaler FP32 groupnorm time BWD = %.5g\n", ((double)(l_total))); tpp_groupnorm_bwd_bf16(NP, CP, HW, CB, G, num_HW_blocks, bf16_dout, bf16_inp, mean, var, bf16_gamma, bf16_dinp, dgamma, dbeta, func11, func12, func13, func14, func15, all_zero_kernel, add_kernel, eps); l_start = libxsmm_timer_tick(); for (it = 0; it < iters; it++) { tpp_groupnorm_bwd_bf16(NP, CP, HW, CB, G, num_HW_blocks, bf16_dout, bf16_inp, mean, var, bf16_gamma, bf16_dinp, dgamma, dbeta, func11, func12, func13, func14, func15, all_zero_kernel, add_kernel, eps); } l_end = libxsmm_timer_tick(); l_total2 = libxsmm_timer_duration(l_start, l_end); printf("TPP BF16 groupnorm time BWD = %.5g\n", ((double)(l_total2))); printf("Speedup BWD is %.5g\n", l_total/l_total2); } /* printf("Running sum is %.5f\n", sum); */ t_tpp += l_total2; t_vec += l_total; printf("\n\n=================================\n"); printf("Total Speedup via TPP Matrix equation is %.5g\n", t_vec/t_tpp); printf("=================================\n"); libxsmm_free(inp); libxsmm_free(out); libxsmm_free(dinp); libxsmm_free(dout); libxsmm_free(eqn_dinp); libxsmm_free(eqn_dout); libxsmm_free(bf16_dinp); libxsmm_free(bf16_dout); libxsmm_free(bf16_eqn_dinp); libxsmm_free(bf16_eqn_dout); libxsmm_free(dgamma); libxsmm_free(dbeta); libxsmm_free(eqn_dgamma); libxsmm_free(eqn_dbeta); libxsmm_free(mean); libxsmm_free(var); libxsmm_free(gamma); libxsmm_free(beta); libxsmm_free(eqn_out); libxsmm_free(bf16_inp); libxsmm_free(bf16_out); libxsmm_free(bf16_gamma); libxsmm_free(bf16_beta); libxsmm_free(bf16_eqn_out); libxsmm_free(cache_fl); return 0; }
HybridAdoptorBase.h
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // // File developed by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory // // File created by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory // ////////////////////////////////////////////////////////////////////////////////////// /** @file HybridAdoptorBase.h * * Hybrid adoptor base class */ #ifndef QMCPLUSPLUS_HYBRID_ADOPTOR_BASE_H #define QMCPLUSPLUS_HYBRID_ADOPTOR_BASE_H #include <Particle/DistanceTableData.h> #include <QMCWaveFunctions/lcao/SoaSphericalTensor.h> #include <spline2/MultiBspline1D.hpp> #include <Numerics/SmoothFunctions.hpp> namespace qmcplusplus { template<typename ST> struct AtomicOrbitalSoA { static const int D = 3; using AtomicSplineType = typename bspline_traits<ST, 1>::SplineType; using AtomicBCType = typename bspline_traits<ST, 1>::BCType; using AtomicSingleSplineType = UBspline_1d_d; using PointType = TinyVector<ST, D>; using value_type = ST; using vContainer_type = aligned_vector<ST>; // near core cutoff ST rmin; // far from core cutoff, rmin_sqrt>=rmin ST rmin_sqrt; ST cutoff, cutoff_buffer, spline_radius, non_overlapping_radius; int spline_npoints, BaseN; int NumBands, Npad; PointType pos; const int lmax, lm_tot; SoaSphericalTensor<ST> Ylm; vContainer_type l_vals; vContainer_type r_power_minus_l; ///1D spline of radial functions of all the orbitals std::shared_ptr<MultiBspline1D<ST>> SplineInst; vContainer_type localV, localG, localL; AtomicOrbitalSoA(int Lmax) : lmax(Lmax), lm_tot((Lmax + 1) * (Lmax + 1)), Ylm(Lmax) { r_power_minus_l.resize(lm_tot); l_vals.resize(lm_tot); for (int l = 0; l <= lmax; l++) for (int m = -l; m <= l; m++) l_vals[l * (l + 1) + m] = l; rmin = std::exp(std::log(std::numeric_limits<ST>::min()) / std::max(Lmax, 1)); rmin = std::max(rmin, std::numeric_limits<ST>::epsilon()); rmin_sqrt = std::max(rmin, std::sqrt(std::numeric_limits<ST>::epsilon())); } inline void resizeStorage(size_t Nb) { NumBands = Nb; Npad = getAlignedSize<ST>(Nb); localV.resize(Npad * lm_tot); localG.resize(Npad * lm_tot); localL.resize(Npad * lm_tot); create_spline(); } void bcast_tables(Communicate* comm) { chunked_bcast(comm, SplineInst->getSplinePtr()); } void gather_tables(Communicate* comm, std::vector<int>& offset) { gatherv(comm, SplineInst->getSplinePtr(), Npad, offset); } template<typename PT, typename VT> inline void set_info(const PT& R, const VT& cutoff_in, const VT& cutoff_buffer_in, const VT& spline_radius_in, const VT& non_overlapping_radius_in, const int spline_npoints_in) { pos[0] = R[0]; pos[1] = R[1]; pos[2] = R[2]; cutoff = cutoff_in; cutoff_buffer = cutoff_buffer_in; spline_radius = spline_radius_in; spline_npoints = spline_npoints_in; non_overlapping_radius = non_overlapping_radius_in; BaseN = spline_npoints + 2; } inline void create_spline() { AtomicBCType bc; bc.lCode = FLAT; bc.rCode = NATURAL; Ugrid grid; grid.start = 0.0; grid.end = spline_radius; grid.num = spline_npoints; SplineInst = std::make_shared<MultiBspline1D<ST>>(); SplineInst->create(grid, bc, lm_tot * Npad); } inline void flush_zero() { SplineInst->flush_zero(); } inline void set_spline(AtomicSingleSplineType* spline, int lm, int ispline) { SplineInst->copy_spline(spline, lm * Npad + ispline, 0, BaseN); } bool read_splines(hdf_archive& h5f) { einspline_engine<AtomicSplineType> bigtable(SplineInst->getSplinePtr()); int lmax_in, spline_npoints_in; ST spline_radius_in; bool success = true; success = success && h5f.readEntry(lmax_in, "l_max"); success = success && h5f.readEntry(spline_radius_in, "spline_radius"); success = success && h5f.readEntry(spline_npoints_in, "spline_npoints"); if (lmax_in != lmax) return false; if (spline_radius_in != spline_radius) return false; if (spline_npoints_in != spline_npoints) return false; return success && h5f.readEntry(bigtable, "radial_spline"); } bool write_splines(hdf_archive& h5f) { bool success = true; success = success && h5f.writeEntry(spline_radius, "spline_radius"); success = success && h5f.writeEntry(spline_npoints, "spline_npoints"); success = success && h5f.writeEntry(lmax, "l_max"); success = success && h5f.writeEntry(pos, "position"); einspline_engine<AtomicSplineType> bigtable(SplineInst->getSplinePtr()); success = success && h5f.writeEntry(bigtable, "radial_spline"); return success; } //evaluate only V template<typename VV> inline void evaluate_v(const ST& r, const PointType& dr, VV& myV) { if (r > std::numeric_limits<ST>::epsilon()) Ylm.evaluateV(dr[0] / r, dr[1] / r, dr[2] / r); else Ylm.evaluateV(0, 0, 1); const ST* restrict Ylm_v = Ylm[0]; constexpr ST czero(0); ST* restrict val = myV.data(); ST* restrict local_val = localV.data(); std::fill(myV.begin(), myV.end(), czero); SplineInst->evaluate(r, localV); for (size_t lm = 0; lm < lm_tot; lm++) { #pragma omp simd aligned(val, local_val) for (size_t ib = 0; ib < myV.size(); ib++) val[ib] += Ylm_v[lm] * local_val[ib]; local_val += Npad; } } template<typename DISPL, typename VM> inline void evaluateValues(const DISPL& Displacements, const int center_idx, const ST& r, VM& multi_myV) { if (r <= std::numeric_limits<ST>::epsilon()) Ylm.evaluateV(0, 0, 1); const ST* restrict Ylm_v = Ylm[0]; const size_t m = multi_myV.cols(); constexpr ST czero(0); std::fill(multi_myV.begin(), multi_myV.end(), czero); SplineInst->evaluate(r, localV); for (int ivp = 0; ivp < Displacements.size(); ivp++) { PointType dr = Displacements[ivp][center_idx]; if (r > std::numeric_limits<ST>::epsilon()) Ylm.evaluateV(-dr[0] / r, -dr[1] / r, -dr[2] / r); ST* restrict val = multi_myV[ivp]; ST* restrict local_val = localV.data(); for (size_t lm = 0; lm < lm_tot; lm++) { #pragma omp simd aligned(val, local_val) for (size_t ib = 0; ib < m; ib++) val[ib] += Ylm_v[lm] * local_val[ib]; local_val += Npad; } } } //evaluate VGL template<typename VV, typename GV> inline void evaluate_vgl(const ST& r, const PointType& dr, VV& myV, GV& myG, VV& myL) { ST drx, dry, drz, rhatx, rhaty, rhatz, rinv; if (r > rmin) { rinv = 1.0 / r; } else { rinv = 0; } drx = dr[0]; dry = dr[1]; drz = dr[2]; rhatx = drx * rinv; rhaty = dry * rinv; rhatz = drz * rinv; Ylm.evaluateVGL(drx, dry, drz); const ST* restrict Ylm_v = Ylm[0]; const ST* restrict Ylm_gx = Ylm[1]; const ST* restrict Ylm_gy = Ylm[2]; const ST* restrict Ylm_gz = Ylm[3]; ST* restrict g0 = myG.data(0); ST* restrict g1 = myG.data(1); ST* restrict g2 = myG.data(2); constexpr ST czero(0), cone(1), chalf(0.5); std::fill(myV.begin(), myV.end(), czero); std::fill(g0, g0 + Npad, czero); std::fill(g1, g1 + Npad, czero); std::fill(g2, g2 + Npad, czero); std::fill(myL.begin(), myL.end(), czero); ST* restrict val = myV.data(); ST* restrict lapl = myL.data(); ST* restrict local_val = localV.data(); ST* restrict local_grad = localG.data(); ST* restrict local_lapl = localL.data(); SplineInst->evaluate_vgl(r, localV, localG, localL); if (r > rmin_sqrt) { // far from core r_power_minus_l[0] = cone; ST r_power_temp = cone; for (int l = 1; l <= lmax; l++) { r_power_temp *= rinv; for (int m = -l, lm = l * l; m <= l; m++, lm++) r_power_minus_l[lm] = r_power_temp; } for (size_t lm = 0; lm < lm_tot; lm++) { const ST& l_val = l_vals[lm]; const ST& r_power = r_power_minus_l[lm]; const ST Ylm_rescale = Ylm_v[lm] * r_power; const ST rhat_dot_G = (rhatx * Ylm_gx[lm] + rhaty * Ylm_gy[lm] + rhatz * Ylm_gz[lm]) * r_power; #pragma omp simd aligned(val, g0, g1, g2, lapl, local_val, local_grad, local_lapl) for (size_t ib = 0; ib < myV.size(); ib++) { const ST local_v = local_val[ib]; const ST local_g = local_grad[ib]; const ST local_l = local_lapl[ib]; // value const ST Vpart = l_val * rinv * local_v; val[ib] += Ylm_rescale * local_v; // grad const ST factor1 = local_g * Ylm_rescale; const ST factor2 = local_v * r_power; const ST factor3 = -Vpart * Ylm_rescale; g0[ib] += factor1 * rhatx + factor2 * Ylm_gx[lm] + factor3 * rhatx; g1[ib] += factor1 * rhaty + factor2 * Ylm_gy[lm] + factor3 * rhaty; g2[ib] += factor1 * rhatz + factor2 * Ylm_gz[lm] + factor3 * rhatz; // laplacian lapl[ib] += (local_l + (local_g * (2 - l_val) - Vpart) * rinv) * Ylm_rescale + (local_g - Vpart) * rhat_dot_G; } local_val += Npad; local_grad += Npad; local_lapl += Npad; } } else if (r > rmin) { // the possibility of reaching here is very very low std::cout << "Warning: an electron is very close to an ion, distance=" << r << " be careful!" << std::endl; // near core, kill divergence in the laplacian r_power_minus_l[0] = cone; ST r_power_temp = cone; for (int l = 1; l <= lmax; l++) { r_power_temp *= rinv; for (int m = -l, lm = l * l; m <= l; m++, lm++) r_power_minus_l[lm] = r_power_temp; } for (size_t lm = 0; lm < lm_tot; lm++) { const ST& l_val = l_vals[lm]; const ST& r_power = r_power_minus_l[lm]; const ST Ylm_rescale = Ylm_v[lm] * r_power; const ST rhat_dot_G = (Ylm_gx[lm] * rhatx + Ylm_gy[lm] * rhaty + Ylm_gz[lm] * rhatz) * r_power * r; #pragma omp simd aligned(val, g0, g1, g2, lapl, local_val, local_grad, local_lapl) for (size_t ib = 0; ib < myV.size(); ib++) { const ST local_v = local_val[ib]; const ST local_g = local_grad[ib]; const ST local_l = local_lapl[ib]; // value const ST Vpart = Ylm_rescale * local_v; val[ib] += Vpart; // grad const ST factor1 = local_g * Ylm_rescale; const ST factor2 = local_v * r_power; const ST factor3 = -l_val * Vpart * rinv; g0[ib] += factor1 * rhatx + factor2 * Ylm_gx[lm] + factor3 * rhatx; g1[ib] += factor1 * rhaty + factor2 * Ylm_gy[lm] + factor3 * rhaty; g2[ib] += factor1 * rhatz + factor2 * Ylm_gz[lm] + factor3 * rhatz; // laplacian lapl[ib] += local_l * (cone - chalf * l_val) * (3 * Ylm_rescale + rhat_dot_G); } local_val += Npad; local_grad += Npad; local_lapl += Npad; } } else { std::cout << "Warning: an electron is on top of an ion!" << std::endl; // strictly zero #pragma omp simd aligned(val, lapl, local_val, local_lapl) for (size_t ib = 0; ib < myV.size(); ib++) { // value val[ib] = Ylm_v[0] * local_val[ib]; // laplacian lapl[ib] = local_lapl[ib] * static_cast<ST>(3) * Ylm_v[0]; } local_val += Npad; local_grad += Npad; local_lapl += Npad; if (lm_tot > 0) { //std::cout << std::endl; for (size_t lm = 1; lm < 4; lm++) { #pragma omp simd aligned(g0, g1, g2, local_grad) for (size_t ib = 0; ib < myV.size(); ib++) { const ST local_g = local_grad[ib]; // grad g0[ib] += local_g * Ylm_gx[lm]; g1[ib] += local_g * Ylm_gy[lm]; g2[ib] += local_g * Ylm_gz[lm]; } local_grad += Npad; } } } } template<typename VV, typename GV, typename HT> void evaluate_vgh(const ST& r, const PointType& dr, VV& myV, GV& myG, HT& myH) { //Needed to do tensor product here APP_ABORT("AtomicOrbitalSoA::evaluate_vgh"); } }; /** adoptor class to match * */ template<typename ST> struct HybridAdoptorBase { static const int D = 3; using PointType = typename AtomicOrbitalSoA<ST>::PointType; using RealType = typename DistanceTableData::RealType; // atomic centers std::vector<AtomicOrbitalSoA<ST>> AtomicCenters; ///table index int myTableID; //mapping supercell to primitive cell std::vector<int> Super2Prim; // r, dr for distance table RealType dist_r; DistanceTableData::PosType dist_dr; // for APBC PointType r_image; // smooth function derivatives RealType f, df_dr, d2f_dr2; /// smoothing schemes enum class smoothing_schemes { CONSISTENT = 0, SMOOTHALL, SMOOTHPARTIAL } smooth_scheme; /// smoothing function smoothing_functions smooth_func_id; HybridAdoptorBase() {} void set_info(const ParticleSet& ions, ParticleSet& els, const std::vector<int>& mapping) { myTableID = els.addTable(ions, DT_SOA); Super2Prim = mapping; } inline void resizeStorage(size_t Nb) { size_t SplineCoefsBytes = 0; for (int ic = 0; ic < AtomicCenters.size(); ic++) { AtomicCenters[ic].resizeStorage(Nb); SplineCoefsBytes += AtomicCenters[ic].SplineInst->sizeInByte(); } app_log() << "MEMORY " << SplineCoefsBytes / (1 << 20) << " MB allocated " << "for the atomic radial splines in hybrid orbital representation" << std::endl; } void bcast_tables(Communicate* comm) { for (int ic = 0; ic < AtomicCenters.size(); ic++) AtomicCenters[ic].bcast_tables(comm); } void gather_atomic_tables(Communicate* comm, std::vector<int>& offset) { if (comm->size() == 1) return; for (int ic = 0; ic < AtomicCenters.size(); ic++) AtomicCenters[ic].gather_tables(comm, offset); } inline void flush_zero() { for (int ic = 0; ic < AtomicCenters.size(); ic++) AtomicCenters[ic].flush_zero(); } bool read_splines(hdf_archive& h5f) { bool success = true; size_t ncenter; success = success && h5f.push("atomic_centers", false); success = success && h5f.readEntry(ncenter, "number_of_centers"); if (!success) return success; if (ncenter != AtomicCenters.size()) success = false; // read splines of each center for (int ic = 0; ic < AtomicCenters.size(); ic++) { std::ostringstream gname; gname << "center_" << ic; success = success && h5f.push(gname.str().c_str(), false); success = success && AtomicCenters[ic].read_splines(h5f); h5f.pop(); } h5f.pop(); return success; } bool write_splines(hdf_archive& h5f) { bool success = true; int ncenter = AtomicCenters.size(); success = success && h5f.push("atomic_centers", true); success = success && h5f.writeEntry(ncenter, "number_of_centers"); // write splines of each center for (int ic = 0; ic < AtomicCenters.size(); ic++) { std::ostringstream gname; gname << "center_" << ic; success = success && h5f.push(gname.str().c_str(), true); success = success && AtomicCenters[ic].write_splines(h5f); h5f.pop(); } h5f.pop(); return success; } template<typename Cell> inline int get_bc_sign(const PointType& r, const Cell& PrimLattice, TinyVector<int, D>& HalfG) { int bc_sign = 0; PointType shift_unit = PrimLattice.toUnit(r - r_image); for (int i = 0; i < D; i++) { ST img = round(shift_unit[i]); bc_sign += HalfG[i] * (int)img; } return bc_sign; } //evaluate only V template<typename VV> inline RealType evaluate_v(const ParticleSet& P, const int iat, VV& myV) { const auto& ei_dist = P.getDistTable(myTableID); const int center_idx = ei_dist.get_first_neighbor(iat, dist_r, dist_dr, P.activePtcl == iat); if (center_idx < 0) abort(); auto& myCenter = AtomicCenters[Super2Prim[center_idx]]; if (dist_r < myCenter.cutoff) { PointType dr(-dist_dr[0], -dist_dr[1], -dist_dr[2]); r_image = myCenter.pos + dr; myCenter.evaluate_v(dist_r, dr, myV); return smooth_function(myCenter.cutoff_buffer, myCenter.cutoff, dist_r); } return RealType(-1); } /* check if the batched algorithm is safe to operate * @param VP virtual particle set * @return true if it is safe * * When the reference electron in the NLPP evaluation has a distance larger than the non overlapping radius of the reference center. * Some qudrature points may get its SPOs evaluated from the nearest center which is not the reference center. * The batched algorthm forces the evaluation on the reference center and introduce some error. * In this case, the non-batched algorithm should be used. */ bool is_batched_safe(const VirtualParticleSet& VP) { const int center_idx = VP.refSourcePtcl; auto& myCenter = AtomicCenters[Super2Prim[center_idx]]; return VP.refPS.getDistTable(myTableID).Distances[VP.refPtcl][center_idx] < myCenter.non_overlapping_radius; } // C2C, C2R cases template<typename VM> inline RealType evaluateValuesC2X(const VirtualParticleSet& VP, VM& multi_myV) { const int center_idx = VP.refSourcePtcl; dist_r = VP.refPS.getDistTable(myTableID).Distances[VP.refPtcl][center_idx]; auto& myCenter = AtomicCenters[Super2Prim[center_idx]]; if (dist_r < myCenter.cutoff) { myCenter.evaluateValues(VP.getDistTable(myTableID).Displacements, center_idx, dist_r, multi_myV); return smooth_function(myCenter.cutoff_buffer, myCenter.cutoff, dist_r); } return RealType(-1); } // R2R case template<typename VM, typename Cell, typename SV> inline RealType evaluateValuesR2R(const VirtualParticleSet& VP, const Cell& PrimLattice, TinyVector<int, D>& HalfG, VM& multi_myV, SV& bc_signs) { const int center_idx = VP.refSourcePtcl; dist_r = VP.refPS.getDistTable(myTableID).Distances[VP.refPtcl][center_idx]; auto& myCenter = AtomicCenters[Super2Prim[center_idx]]; if (dist_r < myCenter.cutoff) { const auto& displ = VP.getDistTable(myTableID).Displacements; for (int ivp = 0; ivp < VP.getTotalNum(); ivp++) { r_image = myCenter.pos - displ[ivp][center_idx]; bc_signs[ivp] = get_bc_sign(VP.R[ivp], PrimLattice, HalfG); ; } myCenter.evaluateValues(displ, center_idx, dist_r, multi_myV); return smooth_function(myCenter.cutoff_buffer, myCenter.cutoff, dist_r); } return RealType(-1); } //evaluate only VGL template<typename VV, typename GV> inline RealType evaluate_vgl(const ParticleSet& P, const int iat, VV& myV, GV& myG, VV& myL) { const auto& ei_dist = P.getDistTable(myTableID); const int center_idx = ei_dist.get_first_neighbor(iat, dist_r, dist_dr, P.activePtcl == iat); if (center_idx < 0) abort(); auto& myCenter = AtomicCenters[Super2Prim[center_idx]]; if (dist_r < myCenter.cutoff) { PointType dr(-dist_dr[0], -dist_dr[1], -dist_dr[2]); r_image = myCenter.pos + dr; myCenter.evaluate_vgl(dist_r, dr, myV, myG, myL); return smooth_function(myCenter.cutoff_buffer, myCenter.cutoff, dist_r); } return RealType(-1); } //evaluate only VGH template<typename VV, typename GV, typename HT> inline RealType evaluate_vgh(const ParticleSet& P, const int iat, VV& myV, GV& myG, HT& myH) { const auto& ei_dist = P.getDistTable(myTableID); const int center_idx = ei_dist.get_first_neighbor(iat, dist_r, dist_dr, P.activePtcl == iat); if (center_idx < 0) abort(); auto& myCenter = AtomicCenters[Super2Prim[center_idx]]; if (dist_r < myCenter.cutoff) { PointType dr(-dist_dr[0], -dist_dr[1], -dist_dr[2]); r_image = myCenter.pos + dr; myCenter.evaluate_vgh(dist_r, dr, myV, myG, myH); return smooth_function(myCenter.cutoff_buffer, myCenter.cutoff, dist_r); } return RealType(-1); } // interpolate buffer region, value only template<typename VV> inline void interpolate_buffer_v(VV& psi, const VV& psi_AO) const { const RealType cone(1); for (size_t i = 0; i < psi.size(); i++) psi[i] = psi_AO[i] * f + psi[i] * (cone - f); } // interpolate buffer region, value, gradients and laplacian template<typename VV, typename GV> inline void interpolate_buffer_vgl(VV& psi, GV& dpsi, VV& d2psi, const VV& psi_AO, const GV& dpsi_AO, const VV& d2psi_AO) const { const RealType cone(1), ctwo(2); const RealType rinv(1.0 / dist_r); if(smooth_scheme == smoothing_schemes::CONSISTENT) for (size_t i = 0; i < psi.size(); i++) { // psi, dpsi, d2psi are all consistent d2psi[i] = d2psi_AO[i] * f + d2psi[i] * (cone - f) + df_dr * rinv * ctwo * dot(dpsi[i] - dpsi_AO[i], dist_dr) + (psi_AO[i] - psi[i]) * (d2f_dr2 + ctwo * rinv * df_dr); dpsi[i] = dpsi_AO[i] * f + dpsi[i] * (cone - f) + df_dr * rinv * dist_dr * (psi[i] - psi_AO[i]); psi[i] = psi_AO[i] * f + psi[i] * (cone - f); } else if(smooth_scheme == smoothing_schemes::SMOOTHALL) for (size_t i = 0; i < psi.size(); i++) { d2psi[i] = d2psi_AO[i] * f + d2psi[i] * (cone - f); dpsi[i] = dpsi_AO[i] * f + dpsi[i] * (cone - f); psi[i] = psi_AO[i] * f + psi[i] * (cone - f); } else if(smooth_scheme == smoothing_schemes::SMOOTHPARTIAL) for (size_t i = 0; i < psi.size(); i++) { // dpsi, d2psi are consistent but psi is not. d2psi[i] = d2psi_AO[i] * f + d2psi[i] * (cone - f) + df_dr * rinv * ctwo * dot(dpsi[i] - dpsi_AO[i], dist_dr); dpsi[i] = dpsi_AO[i] * f + dpsi[i] * (cone - f); psi[i] = psi_AO[i] * f + psi[i] * (cone - f); } else throw std::runtime_error("Unknown smooth scheme!"); } inline RealType smooth_function(const ST& cutoff_buffer, const ST& cutoff, const RealType r) { const RealType cone(1); if (r < cutoff_buffer) return cone; const RealType scale = cone / (cutoff - cutoff_buffer); const RealType x = (r - cutoff_buffer) * scale; f = smoothing(smooth_func_id, x, df_dr, d2f_dr2); df_dr *= scale; d2f_dr2 *= scale*scale; return f; } }; } // namespace qmcplusplus #endif
GB_binop__rminus_int16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__rminus_int16) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__rminus_int16) // A.*B function (eWiseMult): GB (_AemultB_03__rminus_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__rminus_int16) // A*D function (colscale): GB (_AxD__rminus_int16) // D*A function (rowscale): GB (_DxB__rminus_int16) // C+=B function (dense accum): GB (_Cdense_accumB__rminus_int16) // C+=b function (dense accum): GB (_Cdense_accumb__rminus_int16) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rminus_int16) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rminus_int16) // C=scalar+B GB (_bind1st__rminus_int16) // C=scalar+B' GB (_bind1st_tran__rminus_int16) // C=A+scalar GB (_bind2nd__rminus_int16) // C=A'+scalar GB (_bind2nd_tran__rminus_int16) // C type: int16_t // A type: int16_t // B,b type: int16_t // BinaryOp: cij = (bij - aij) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int16_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = (y - x) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_RMINUS || GxB_NO_INT16 || GxB_NO_RMINUS_INT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__rminus_int16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__rminus_int16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__rminus_int16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__rminus_int16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int16_t int16_t bwork = (*((int16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__rminus_int16) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__rminus_int16) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__rminus_int16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__rminus_int16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__rminus_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__rminus_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__rminus_int16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__rminus_int16) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; int16_t bij = Bx [p] ; Cx [p] = (bij - x) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__rminus_int16) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = Ax [p] ; Cx [p] = (y - aij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = Ax [pA] ; \ Cx [pC] = (aij - x) ; \ } GrB_Info GB (_bind1st_tran__rminus_int16) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = Ax [pA] ; \ Cx [pC] = (y - aij) ; \ } GrB_Info GB (_bind2nd_tran__rminus_int16) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
perftest.c
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED. * Copyright (C) The University of Tennessee and The University * of Tennessee Research Foundation. 2015. ALL RIGHTS RESERVED. * Copyright (C) UT-Battelle, LLC. 2015. ALL RIGHTS RESERVED. * Copyright (C) ARM Ltd. 2017-2021. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "perftest.h" #include <ucs/sys/string.h> #include <ucs/sys/sys.h> #include <ucs/sys/sock.h> #include <ucs/debug/log.h> #include <sys/socket.h> #include <arpa/inet.h> #include <stdlib.h> #include <unistd.h> #include <netdb.h> #include <sys/poll.h> test_type_t tests[] = { {"am_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_PINGPONG, "active message latency", "latency", 1}, {"put_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_PINGPONG, "put latency", "latency", 1}, {"add_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_PINGPONG, "atomic add latency", "latency", 1}, {"get", UCX_PERF_API_UCT, UCX_PERF_CMD_GET, UCX_PERF_TEST_TYPE_STREAM_UNI, "get latency / bandwidth / message rate", "latency", 1}, {"fadd", UCX_PERF_API_UCT, UCX_PERF_CMD_FADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic fetch-and-add latency / rate", "latency", 1}, {"swap", UCX_PERF_API_UCT, UCX_PERF_CMD_SWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic swap latency / rate", "latency", 1}, {"cswap", UCX_PERF_API_UCT, UCX_PERF_CMD_CSWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic compare-and-swap latency / rate", "latency", 1}, {"am_bw", UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI, "active message bandwidth / message rate", "overhead", 1}, {"put_bw", UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI, "put bandwidth / message rate", "overhead", 1}, {"add_mr", UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic add message rate", "overhead", 1}, {"tag_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG, UCX_PERF_TEST_TYPE_PINGPONG, "tag match latency", "latency", 1}, {"tag_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG, UCX_PERF_TEST_TYPE_STREAM_UNI, "tag match bandwidth", "overhead", 32}, {"tag_sync_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG_SYNC, UCX_PERF_TEST_TYPE_PINGPONG, "tag sync match latency", "latency", 1}, {"tag_sync_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG_SYNC, UCX_PERF_TEST_TYPE_STREAM_UNI, "tag sync match bandwidth", "overhead", 32}, {"ucp_put_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_PINGPONG, "put latency", "latency", 1}, {"ucp_put_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI, "put bandwidth", "overhead", 32}, {"ucp_get", UCX_PERF_API_UCP, UCX_PERF_CMD_GET, UCX_PERF_TEST_TYPE_STREAM_UNI, "get latency / bandwidth / message rate", "latency", 1}, {"ucp_add", UCX_PERF_API_UCP, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic add bandwidth / message rate", "overhead", 1}, {"ucp_fadd", UCX_PERF_API_UCP, UCX_PERF_CMD_FADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic fetch-and-add latency / bandwidth / rate", "latency", 1}, {"ucp_swap", UCX_PERF_API_UCP, UCX_PERF_CMD_SWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic swap latency / bandwidth / rate", "latency", 1}, {"ucp_cswap", UCX_PERF_API_UCP, UCX_PERF_CMD_CSWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic compare-and-swap latency / bandwidth / rate", "latency", 1}, {"stream_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_STREAM, UCX_PERF_TEST_TYPE_STREAM_UNI, "stream bandwidth", "overhead", 1}, {"stream_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_STREAM, UCX_PERF_TEST_TYPE_PINGPONG, "stream latency", "latency", 1}, {"ucp_am_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_PINGPONG, "am latency", "latency", 1}, {"ucp_am_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI, "am bandwidth / message rate", "overhead", 32}, {NULL} }; static int sock_io(int sock, ssize_t (*sock_call)(int, void *, size_t, int), int poll_events, void *data, size_t size, void (*progress)(void *arg), void *arg, const char *name) { size_t total = 0; struct pollfd pfd; int ret; while (total < size) { pfd.fd = sock; pfd.events = poll_events; pfd.revents = 0; ret = poll(&pfd, 1, 1); /* poll for 1ms */ if (ret > 0) { ucs_assert(ret == 1); ucs_assert(pfd.revents & poll_events); ret = sock_call(sock, (char*)data + total, size - total, 0); if (ret < 0) { ucs_error("%s() failed: %m", name); return -1; } total += ret; } else if ((ret < 0) && (errno != EINTR)) { ucs_error("poll(fd=%d) failed: %m", sock); return -1; } /* progress user context */ if (progress != NULL) { progress(arg); } } return 0; } static int safe_send(int sock, void *data, size_t size, void (*progress)(void *arg), void *arg) { typedef ssize_t (*sock_call)(int, void *, size_t, int); return sock_io(sock, (sock_call)send, POLLOUT, data, size, progress, arg, "send"); } static int safe_recv(int sock, void *data, size_t size, void (*progress)(void *arg), void *arg) { return sock_io(sock, recv, POLLIN, data, size, progress, arg, "recv"); } ucs_status_t init_test_params(perftest_params_t *params) { memset(params, 0, sizeof(*params)); params->super.api = UCX_PERF_API_LAST; params->super.command = UCX_PERF_CMD_LAST; params->super.test_type = UCX_PERF_TEST_TYPE_LAST; params->super.thread_mode = UCS_THREAD_MODE_SINGLE; params->super.thread_count = 1; params->super.async_mode = UCS_ASYNC_THREAD_LOCK_TYPE; params->super.wait_mode = UCX_PERF_WAIT_MODE_LAST; params->super.max_outstanding = 0; params->super.warmup_iter = 10000; params->super.alignment = ucs_get_page_size(); params->super.max_iter = 1000000l; params->super.max_time = 0.0; params->super.report_interval = 1.0; params->super.percentile_rank = 50.0; params->super.flags = UCX_PERF_TEST_FLAG_VERBOSE; params->super.uct.fc_window = UCT_PERF_TEST_MAX_FC_WINDOW; params->super.uct.data_layout = UCT_PERF_DATA_LAYOUT_SHORT; params->super.uct.am_hdr_size = 8; params->super.send_mem_type = UCS_MEMORY_TYPE_HOST; params->super.recv_mem_type = UCS_MEMORY_TYPE_HOST; params->super.msg_size_cnt = 1; params->super.iov_stride = 0; params->super.ucp.send_datatype = UCP_PERF_DATATYPE_CONTIG; params->super.ucp.recv_datatype = UCP_PERF_DATATYPE_CONTIG; params->super.ucp.am_hdr_size = 0; strcpy(params->super.uct.dev_name, TL_RESOURCE_NAME_NONE); strcpy(params->super.uct.tl_name, TL_RESOURCE_NAME_NONE); params->super.msg_size_list = calloc(params->super.msg_size_cnt, sizeof(*params->super.msg_size_list)); if (params->super.msg_size_list == NULL) { return UCS_ERR_NO_MEMORY; } params->super.msg_size_list[0] = 8; params->test_id = TEST_ID_UNDEFINED; return UCS_OK; } static unsigned sock_rte_group_size(void *rte_group) { return 2; } static unsigned sock_rte_group_index(void *rte_group) { sock_rte_group_t *group = rte_group; return group->is_server ? 0 : 1; } static void sock_rte_barrier(void *rte_group, void (*progress)(void *arg), void *arg) { #pragma omp barrier #pragma omp master { sock_rte_group_t *group = rte_group; const unsigned magic = 0xdeadbeef; unsigned snc; snc = magic; safe_send(group->connfd, &snc, sizeof(unsigned), progress, arg); snc = 0; safe_recv(group->connfd, &snc, sizeof(unsigned), progress, arg); ucs_assert(snc == magic); } #pragma omp barrier } static void sock_rte_post_vec(void *rte_group, const struct iovec *iovec, int iovcnt, void **req) { sock_rte_group_t *group = rte_group; size_t size; int i; size = 0; for (i = 0; i < iovcnt; ++i) { size += iovec[i].iov_len; } safe_send(group->connfd, &size, sizeof(size), NULL, NULL); for (i = 0; i < iovcnt; ++i) { safe_send(group->connfd, iovec[i].iov_base, iovec[i].iov_len, NULL, NULL); } } static void sock_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { sock_rte_group_t *group = rte_group; int group_index; size_t size; group_index = sock_rte_group_index(rte_group); if (src == group_index) { return; } ucs_assert_always(src == (1 - group_index)); safe_recv(group->connfd, &size, sizeof(size), NULL, NULL); ucs_assert_always(size <= max); safe_recv(group->connfd, buffer, size, NULL, NULL); } static void sock_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final, int is_multi_thread) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final, ctx->server_addr == NULL, is_multi_thread); } static ucx_perf_rte_t sock_rte = { .group_size = sock_rte_group_size, .group_index = sock_rte_group_index, .barrier = sock_rte_barrier, .post_vec = sock_rte_post_vec, .recv = sock_rte_recv, .exchange_vec = (ucx_perf_rte_exchange_vec_func_t)ucs_empty_function, .report = sock_rte_report, }; static ucs_status_t setup_sock_rte(struct perftest_context *ctx) { struct sockaddr_in inaddr; struct hostent *he; ucs_status_t status; int optval = 1; int sockfd, connfd; int ret; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { ucs_error("socket() failed: %m"); status = UCS_ERR_IO_ERROR; goto err; } if (ctx->server_addr == NULL) { optval = 1; status = ucs_socket_setopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if (status != UCS_OK) { goto err_close_sockfd; } inaddr.sin_family = AF_INET; inaddr.sin_port = htons(ctx->port); inaddr.sin_addr.s_addr = INADDR_ANY; memset(inaddr.sin_zero, 0, sizeof(inaddr.sin_zero)); ret = bind(sockfd, (struct sockaddr*)&inaddr, sizeof(inaddr)); if (ret < 0) { ucs_error("bind() failed: %m"); status = UCS_ERR_INVALID_ADDR; goto err_close_sockfd; } ret = listen(sockfd, 10); if (ret < 0) { ucs_error("listen() failed: %m"); status = UCS_ERR_IO_ERROR; goto err_close_sockfd; } printf("Waiting for connection...\n"); /* Accept next connection */ connfd = accept(sockfd, NULL, NULL); if (connfd < 0) { ucs_error("accept() failed: %m"); status = UCS_ERR_IO_ERROR; goto err_close_sockfd; } close(sockfd); /* release the memory for the list of the message sizes allocated * during the initialization of the default testing parameters */ free(ctx->params.super.msg_size_list); ctx->params.super.msg_size_list = NULL; ret = safe_recv(connfd, &ctx->params, sizeof(ctx->params), NULL, NULL); if (ret) { status = UCS_ERR_IO_ERROR; goto err_close_connfd; } if (ctx->params.super.msg_size_cnt != 0) { ctx->params.super.msg_size_list = calloc(ctx->params.super.msg_size_cnt, sizeof(*ctx->params.super.msg_size_list)); if (NULL == ctx->params.super.msg_size_list) { status = UCS_ERR_NO_MEMORY; goto err_close_connfd; } ret = safe_recv(connfd, ctx->params.super.msg_size_list, sizeof(*ctx->params.super.msg_size_list) * ctx->params.super.msg_size_cnt, NULL, NULL); if (ret) { status = UCS_ERR_IO_ERROR; goto err_close_connfd; } } ctx->sock_rte_group.connfd = connfd; ctx->sock_rte_group.is_server = 1; } else { he = gethostbyname(ctx->server_addr); if (he == NULL || he->h_addr_list == NULL) { ucs_error("host %s not found: %s", ctx->server_addr, hstrerror(h_errno)); status = UCS_ERR_INVALID_ADDR; goto err_close_sockfd; } inaddr.sin_family = he->h_addrtype; inaddr.sin_port = htons(ctx->port); ucs_assert(he->h_length == sizeof(inaddr.sin_addr)); memcpy(&inaddr.sin_addr, he->h_addr_list[0], he->h_length); memset(inaddr.sin_zero, 0, sizeof(inaddr.sin_zero)); ret = connect(sockfd, (struct sockaddr*)&inaddr, sizeof(inaddr)); if (ret < 0) { ucs_error("connect() failed: %m"); status = UCS_ERR_UNREACHABLE; goto err_close_sockfd; } safe_send(sockfd, &ctx->params, sizeof(ctx->params), NULL, NULL); if (ctx->params.super.msg_size_cnt != 0) { safe_send(sockfd, ctx->params.super.msg_size_list, sizeof(*ctx->params.super.msg_size_list) * ctx->params.super.msg_size_cnt, NULL, NULL); } ctx->sock_rte_group.connfd = sockfd; ctx->sock_rte_group.is_server = 0; } if (ctx->sock_rte_group.is_server) { ctx->flags |= TEST_FLAG_PRINT_TEST; } else { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.super.rte_group = &ctx->sock_rte_group; ctx->params.super.rte = &sock_rte; ctx->params.super.report_arg = ctx; return UCS_OK; err_close_connfd: close(connfd); goto err; err_close_sockfd: close(sockfd); err: return status; } static ucs_status_t cleanup_sock_rte(struct perftest_context *ctx) { close(ctx->sock_rte_group.connfd); return UCS_OK; } #if defined (HAVE_MPI) static unsigned mpi_rte_group_size(void *rte_group) { int size; MPI_Comm_size(MPI_COMM_WORLD, &size); return size; } static unsigned mpi_rte_group_index(void *rte_group) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); return rank; } static void mpi_rte_barrier(void *rte_group, void (*progress)(void *arg), void *arg) { int group_size, my_rank, i; MPI_Request *reqs; int nreqs = 0; int dummy; int flag; #pragma omp barrier #pragma omp master { /* * Naive non-blocking barrier implementation over send/recv, to call user * progress while waiting for completion. * Not using MPI_Ibarrier to be compatible with MPI-1. */ MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &group_size); /* allocate maximal possible number of requests */ reqs = (MPI_Request*)alloca(sizeof(*reqs) * group_size); if (my_rank == 0) { /* root gathers "ping" from all other ranks */ for (i = 1; i < group_size; ++i) { MPI_Irecv(&dummy, 0, MPI_INT, i /* source */, 1 /* tag */, MPI_COMM_WORLD, &reqs[nreqs++]); } } else { /* every non-root rank sends "ping" and waits for "pong" */ MPI_Send(&dummy, 0, MPI_INT, 0 /* dest */, 1 /* tag */, MPI_COMM_WORLD); MPI_Irecv(&dummy, 0, MPI_INT, 0 /* source */, 2 /* tag */, MPI_COMM_WORLD, &reqs[nreqs++]); } /* Waiting for receive requests */ do { MPI_Testall(nreqs, reqs, &flag, MPI_STATUSES_IGNORE); progress(arg); } while (!flag); if (my_rank == 0) { /* root sends "pong" to all ranks */ for (i = 1; i < group_size; ++i) { MPI_Send(&dummy, 0, MPI_INT, i /* dest */, 2 /* tag */, MPI_COMM_WORLD); } } } #pragma omp barrier } static void mpi_rte_post_vec(void *rte_group, const struct iovec *iovec, int iovcnt, void **req) { int group_size; int my_rank; int dest, i; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &group_size); for (dest = 0; dest < group_size; ++dest) { if (dest == my_rank) { continue; } for (i = 0; i < iovcnt; ++i) { MPI_Send(iovec[i].iov_base, iovec[i].iov_len, MPI_BYTE, dest, i == (iovcnt - 1), /* Send last iov with tag == 1 */ MPI_COMM_WORLD); } } *req = (void*)(uintptr_t)1; } static void mpi_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { MPI_Status status; size_t offset; int my_rank; int count; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); if (src == my_rank) { return; } offset = 0; do { ucs_assert_always(offset < max); MPI_Recv(buffer + offset, max - offset, MPI_BYTE, src, MPI_ANY_TAG, MPI_COMM_WORLD, &status); MPI_Get_count(&status, MPI_BYTE, &count); offset += count; } while (status.MPI_TAG != 1); } static void mpi_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final, int is_multi_thread) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final, ctx->server_addr == NULL, is_multi_thread); } #elif defined (HAVE_RTE) static unsigned ext_rte_group_size(void *rte_group) { rte_group_t group = (rte_group_t)rte_group; return rte_group_size(group); } static unsigned ext_rte_group_index(void *rte_group) { rte_group_t group = (rte_group_t)rte_group; return rte_group_rank(group); } static void ext_rte_barrier(void *rte_group, void (*progress)(void *arg), void *arg) { #pragma omp barrier #pragma omp master { rte_group_t group = (rte_group_t)rte_group; int rc; rc = rte_barrier(group); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_barrier"); } } #pragma omp barrier } static void ext_rte_post_vec(void *rte_group, const struct iovec* iovec, int iovcnt, void **req) { rte_group_t group = (rte_group_t)rte_group; rte_srs_session_t session; rte_iovec_t *r_vec; int i, rc; rc = rte_srs_session_create(group, 0, &session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_session_create"); } r_vec = calloc(iovcnt, sizeof(rte_iovec_t)); if (r_vec == NULL) { return; } for (i = 0; i < iovcnt; ++i) { r_vec[i].iov_base = iovec[i].iov_base; r_vec[i].type = rte_datatype_uint8_t; r_vec[i].count = iovec[i].iov_len; } rc = rte_srs_set_data(session, "KEY_PERF", r_vec, iovcnt); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_set_data"); } *req = session; free(r_vec); } static void ext_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { rte_group_t group = (rte_group_t)rte_group; rte_srs_session_t session = (rte_srs_session_t)req; void *rte_buffer = NULL; rte_iovec_t r_vec; uint32_t offset; int size; int rc; rc = rte_srs_get_data(session, rte_group_index_to_ec(group, src), "KEY_PERF", &rte_buffer, &size); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_get_data"); return; } r_vec.iov_base = buffer; r_vec.type = rte_datatype_uint8_t; r_vec.count = max; offset = 0; rte_unpack(&r_vec, rte_buffer, &offset); rc = rte_srs_session_destroy(session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_session_destroy"); } free(rte_buffer); } static void ext_rte_exchange_vec(void *rte_group, void * req) { rte_srs_session_t session = (rte_srs_session_t)req; int rc; rc = rte_srs_exchange_data(session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_exchange_data"); } } static void ext_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final, int is_multi_thread) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final, ctx->server_addr == NULL, is_multi_thread); } static ucx_perf_rte_t ext_rte = { .group_size = ext_rte_group_size, .group_index = ext_rte_group_index, .barrier = ext_rte_barrier, .report = ext_rte_report, .post_vec = ext_rte_post_vec, .recv = ext_rte_recv, .exchange_vec = ext_rte_exchange_vec, }; #endif static ucs_status_t setup_mpi_rte(struct perftest_context *ctx) { #if defined (HAVE_MPI) static ucx_perf_rte_t mpi_rte = { .group_size = mpi_rte_group_size, .group_index = mpi_rte_group_index, .barrier = mpi_rte_barrier, .post_vec = mpi_rte_post_vec, .recv = mpi_rte_recv, .exchange_vec = (void*)ucs_empty_function, .report = mpi_rte_report, }; int size, rank; ucs_trace_func(""); MPI_Comm_size(MPI_COMM_WORLD, &size); if (size != 2) { ucs_error("This test should run with exactly 2 processes (actual: %d)", size); return UCS_ERR_INVALID_PARAM; } MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 1) { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.super.rte_group = NULL; ctx->params.super.rte = &mpi_rte; ctx->params.super.report_arg = ctx; #elif defined (HAVE_RTE) ucs_trace_func(""); ctx->params.rte_group = NULL; ctx->params.rte = &mpi_rte; ctx->params.report_arg = ctx; rte_group_t group; rte_init(NULL, NULL, &group); if (1 == rte_group_rank(group)) { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.super.rte_group = group; ctx->params.super.rte = &ext_rte; ctx->params.super.report_arg = ctx; #endif return UCS_OK; } static ucs_status_t cleanup_mpi_rte(struct perftest_context *ctx) { #ifdef HAVE_RTE rte_finalize(); #endif return UCS_OK; } static ucs_status_t check_system(struct perftest_context *ctx) { ucs_sys_cpuset_t cpuset; unsigned i, count, nr_cpus; int ret; ucs_trace_func(""); ret = sysconf(_SC_NPROCESSORS_CONF); if (ret < 0) { ucs_error("failed to get local cpu count: %m"); return UCS_ERR_INVALID_PARAM; } nr_cpus = ret; memset(&cpuset, 0, sizeof(cpuset)); if (ctx->flags & TEST_FLAG_SET_AFFINITY) { for (i = 0; i < ctx->num_cpus; i++) { if (ctx->cpus[i] >= nr_cpus) { ucs_error("cpu (%u) out of range (0..%u)", ctx->cpus[i], nr_cpus - 1); return UCS_ERR_INVALID_PARAM; } } for (i = 0; i < ctx->num_cpus; i++) { CPU_SET(ctx->cpus[i], &cpuset); } ret = ucs_sys_setaffinity(&cpuset); if (ret) { ucs_warn("sched_setaffinity() failed: %m"); return UCS_ERR_INVALID_PARAM; } } else { ret = ucs_sys_getaffinity(&cpuset); if (ret) { ucs_warn("sched_getaffinity() failed: %m"); return UCS_ERR_INVALID_PARAM; } count = 0; for (i = 0; i < CPU_SETSIZE; ++i) { if (CPU_ISSET(i, &cpuset)) { ++count; } } if (count > 2) { ucs_warn("CPU affinity is not set (bound to %u cpus)." " Performance may be impacted.", count); } } return UCS_OK; } int main(int argc, char **argv) { struct perftest_context ctx; ucs_status_t status; int mpi_initialized; int mpi_rte; int ret; #ifdef HAVE_MPI int provided; mpi_initialized = !isatty(0) && /* Using MPI_THREAD_FUNNELED since ucx_perftest supports * using multiple threads when only the main one makes * MPI calls (which is also suitable for a single threaded * run). * MPI_THREAD_FUNNELED: * The process may be multi-threaded, but only the main * thread will make MPI calls (all MPI calls are funneled * to the main thread). */ (MPI_Init_thread(&argc, &argv, MPI_THREAD_FUNNELED, &provided) == 0); if (mpi_initialized && (provided != MPI_THREAD_FUNNELED)) { printf("MPI_Init_thread failed to set MPI_THREAD_FUNNELED. (provided = %d)\n", provided); ret = -1; goto out; } #else mpi_initialized = 0; #endif /* Parse command line */ status = parse_opts(&ctx, mpi_initialized, argc, argv); if (status != UCS_OK) { ret = (status == UCS_ERR_CANCELED) ? 0 : -127; goto out_msg_size_list; } #ifdef __COVERITY__ /* coverity[dont_call] */ mpi_rte = rand(); /* Shut up deadcode error */ #endif if (ctx.mpi) { mpi_rte = 1; } else { #ifdef HAVE_RTE mpi_rte = 1; #else mpi_rte = 0; #endif } status = check_system(&ctx); if (status != UCS_OK) { ret = -1; goto out_msg_size_list; } /* Create RTE */ status = (mpi_rte) ? setup_mpi_rte(&ctx) : setup_sock_rte(&ctx); if (status != UCS_OK) { ret = -1; goto out_msg_size_list; } /* Run the test */ status = run_test(&ctx); if (status != UCS_OK) { ret = -1; goto out_cleanup_rte; } ret = 0; out_cleanup_rte: (mpi_rte) ? cleanup_mpi_rte(&ctx) : cleanup_sock_rte(&ctx); out_msg_size_list: free(ctx.params.super.msg_size_list); #if HAVE_MPI out: #endif if (mpi_initialized) { #ifdef HAVE_MPI MPI_Finalize(); #endif } return ret; }
algo.h
/** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MINDQUANTUM_SPARSE_ALGO_H_ #define MINDQUANTUM_SPARSE_ALGO_H_ #include <memory> #include "sparse/csrhdmatrix.h" #include "sparse/paulimat.h" #include "sparse/sparse_utils.h" namespace mindquantum { namespace sparse { template <typename T> std::shared_ptr<CsrHdMatrix<T>> TransposeCsrHdMatrix(std::shared_ptr<CsrHdMatrix<T>> a) { auto &dim = a->dim_; auto &nnz = a->nnz_; auto &a_indices = a->indices_; auto &a_indptr = a->indptr_; auto &a_data = a->data_; Index *indices = reinterpret_cast<Index *>(malloc(sizeof(Index) * nnz)); Index *indptr = reinterpret_cast<Index *>(malloc(sizeof(Index) * (dim + 1))); CTP<T> data = reinterpret_cast<CTP<T>>(malloc(sizeof(CT<T>) * nnz)); std::fill(indptr, indptr + dim, 0); for (Index n = 0; n < nnz; n++) { indptr[a_indices[n]]++; } for (Index col = 0, sum = 0; col < dim; col++) { Index t = indptr[col]; indptr[col] = sum; sum += t; } indptr[dim] = nnz; for (Index row = 0; row < dim; row++) { for (Index jj = a_indptr[row]; jj < a_indptr[row + 1]; jj++) { Index col = a_indices[jj]; Index dest = indptr[col]; indices[dest] = row; data[dest] = std::conj(a_data[jj]); indptr[col]++; } } for (Index col = 0, last = 0; col <= dim; col++) { Index t = indptr[col]; indptr[col] = last; last = t; } auto c = std::make_shared<CsrHdMatrix<T>>(dim, nnz, indptr, indices, data); return c; } template <typename T> std::shared_ptr<CsrHdMatrix<T>> PauliMatToCsrHdMatrix(std::shared_ptr<PauliMat<T>> a) { Index nnz = 0; auto &col = a->col_; auto &dim = a->dim_; auto &coeff = a->coeff_; auto &p = a->p_; #pragma omp parallel for schedule(static) reduction(+ : nnz) for (Index i = 0; i < dim; i++) { if (i <= col[i]) { nnz++; } } Index *indptr = reinterpret_cast<Index *>(malloc(sizeof(Index) * (dim + 1))); Index *indices = reinterpret_cast<Index *>(malloc(sizeof(Index) * nnz)); CTP<T> data = reinterpret_cast<CTP<T>>(malloc(sizeof(CT<T>) * nnz)); indptr[0] = 0; for (Index i = 0, j = 0; i < dim; i++) { if (i <= col[i]) { indptr[i + 1] = indptr[i] + 1; if (i == col[i]) { data[j] = p * POLAR[coeff[i]] * (T) (0.5); } else { data[j] = p * POLAR[coeff[i]]; } indices[j] = col[i]; j++; } else { indptr[i + 1] = indptr[i]; } } auto c = std::make_shared<CsrHdMatrix<T>>(dim, nnz, indptr, indices, data); return c; } template <typename T> std::shared_ptr<PauliMat<T>> GetPauliMat(const PauliTerm<T> &pt, Index n_qubits) { auto c = std::make_shared<PauliMat<T>>(pt, n_qubits); return c; } template <typename T> std::shared_ptr<CsrHdMatrix<T>> Csr_Plus_Csr(std::shared_ptr<CsrHdMatrix<T>> a, std::shared_ptr<CsrHdMatrix<T>> b) { auto a_nnz = a->nnz_; auto b_nnz = b->nnz_; auto dim = a->dim_; auto maxnnz = a_nnz + b_nnz; CTP<T> data = reinterpret_cast<CTP<T>>(malloc(sizeof(CT<T>) * maxnnz)); Index *indices = reinterpret_cast<Index *>(malloc(sizeof(Index) * maxnnz)); Index *indptr = reinterpret_cast<Index *>(malloc(sizeof(Index) * (dim + 1))); csr_plus_csr(dim, a->indptr_, a->indices_, a->data_, b->indptr_, b->indices_, b->data_, indptr, indices, data); auto nnz = indptr[dim]; auto c = std::make_shared<CsrHdMatrix<T>>(dim, nnz, indptr, indices, data); return c; } template <typename T> std::shared_ptr<CsrHdMatrix<T>> SparseHamiltonian(const VT<PauliTerm<T>> &hams, Index n_qubits) { VT<std::shared_ptr<CsrHdMatrix<T>>> sp_hams(hams.size()); #pragma omp parallel for schedule(static) for (Index i = 0; i < static_cast<Index>(hams.size()); i++) { auto pm = GetPauliMat(hams[i], n_qubits); sp_hams[i] = PauliMatToCsrHdMatrix(pm); pm->Reset(); } Index tot = static_cast<Index>(hams.size()); while (tot > 1) { Index half = tot / 2 + tot % 2; #pragma omp parallel for schedule(static) num_threads(half) for (Index i = half; i < tot; i++) { sp_hams[i - half] = Csr_Plus_Csr(sp_hams[i - half], sp_hams[i]); sp_hams[i]->Reset(); } tot = half; } return sp_hams[0]; } template <typename T, typename T2> T2 *Csr_Dot_Vec(std::shared_ptr<CsrHdMatrix<T>> a, T2 *vec) { auto dim = a->dim_; auto c_vec = reinterpret_cast<CTP<T2>>(vec); auto new_vec = reinterpret_cast<CTP<T2>>(malloc(sizeof(CT<T2>) * dim)); // auto nnz = a->nnz_; auto data = a->data_; auto indptr = a->indptr_; auto indices = a->indices_; #pragma omp parallel for schedule(static) for (Index i = 0; i < dim; i++) { CT<T2> sum = {0.0, 0.0}; for (Index j = indptr[i]; j < indptr[i + 1]; j++) { sum += data[j] * c_vec[indices[j]]; } new_vec[i] = sum; } free(vec); return reinterpret_cast<T2 *>(new_vec); } template <typename T, typename T2> T2 *Csr_Dot_Vec(std::shared_ptr<CsrHdMatrix<T>> a, std::shared_ptr<CsrHdMatrix<T>> b, T2 *vec) { auto dim = a->dim_; auto c_vec = reinterpret_cast<CTP<T2>>(vec); auto new_vec = reinterpret_cast<CTP<T2>>(malloc(sizeof(CT<T2>) * dim)); // auto nnz = a->nnz_; auto data = a->data_; auto indptr = a->indptr_; auto indices = a->indices_; auto data_b = b->data_; auto indptr_b = b->indptr_; auto indices_b = b->indices_; #pragma omp parallel for schedule(static) for (Index i = 0; i < dim; i++) { CT<T2> sum = {0.0, 0.0}; for (Index j = indptr[i]; j < indptr[i + 1]; j++) { sum += data[j] * c_vec[indices[j]]; } for (Index j = indptr_b[i]; j < indptr_b[i + 1]; j++) { sum += data_b[j] * c_vec[indices_b[j]]; } new_vec[i] = sum; } free(vec); return reinterpret_cast<T2 *>(new_vec); } } // namespace sparse } // namespace mindquantum #endif // MINDQUANTUM_SPARSE_ALGO_H_
pr66133.c
/* PR middle-end/66133 */ /* { dg-do run } */ #include <stdlib.h> #include <unistd.h> volatile int x; __attribute__((noinline)) void foo (void) { if (x == 0) { #pragma omp task { usleep (2000); exit (0); } } else abort (); } int main () { #pragma omp parallel num_threads (2) { #pragma omp barrier #pragma omp single foo (); } exit (0); }
GB_binop__eq_int32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__eq_int32) // A.*B function (eWiseMult): GB (_AemultB_08__eq_int32) // A.*B function (eWiseMult): GB (_AemultB_02__eq_int32) // A.*B function (eWiseMult): GB (_AemultB_04__eq_int32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__eq_int32) // A*D function (colscale): GB (_AxD__eq_int32) // D*A function (rowscale): GB (_DxB__eq_int32) // C+=B function (dense accum): GB (_Cdense_accumB__eq_int32) // C+=b function (dense accum): GB (_Cdense_accumb__eq_int32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__eq_int32) // C=scalar+B GB (_bind1st__eq_int32) // C=scalar+B' GB (_bind1st_tran__eq_int32) // C=A+scalar GB (_bind2nd__eq_int32) // C=A'+scalar GB (_bind2nd_tran__eq_int32) // C type: bool // A type: int32_t // B,b type: int32_t // BinaryOp: cij = (aij == bij) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int32_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int32_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x == y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_EQ || GxB_NO_INT32 || GxB_NO_EQ_INT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__eq_int32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__eq_int32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__eq_int32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type int32_t int32_t bwork = (*((int32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__eq_int32) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__eq_int32) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__eq_int32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__eq_int32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__eq_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__eq_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__eq_int32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__eq_int32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int32_t *Bx = (int32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int32_t bij = GBX (Bx, p, false) ; Cx [p] = (x == bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__eq_int32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; int32_t *Ax = (int32_t *) Ax_input ; int32_t y = (*((int32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int32_t aij = GBX (Ax, p, false) ; Cx [p] = (aij == y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x == aij) ; \ } GrB_Info GB (_bind1st_tran__eq_int32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij == y) ; \ } GrB_Info GB (_bind2nd_tran__eq_int32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t y = (*((const int32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_binop__times_fc64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__times_fc64 // A.*B function (eWiseMult): GB_AemultB__times_fc64 // A*D function (colscale): GB_AxD__times_fc64 // D*A function (rowscale): GB_DxB__times_fc64 // C+=B function (dense accum): GB_Cdense_accumB__times_fc64 // C+=b function (dense accum): GB_Cdense_accumb__times_fc64 // C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__times_fc64 // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__times_fc64 // C=scalar+B GB_bind1st__times_fc64 // C=scalar+B' GB_bind1st_tran__times_fc64 // C=A+scalar GB_bind2nd__times_fc64 // C=A'+scalar GB_bind2nd_tran__times_fc64 // C type: GxB_FC64_t // A type: GxB_FC64_t // B,b type: GxB_FC64_t // BinaryOp: cij = GB_FC64_mul (aij, bij) #define GB_ATYPE \ GxB_FC64_t #define GB_BTYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ GxB_FC64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ GxB_FC64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = GB_FC64_mul (x, y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_TIMES || GxB_NO_FC64 || GxB_NO_TIMES_FC64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB_Cdense_ewise3_accum__times_fc64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__times_fc64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__times_fc64 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__times_fc64 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type GxB_FC64_t GxB_FC64_t bwork = (*((GxB_FC64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__times_fc64 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t *GB_RESTRICT Cx = (GxB_FC64_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__times_fc64 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t *GB_RESTRICT Cx = (GxB_FC64_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__times_fc64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__times_fc64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__times_fc64 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t *Cx = (GxB_FC64_t *) Cx_output ; GxB_FC64_t x = (*((GxB_FC64_t *) x_input)) ; GxB_FC64_t *Bx = (GxB_FC64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t bij = Bx [p] ; Cx [p] = GB_FC64_mul (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__times_fc64 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; GxB_FC64_t *Cx = (GxB_FC64_t *) Cx_output ; GxB_FC64_t *Ax = (GxB_FC64_t *) Ax_input ; GxB_FC64_t y = (*((GxB_FC64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; Cx [p] = GB_FC64_mul (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC64_t aij = Ax [pA] ; \ Cx [pC] = GB_FC64_mul (x, aij) ; \ } GrB_Info GB_bind1st_tran__times_fc64 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ GxB_FC64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t x = (*((const GxB_FC64_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC64_t aij = Ax [pA] ; \ Cx [pC] = GB_FC64_mul (aij, y) ; \ } GrB_Info GB_bind2nd_tran__times_fc64 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t y = (*((const GxB_FC64_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
ClientComm.h
/*! @brief Flag for checking if this header has already been included. */ #ifndef YGGCLIENTCOMM_H_ #define YGGCLIENTCOMM_H_ #include <../tools.h> #include <CommBase.h> #include <DefaultComm.h> #include "../datatypes/datatypes.h" #ifdef __cplusplus /* If this is a C++ compiler, use C linkage */ extern "C" { #endif // Handle is send address // Info is response static unsigned _client_rand_seeded = 0; /*! @brief Create a new channel. @param[in] comm comm_t * Comm structure initialized with new_comm_base. @returns int -1 if the address could not be created. */ static inline int new_client_address(comm_t *comm) { #ifdef _OPENMP #pragma omp critical (client) { #endif if (!(_client_rand_seeded)) { srand(ptr2seed(comm)); _client_rand_seeded = 1; } #ifdef _OPENMP } #endif comm->type = _default_comm; return new_default_address(comm); }; /*! @brief Initialize a client communicator. @param[in] comm comm_t * Comm structure initialized with init_comm_base. @returns int -1 if the comm could not be initialized. */ static inline int init_client_comm(comm_t *comm) { int ret = 0; ygglog_debug("init_client_comm: Creating a client comm"); #ifdef _OPENMP #pragma omp critical (client) { #endif if (!(_client_rand_seeded)) { srand(ptr2seed(comm)); _client_rand_seeded = 1; } #ifdef _OPENMP } #endif // Called to create temp comm for send/recv if ((strlen(comm->name) == 0) && (strlen(comm->address) > 0)) { comm->type = _default_comm; return init_default_comm(comm); } // Called to initialize/create client comm dtype_t *dtype_out = NULL; if (strlen(comm->direction) > 0) { dtype_out = create_dtype_format(comm->direction, 0, false); if (dtype_out == NULL) { ygglog_error("init_client_comm: Failed to create output datatype."); return -1; } } comm_t *handle; if (strlen(comm->name) == 0) { handle = new_comm_base(comm->address, "send", _default_comm, dtype_out); sprintf(handle->name, "client_request.%s", comm->address); } else { handle = init_comm_base(comm->name, "send", _default_comm, dtype_out); } ret = init_default_comm(handle); strcpy(comm->address, handle->address); comm->handle = (void*)handle; // Keep track of response comms int *ncomm = (int*)malloc(sizeof(int)); if (ncomm == NULL) { ygglog_error("init_client_comm: Failed to malloc ncomm."); return -1; } ncomm[0] = 0; handle->info = (void*)ncomm; strcpy(comm->direction, "send"); comm->always_send_header = 1; comm_t ***info = (comm_t***)malloc(sizeof(comm_t**)); if (info == NULL) { ygglog_error("init_client_comm: Failed to malloc info."); return -1; } info[0] = NULL; comm->info = (void*)info; return ret; }; static inline int get_client_response_count(const comm_t* x) { comm_t *handle = (comm_t*)(x->handle); int out = 0; if (handle != NULL) { out = ((int*)(handle->info))[0]; } return out; }; static inline void set_client_response_count(const comm_t* x, const int new_val) { comm_t *handle = (comm_t*)(x->handle); if (handle != NULL) { int *count = (int*)(handle->info); count[0] = new_val; } }; static inline void inc_client_response_count(const comm_t* x) { comm_t *handle = (comm_t*)(x->handle); if (handle != NULL) { int *count = (int*)(handle->info); count[0]++; } }; static inline void dec_client_response_count(const comm_t* x) { comm_t *handle = (comm_t*)(x->handle); if (handle != NULL) { int *count = (int*)(handle->info); count[0]--; } }; static inline void free_client_response_count(comm_t *x) { comm_t *handle = (comm_t*)(x->handle); if (handle != NULL) { int *count = (int*)(handle->info); free(count); handle->info = NULL; } }; /*! @brief Perform deallocation for client communicator. @param[in] x comm_t* Pointer to communicator to deallocate. @returns int 1 if there is and error, 0 otherwise. */ static inline int free_client_comm(comm_t *x) { if (x->info != NULL) { comm_t ***info = (comm_t***)(x->info); if (info[0] != NULL) { int ncomm = get_client_response_count(x); int i; for (i = 0; i < ncomm; i++) { if (info[0][i] != NULL) { free_default_comm(info[0][i]); free_comm_base(info[0][i]); free(info[0][i]); } } free(*info); info[0] = NULL; } free(info); x->info = NULL; } free_client_response_count(x); if (x->handle != NULL) { comm_t *handle = (comm_t*)(x->handle); free_default_comm(handle); free_comm_base(handle); free(x->handle); x->handle = NULL; } return 0; }; /*! @brief Get number of messages in the comm. @param[in] x comm_t* Communicator to check. @returns int Number of messages. -1 indicates an error. */ static inline int client_comm_nmsg(const comm_t* x) { comm_t *handle = (comm_t*)(x->handle); int ret = default_comm_nmsg(handle); return ret; }; /*! @brief Create response comm and add info to header. @param[in] x comm_t* structure that header will be sent to. @param[in] head comm_head_t Prexisting header structure. @returns comm_head_t Header structure that includes the additional information about the response comm. */ static inline comm_head_t client_response_header(const comm_t* x, comm_head_t head) { // Initialize new comm int ncomm = get_client_response_count(x); comm_t ***res_comm = (comm_t***)(x->info); res_comm[0] = (comm_t**)realloc(res_comm[0], sizeof(comm_t*)*(ncomm + 1)); if (res_comm[0] == NULL) { ygglog_error("client_response_header: Failed to realloc response comm."); head.valid = 0; return head; } dtype_t * dtype_copy = copy_dtype(x->datatype); res_comm[0][ncomm] = new_comm_base(NULL, "recv", _default_comm, dtype_copy); int ret = new_default_address(res_comm[0][ncomm]); if (ret < 0) { ygglog_error("client_response_header(%s): could not create response comm", x->name); head.valid = 0; return head; } res_comm[0][ncomm]->sent_eof[0] = 1; res_comm[0][ncomm]->recv_eof[0] = 1; inc_client_response_count(x); ncomm = get_client_response_count(x); ygglog_debug("client_response_header(%s): Created response comm number %d", x->name, ncomm); // Add address & request ID to header strcpy(head.response_address, res_comm[0][ncomm - 1]->address); sprintf(head.request_id, "%d", rand()); ygglog_debug("client_response_header(%s): response_address = %s, request_id = %s", x->name, head.response_address, head.request_id); return head; }; /*! @brief Send a message to the comm. @param[in] x comm_t* structure that comm should be sent to. @param[in] data character pointer to message that should be sent. @param[in] len size_t length of message to be sent. @returns int 0 if send succesfull, -1 if send unsuccessful. */ static inline int client_comm_send(const comm_t* x, const char *data, const size_t len) { int ret; ygglog_debug("client_comm_send(%s): %d bytes", x->name, len); if (x->handle == NULL) { ygglog_error("client_comm_send(%s): no request comm registered", x->name); return -1; } comm_t *req_comm = (comm_t*)(x->handle); ret = default_comm_send(req_comm, data, len); if (is_eof(data)) { req_comm->sent_eof[0] = 1; } return ret; }; /*! @brief Receive a message from an input comm. @param[in] x comm_t* structure that message should be sent to. @param[out] data char ** pointer to allocated buffer where the message should be saved. This should be a malloc'd buffer if allow_realloc is 1. @param[in] len const size_t length of the allocated message buffer in bytes. @param[in] allow_realloc const int If 1, the buffer will be realloced if it is not large enought. Otherwise an error will be returned. @returns int -1 if message could not be received. Length of the received message if message was received. */ static inline int client_comm_recv(const comm_t* x, char **data, const size_t len, const int allow_realloc) { ygglog_debug("client_comm_recv(%s)", x->name); if ((x->info == NULL) || (get_client_response_count(x) == 0)) { ygglog_error("client_comm_recv(%s): no response comm registered", x->name); return -1; } comm_t ***res_comm = (comm_t***)(x->info); int ret = default_comm_recv(res_comm[0][0], data, len, allow_realloc); if (ret < 0) { ygglog_error("client_comm_recv(%s): default_comm_recv returned %d", x->name, ret); return ret; } // Close response comm and decrement count of response comms ygglog_debug("client_comm_recv(%s): default_comm_recv returned %d", x->name, ret); free_default_comm(res_comm[0][0]); free_comm_base(res_comm[0][0]); free(res_comm[0][0]); dec_client_response_count(x); int nresp = get_client_response_count(x); memmove(*res_comm, *res_comm + 1, nresp*sizeof(comm_t*)); return ret; }; #ifdef __cplusplus /* If this is a C++ compiler, end C linkage */ } #endif #endif /*YGGCLIENTCOMM_H_*/
tmp_par.c
#include <stdio.h> #include <omp.h> // #include <omp.h> // #include <stdio.h> // #include <stdlib.h> int main(int argc, char** argv){ double valor = 0; // double passo; // passo = 1.0/(double)2147480000; #pragma omp parallel for shared(count) reduction(+:valor) for(int count=0; count < 2147480000; count++){ valor = valor + 4.0/(1.0 + ((count + 0.5)*(1.0/(double)2147480000))*((count + 0.5)*(1.0/(double)2147480000))); } valor = valor*(1.0/(double)2147480000); printf("%f\n", valor); return 0; }
image.h
#pragma once #include <vector> #include <cmath> #include <map> #include <string> #include <algorithm> #include <omp.h> #include "CImg.h" #undef max #undef min typedef double Float; enum class ColorMode {GRAY, LUMIANCE, R, G, B, AVG}; struct Image { // Image() {} Image(int w, int h, Float default_val = 0):W(w), H(h) { data = new Float* [H]; for (int i = 0; i < H; ++i) data[i] = new Float[W]; Clear(default_val); } Image(const Image& img) { for (int i = 0; i < H; ++i) delete[] data[i]; delete[] data; H = img.H; W = img.W; data = new Float * [H]; for (int i = 0; i < H; ++i) data[i] = new Float[W]; #pragma omp parallel for num_threads(8) for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { data[i][j] = img.data[i][j]; } } } ~Image() { for (int i = 0; i < H; ++i) delete[] data[i]; delete[] data; } Float Get(int x, int y) const { return data[y][x]; } Float& Get(int x, int y) { return data[y][x]; } Image& operator=(const Image& img) { if (H != img.H || W != img.W) { for (int i = 0; i < H; ++i) delete[] data[i]; delete[] data; H = img.H; W = img.W; data = new Float * [H]; for (int i = 0; i < H; ++i) data[i] = new Float[W]; } #pragma omp parallel for num_threads(8) for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { data[i][j] = img.data[i][j]; } } return *this; } void Clear(Float default_val) { #pragma omp parallel for num_threads(8) for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { data[i][j] = default_val; } } } void UpdatePixel(int x, int y, Float length) { #pragma omp atomic data[y][x] += length; } void DrawLineLength(const std::pair<int, int>& p1, const std::pair<int, int>& p2) { int x1 = p1.first, y1 = p1.second; int x2 = p2.first, y2 = p2.second; if (x1 == x2) { int y_min = std::min(y1, y2); int y_max = std::max(y1, y2); for (int y = y_min; y <= y_max; ++y) { UpdatePixel(x1, y, 1); } return; } if (y1 == y2) { int x_min = std::min(x1, x2); int x_max = std::max(x1, x2); for (int x = x_min; x <= x_max; ++x) { UpdatePixel(x, y1, 1); } return; } Float k = (y2 - y1) / (x2 - x1); if ((x1 <= x2 && y1 <= y2) || (x1 >= x2 && y1 >= y2)) { int x_min = std::min(x1, x2); int x_max = std::max(x1, x2); int y_min = std::min(y1, y2); int y_max = std::max(y1, y2); Float ky = y_max - y_min + 1; Float kx = x_max - x_min + 1; int x = x_min, y = y_min; Float xx = x, yy = y; while (x <= x_max && y <= y_max) { int tmp_x = x, tmp_y = y; Float delta_x = x + 1 - xx; Float delta_y = y + 1 - yy; Float tx = delta_x / kx; Float ty = delta_y / ky; Float len; if (tx - ty > 1e-5) { // UP y += 1; len = std::sqrt((y - yy) * (y - yy) + (ty * kx) * (ty * kx)); xx += ty * kx; yy = y; } else if (ty - tx > 1e-5) { // RIGHT x += 1; len = std::sqrt((x - xx) * (x - xx) + (tx * ky) * (tx * ky)); xx = x; yy += tx * ky; } else { // UP-RIGHT x += 1; y += 1; len = std::sqrt((x - xx) * (x - xx) + (y - yy) * (y - yy)); xx = x; yy = y; } UpdatePixel(tmp_x, tmp_y, len); } } else { // [xmin, ymax] => [xmax, ymin] int x_min = std::min(x1, x2); int x_max = std::max(x1, x2); int y_min = std::min(y1, y2); int y_max = std::max(y1, y2); int x = x_min, y = y_max; Float xx = x, yy = y; Float ky = y_max - y_min + 1; Float kx = x_max - x_min + 1; while (x <= x_max && y >= y_min) { int tmp_x = x, tmp_y = y; Float delta_x = x + 1 - xx; Float delta_y = yy - (y - 1); Float tx = delta_x / kx; Float ty = delta_y / ky; Float len; if (tx - ty > 1e-5) { // DOWN y -= 1; len = std::sqrt((y - yy) * (y - yy) + (ty * kx) * (ty * kx)); xx += ty * kx; yy = y; } else if (ty - tx > 1e-5) { // RIGHT x += 1; len = std::sqrt((x - xx) * (x - xx) + (tx * ky) * (tx * ky)); xx = x; yy -= tx * ky; } else { // DOWN-RIGHT x += 1; y -= 1; len = std::sqrt((x - xx) * (x - xx) + (y - yy) * (y - yy)); xx = x; yy = y; } UpdatePixel(tmp_x, tmp_y, len); } } } void DrawLineCount(const std::pair<int, int>& p1, const std::pair<int, int>& p2) { int x1 = p1.first, y1 = p1.second; int x2 = p2.first, y2 = p2.second; int dx, dy, i, e; int incx, incy, inc1, inc2; int x, y; dx = x2 - x1; dy = y2 - y1; if (dx < 0) dx = -dx; if (dy < 0) dy = -dy; incx = 1; if (x2 < x1) incx = -1; incy = 1; if (y2 < y1) incy = -1; x = x1; y = y1; if (dx > dy) { UpdatePixel(x, y, 1); e = 2 * dy - dx; inc1 = 2 * (dy - dx); inc2 = 2 * dy; for (i = 0; i < dx; i++) { if (e >= 0) { y += incy; e += inc1; } else e += inc2; x += incx; UpdatePixel(x, y, 1); } } else { UpdatePixel(x, y, 1); e = 2 * dx - dy; inc1 = 2 * (dx - dy); inc2 = 2 * dx; for (i = 0; i < dy; i++) { if (e >= 0) { x += incx; e += inc1; } else e += inc2; y += incy; UpdatePixel(x, y, 1); } } } void DrawLineBinary(const std::pair<int, int>& p1, const std::pair<int, int>& p2) { int x1 = p1.first, y1 = p1.second; int x2 = p2.first, y2 = p2.second; int dx, dy, i, e; int incx, incy, inc1, inc2; int x, y; dx = x2 - x1; dy = y2 - y1; if (dx < 0) dx = -dx; if (dy < 0) dy = -dy; incx = 1; if (x2 < x1) incx = -1; incy = 1; if (y2 < y1) incy = -1; x = x1; y = y1; if (dx > dy) { data[y][x] = 0; e = 2 * dy - dx; inc1 = 2 * (dy - dx); inc2 = 2 * dy; for (i = 0; i < dx; i++) { if (e >= 0) { y += incy; e += inc1; } else e += inc2; x += incx; data[y][x] = 0; } } else { //data[y][x] += 1.0 / 255; data[y][x] = 0; e = 2 * dx - dy; inc1 = 2 * (dx - dy); inc2 = 2 * dx; for (i = 0; i < dy; i++) { if (e >= 0) { x += incx; e += inc1; } else e += inc2; y += incy; //data[y][x] += 1.0 / 255; data[y][x] = 0; } } } Float Max() const { Float shared_max = -1; #pragma omp parallel { Float max_value = -1; #pragma omp for nowait for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { max_value = std::max(max_value, data[i][j]); } } #pragma omp critical { shared_max = std::max(shared_max, max_value); } } return shared_max; } Float Min() const { Float shared_min = std::numeric_limits<Float>::max(); #pragma omp parallel { Float min_value = std::numeric_limits<Float>::max(); #pragma omp for nowait for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { min_value = std::min(min_value, data[i][j]); } } #pragma omp critical { shared_min = std::min(shared_min, min_value); } } return shared_min; } Float Mean() const { return Sum() / Float(W * H); } Float Sum() const { Float sum = 0; #pragma omp parallel for reduction(+:sum) num_threads(8) for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { sum += data[i][j]; } } return sum; } void Write(const std::string& name, int _W=-1, int _H=-1) const { cimg_library::CImg<Float> image(W, H, 1, 1); for (int j = 0; j < H; j++) { for (int i = 0; i < W; i++) { Float c = data[j][i]; c = c > 0 ? c : 0; c = c < 1 ? c : 1; c = c * 255; image(i, j, 0, 0) = c; } } if (_W > 0 && _H > 0) { image = image.resize(_W, _H, -100, -100, 6); } image.save(name.c_str()); } void Load(const std::string& name, ColorMode mode = ColorMode::LUMIANCE) const { cimg_library::CImg<Float> image(name.c_str()); if (image.width() != W || image.height() != H) { printf("Resize input image from [%d, %d] to [%d, %d].\n", image.width(), image.height(), W, H); image = image.resize(W, H, -100, -100, 6); } for (int j = 0; j < H; j++) { for (int i = 0; i < W; i++) { Float r = image(i, j, 0, 0) / 255.0; Float g = image(i, j, 0, 1) / 255.0; Float b = image(i, j, 0, 2) / 255.0; Float pixel_value; switch (mode) { case ColorMode::GRAY: pixel_value = 0.2989 * r + 0.5870 * g + 0.1140 * b; break; case ColorMode::LUMIANCE: pixel_value = 0.212671 * r + 0.715160 * g + 0.072169 * b; break; case ColorMode::R: pixel_value = r; break; case ColorMode::G: pixel_value = g; break; case ColorMode::B: pixel_value = b; break; case ColorMode::AVG: pixel_value = (r + g + b) / 3.0; break; default: pixel_value = 0.212671 * r + 0.715160 * g + 0.072169 * b; break; } data[j][i] = pixel_value; } } } Float** data; int W, H; };
simdsort.h
// // // simdsort.h // // // Copyright 2020- J. Makino all rights resesrved. // // sort with avx2 (etc) #include <stdbool.h> #include <assert.h> #include <time.h> #if defined(AVX2) || defined(AVX512) #include <x86intrin.h> #endif #if defined(SVE) #ifdef __ARM_FEATURE_SVE #include <arm_sve.h> #endif /* __ARM_FEATURE_SVE */ #endif #ifdef AVX2 void make_permute_and_popcount_table_for_avx2(__m256i * stable, int* ptable, bool upper) { // lower 4 bits: 1 if smaller than pivot // upper 4 bits: 1 if larger than pivot for (int i=0;i<16;i++){ int count=0; int mask=0; int32_t * p = (int32_t*)(stable+i); for(int k=0;k<4;k++){ if ((1<<k)&i){ int index = count*2;; if (upper){ index = 6-index; } p[index] = k*2; p[index+1] = k*2+1; count++; } } ptable[i]=count; // fprintf(stderr, "i=%x count=%x ",i, count); // for (int ii=0;ii<8;ii++){ // fprintf(stderr, " %x",p[ii]); // } // fprintf(stderr, "\n"); } } #endif #ifdef AVX512 void make_permute_and_popcount_table_for_avx512(__m512i * stable, int* ptable, bool upper) { // lower 4 bits: 1 if smaller than pivot // upper 4 bits: 1 if larger than pivot for (int i=0;i<256;i++){ int count=0; int mask=0; int64_t * p = (int64_t*)(stable+i); for(int k=0;k<8;k++){ if ((1<<k)&i){ int index = count;; if (upper){ index = 7-index; } p[index] = k; count++; } } ptable[i]=count; //fprintf(stderr, "i=%x count=%x ",i, count); // for (int ii=0;ii<8;ii++){ // fprintf(stderr, " %lx",p[ii]); // } // fprintf(stderr, "\n"); } } void make_mask_table_for_avx512(__mmask8 * table) { // 4 bits: 1 if larger than pivot for (int i=0;i<256;i++){ int count=0; for(int k=0;k<8;k++){ if ((1<<k)&i){ count++; } } int mask=0; for(int k=0;k<count;k++){ mask |= 1<<(7-k); } table[i]=mask; } } static __m512i permute_table_lower_avx512[256]; static __m512i permute_table_upper_avx512[256]; static int popcount_table_upper_avx512[256]; static int popcount_table_lower_avx512[256]; static __mmask8 mask_table_avx512[256]; #endif #ifdef AVX2 void make_single_permute_and_popcount_table_for_avx2(__m256i * stable, int* ptable) { // lower 4 bits: 1 if smaller than pivot // upper 4 bits: 1 if larger than pivot for (int i=0;i<16;i++){ int count=0; int countl=0; int mask=0; int32_t * p = (int32_t*)(stable+i); for(int k=0;k<4;k++){ if ((1<<k)&i){ int index = 6-count*2; p[index] = k*2; p[index+1] = k*2+1; count++; }else{ int index = countl*2; p[index] = k*2; p[index+1] = k*2+1; countl++; } } ptable[i]=count; // fprintf(stderr, "i=%x count=%x ",i, count); // for (int ii=0;ii<8;ii++){ // fprintf(stderr, " %x",p[ii]); // } // fprintf(stderr, "\n"); } } void make_mask_table_for_avx2(__m256i * table) { // 4 bits: 1 if larger than pivot for (int i=0;i<16;i++){ int count=0; for(int k=0;k<4;k++){ if ((1<<k)&i){ count++; } } int64_t * p = (int64_t *) (table + i); for(int k=0;k<4;k++){p[k]=0;} for(int k=0;k<count;k++){p[3-k]=-1;} } } static __m256i permute_table_lower[16]; static __m256i permute_table_upper[16]; static int popcount_table_upper[16]; static int popcount_table_lower[16]; static __m256i mask_table[16]; void dump_tables(__m256i * stable, int* ptable) { for(int i=0;i<16;i++){ fprintf(stderr, "i=%x %x", i, ptable[i]); int32_t * p = (int32_t*)(stable+i); for (int ii=0;ii<8;ii++){ fprintf(stderr, " %x",p[ii]); } fprintf(stderr, "\n"); } } void dump_sort_table() { dump_tables(permute_table_upper, popcount_table_upper); dump_tables(permute_table_lower, popcount_table_lower); } #endif void init_sort_table() { #ifdef AVX2 make_permute_and_popcount_table_for_avx2(permute_table_upper, popcount_table_upper, true); make_permute_and_popcount_table_for_avx2(permute_table_lower, popcount_table_lower, false); make_mask_table_for_avx2(mask_table); #endif #ifdef AVX512 make_permute_and_popcount_table_for_avx512(permute_table_upper_avx512, popcount_table_upper_avx512, true); make_permute_and_popcount_table_for_avx512(permute_table_lower_avx512, popcount_table_lower_avx512, false); make_mask_table_for_avx512(mask_table_avx512); #endif } inline double GetWtime() { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC,&ts )){ printf("GetWtime Failed\n"); } return ((double) ts.tv_sec)+ ts.tv_nsec*1e-9; } static double time0; void init_timer() { time0=GetWtime(); } void print_dt(char* s) { double time=GetWtime(); printf("%s %g\n", s, time-time0); time0=GetWtime(); } int compare_int64_t(const void *a, const void *b) { int64_t ua = *((int64_t*)a); int64_t ub = *((int64_t*)b); if (ua<ub){ return -1; }else if(ua==ub){ return 0; }else{ return 1; } } void sort_int64_array( int64_t * r, int lo, int up ) { int i, j; int64_t tempr; // fprintf(stderr, "called with %d %d\n", lo, up); while ( up>lo ) { i = lo; j = up; tempr = r[lo]; /*** Split data in two ***/ while ( i<j ) { for ( ; r[j]> tempr; j-- ); for ( r[i]=r[j]; i<j && r[i]<=tempr; i++ ); r[j] = r[i]; } r[i] = tempr; /*** Sort recursively, the smallest first ***/ if ( i-lo < up-i ) { sort_int64_array(r,lo,i-1); lo = i+1; }else{ sort_int64_array(r,i+1,up); up = i-1; } } } void sort_int64_array2( int64_t * r, int lo, int up ) { if (up-lo<1) return; // fprintf(stderr, "called with %d %d\n", lo, up); int i, j; int64_t tempr; i = lo; j = up; tempr = r[lo]; /*** Split data in two ***/ while ( i<j ) { for ( ; r[j]> tempr; j-- ); for ( r[i]=r[j]; i<j && r[i]<=tempr; i++ ); r[j] = r[i]; } r[i] = tempr; sort_int64_array2(r,lo,i-1); sort_int64_array2(r,i+1,up); } void sort_int64( int64_t * r, int n) { sort_int64_array(r, 0, n-1); } #define SIMD_WIDTH 4 int block_partition(int64_t* data, int64_t pibot, int n) { int64_t work[n]; #pragma omp simd //#pragma GCC ivdep for(int i=0;i<n;i++){ work[i]=data[i]; } int l= -1; int h=n; int i; for(i=0;i<n;i++){ if(work[i]< pibot){ l++; data[l]=work[i]; }else if(work[i]> pibot){ h--; data[h]=work[i]; } } for(i=l+1; i<h; i++){ data[i]=pibot; } return i-1; } #ifdef AVX2 typedef union m256di{ __m256d d; __m256i i; __m256 f; }M256DI, *PM256DI; #include "bitonic8.h" void dump256(__m256i* pdata, char * s) { fprintf(stderr, "%s ", s); int64_t * p = (int64_t*) pdata; for(int i=0;i<4; i++){ fprintf(stderr, " %ld", p[i]); } fprintf(stderr, "\n"); } int simd_partition_avx2(int64_t* data, int64_t pivot, int n, int*hi) { int n4 = (n+3)/4; int nb = n4*4; __m256i work256[n4]; int64_t * work = (int64_t*) work256; __m256d* src = (__m256d*)data; __m256d* dest = (__m256d*)work; // fprintf(stderr, "addresses = %lx %lx\n",(int64_t) src, (int64_t) dest); for(int i=0;i<n4;i++){ dest[i]=_mm256_loadu_pd((double*)(src+i)); } int l= -1; int h=n; int i; int n4l = n/4; __m256i* pwork = (__m256i*)work; __m256i pivotv = _mm256_broadcastq_epi64(*((__m128i*)(&pivot))); for(int ii=0;ii<n4l;ii++){ #if 0 int i4 = ii<<2; for(i=i4; i<i4+4; i++){ if(work[i]> pivot){ h--; data[h]=work[i]; }else if(work[i]< pivot){ l++; data[l]=work[i]; } } #else register union m256di u, u2; u.i = _mm256_cmpgt_epi64(pivotv, pwork[ii]); int maskl = _mm256_movemask_pd(u.d); u.i = _mm256_cmpgt_epi64( pwork[ii], pivotv); int masku = _mm256_movemask_pd(u.d); register union m256di lower, upper; int dl = popcount_table_upper[maskl]; int dh = popcount_table_upper[masku]; // int dl = _mm_popcnt_u32(maskl); // int dh = _mm_popcnt_u32(masku); lower.f =_mm256_permutevar8x32_ps(*((__m256*)(pwork+ii)), *((__m256i*)(permute_table_lower +maskl))); _mm256_storeu_pd((double*)(data+l+1), lower.d); upper.f =_mm256_permutevar8x32_ps(*((__m256*)(pwork+ii)), *((__m256i*)(permute_table_upper +masku))); _mm256_maskstore_pd((double*)(data+h-4), mask_table[masku], upper.d); l+=dl; h-=dh; #endif } for(i=n4l*4;i<n;i++){ if(work[i]< pivot){ l++; data[l]=work[i]; }else if(work[i]> pivot){ h--; data[h]=work[i]; } } for(i=l+1; i<h; i++){ data[i]=pivot; } *hi=h; return l+1; } int simd_partition_2part_avx2(int64_t* data, int64_t pivot, int n) { int n4 = (n+3)/4; int nb = n4*4; __m256i work256[n4]; int64_t * work = (int64_t*) work256; __m256d* src = (__m256d*)(data+1); __m256d* dest = (__m256d*)work; // fprintf(stderr, "addresses = %lx %lx\n",(int64_t) src, (int64_t) dest); for(int i=0;i<n4;i++){ dest[i]=_mm256_loadu_pd((double*)(src+i)); } int l= -1; int h=n; int i; int n4l = (n-1)/4; __m256i* pwork = (__m256i*)work; __m256i pivotv = _mm256_broadcastq_epi64(*((__m128i*)(&pivot))); for(int ii=0;ii<n4l;ii++){ #if 0 int i4 = ii<<2; for(i=i4; i<i4+4; i++){ if(work[i]> pivot){ h--; data[h]=work[i]; }else{ l++; data[l]=work[i]; } } #else register union m256di u, u2; u.i = _mm256_cmpgt_epi64( pwork[ii], pivotv); int masku = _mm256_movemask_pd(u.d); register union m256di lower, upper; int dh = popcount_table_upper[masku]; int dl = 4-dh; upper.f =_mm256_permutevar8x32_ps(*((__m256*)(pwork+ii)), *((__m256i*)(permute_table_upper +masku))); _mm256_storeu_pd((double*)(data+l+1), upper.d); _mm256_maskstore_pd((double*)(data+h-4), mask_table[masku], upper.d); l+=dl; h-=dh; #endif } for(i=n4l*4;i<n-1;i++){ if(work[i]> pivot){ h--; data[h]=work[i]; }else{ l++; data[l]=work[i]; } } data[l+1]=pivot; return l+1; } #endif #ifdef AVX512 #ifndef AVX512_TYPE typedef union m512di{ __m512d d; __m512i i; __m512 f; }M512DI,*PM512DI ; #endif #include "bitonic16.h" void dump512(__m512i* pdata, char * s) { fprintf(stderr, "%s ", s); int64_t * p = (int64_t*) pdata; for(int i=0;i<8; i++){ fprintf(stderr, " %lx", p[i]); } fprintf(stderr, "\n"); } int simd_partition_avx512(int64_t* data, int64_t pivot, int n, int*hi) { // if (n < 8){ // return simd_partition_avx2(data, pivot, n); // } int n8 = (n+7)/8; int nb = n8*8; __m512i work256[n8]; int64_t * work = (int64_t*) work256; __m512d* src = (__m512d*)data; __m512d* dest = (__m512d*)work; for(int i=0;i<n8;i++){ dest[i]=_mm512_loadu_pd((double*)(src+i)); } int l= -1; int h=n; int i; int n8l = n/8; __m512i* pwork = (__m512i*)work; __m512i pivotv = _mm512_broadcastq_epi64(*((__m128i*)(&pivot))); for(int ii=0;ii<n8l;ii++){ #if 0 int i8 = ii<<3; for(i=i8; i<i8+8; i++){ if(work[i]> pivot){ h--; dat<a[h]=work[i]; }else if(work[i]< pivot){ l++; data[l]=work[i]; } } #else __mmask8 maskl = _mm512_cmpgt_epi64_mask(pivotv, pwork[ii]); __mmask8 masku = _mm512_cmpgt_epi64_mask( pwork[ii], pivotv); int dl = _mm_popcnt_u32(maskl); int dh = _mm_popcnt_u32(masku); _mm512_mask_compressstoreu_pd((double*)(data+l+1), maskl, *((__m512d*)(pwork+ii))); _mm512_mask_compressstoreu_pd((double*)(data+h-dh), masku, *((__m512d*)(pwork+ii))); l+=dl; h-=dh; #endif } int nremain = n -n8l*8; if (nremain > 0){ int ii = n8l; __mmask8 maskr =(__mmask8) ((1<<nremain)-1); __mmask8 maskl = _mm512_mask_cmpgt_epi64_mask(maskr,pivotv, pwork[ii]); __mmask8 masku = _mm512_mask_cmpgt_epi64_mask(maskr, pwork[ii], pivotv); int dl = _mm_popcnt_u32(maskl); int dh = _mm_popcnt_u32(masku); _mm512_mask_compressstoreu_pd((double*)(data+l+1), maskl, *((__m512d*)(pwork+ii))); _mm512_mask_compressstoreu_pd((double*)(data+h-dh), masku, *((__m512d*)(pwork+ii))); l+=dl; h-=dh; } #if 0 for(i=n8l*8;i<n;i++){ if(work[i]< pivot){ l++; data[l]=work[i]; }else if(work[i]> pivot){ h--; data[h]=work[i]; } } #endif for(i=l+1; i<h; i++){ data[i]=pivot; } *hi = h; return l+1; } int simd_partition_arrays_avx512_n1(uint64_t* data, int n) { uint64_t pivot = data[0]; int n8 = (n+7)/8; int nb = n8*8; __m512i work256[n8]; uint64_t * work = (int64_t*) work256; __m512d* src = (__m512d*)data; __m512d* dest = (__m512d*)work; for(int i=0;i<n8;i++){ dest[i]=_mm512_loadu_pd((double*)(src+i)); } int l= -1; int h=n; int i; int n8l = n/8; __m512i* pwork = (__m512i*)work; __m512i pivotv = _mm512_broadcastq_epi64(*((__m128i*)(&pivot))); for(int ii=0;ii<n8l;ii++){ __mmask8 maskl = _mm512_cmpgt_epu64_mask(pivotv, pwork[ii]); __mmask8 masku = _mm512_cmpgt_epu64_mask( pwork[ii], pivotv); int dl = _mm_popcnt_u32(maskl); int dh = _mm_popcnt_u32(masku); _mm512_mask_compressstoreu_pd((double*)(data+l+1), maskl, *((__m512d*)(pwork+ii))); _mm512_mask_compressstoreu_pd((double*)(data+h-dh), masku, *((__m512d*)(pwork+ii))); l+=dl; h-=dh; } int nremain = n -n8l*8; if (nremain > 0){ int ii = n8l; __mmask8 maskr =(__mmask8) ((1<<nremain)-1); __mmask8 maskl = _mm512_mask_cmpgt_epu64_mask(maskr,pivotv, pwork[ii]); __mmask8 masku = _mm512_mask_cmpgt_epu64_mask(maskr, pwork[ii], pivotv); int dl = _mm_popcnt_u32(maskl); int dh = _mm_popcnt_u32(masku); _mm512_mask_compressstoreu_pd((double*)(data+l+1), maskl, *((__m512d*)(pwork+ii))); _mm512_mask_compressstoreu_pd((double*)(data+h-dh), masku, *((__m512d*)(pwork+ii))); l+=dl; h-=dh; } for(i=l+1; i<h; i++){ data[i]=pivot; } return i-1; } #if 0 int simd_partition_arrays_avx512_n2(uint64_t* data, uint64_t* data1, int n) { uint64_t pivot = data[0]; uint64_t pivot1 = data1[0]; int n8 = (n+7)/8; int nb = n8*8; __m512i work256[n8]; __m512i work2561[n8]; uint64_t * work = (int64_t*) work256; uint64_t * work1 = (int64_t*) work2561; __m512d* src = (__m512d*)data; __m512d* dest = (__m512d*)work; for(int i=0;i<n8;i++){ dest[i]=_mm512_loadu_pd((double*)(src+i)); } __m512d* src = (__m512d*)data1; __m512d* dest = (__m512d*)work1; for(int i=0;i<n8;i++){ dest[i]=_mm512_loadu_pd((double*)(src+i)); } int l= -1; int h=n; int i; int n8l = n/8; __m512i* pwork = (__m512i*)work; __m512i* pwork1 = (__m512i*)work1; __m512i pivotv = _mm512_broadcastq_epi64(*((__m128i*)(&pivot))); __m512i pivotv1 = _mm512_broadcastq_epi64(*((__m128i*)(&pivot1))); for(int ii=0;ii<n8l;ii++){ __mmask8 maskl = _mm512_cmpgt_epu64_mask(pivotv, pwork[ii]); __mmask8 masku = _mm512_cmpgt_epu64_mask( pwork[ii], pivotv); __mmask8 maskeq = _mm512_cmpeq_epu64_mask( pwork[ii], pivotv); int dl = _mm_popcnt_u32(maskl); int dh = _mm_popcnt_u32(masku); _mm512_mask_compressstoreu_pd((double*)(data+l+1), maskl, *((__m512d*)(pwork+ii))); _mm512_mask_compressstoreu_pd((double*)(data+h-dh), masku, *((__m512d*)(pwork+ii))); l+=dl; h-=dh; } int nremain = n -n8l*8; if (nremain > 0){ int ii = n8l; __mmask8 maskr =(__mmask8) ((1<<nremain)-1); __mmask8 maskl = _mm512_mask_cmpgt_epu64_mask(maskr,pivotv, pwork[ii]); __mmask8 masku = _mm512_mask_cmpgt_epu64_mask(maskr, pwork[ii], pivotv); int dl = _mm_popcnt_u32(maskl); int dh = _mm_popcnt_u32(masku); _mm512_mask_compressstoreu_pd((double*)(data+l+1), maskl, *((__m512d*)(pwork+ii))); _mm512_mask_compressstoreu_pd((double*)(data+h-dh), masku, *((__m512d*)(pwork+ii))); l+=dl; h-=dh; } for(i=l+1; i<h; i++){ data[i]=pivot; } return i-1; } #endif int simd_partition_arrays_avx512(uint64_t** data, int nwords, int lo, int n) { if (nwords==1){ return simd_partition_arrays_avx512_n1(data[0]+lo,n); } } #endif #ifdef SVE #include "bitonic16sve.h" void dumpsve(svint64_t v, char *s) { fprintf(stderr, "%s ", s); int64_t x[8]; svst1_s64(svptrue_b64(),x, v); for(int i=0;i<8;i++){ fprintf(stderr, " %lx", x[i]); } fprintf(stderr, "\n"); } void dump512(int64_t * pdata, char * s) { fprintf(stderr, "%s ", s); int64_t * p = (int64_t*) pdata; for(int i=0;i<8; i++){ fprintf(stderr, " %lx", p[i]); } fprintf(stderr, "\n"); } int simd_partition_sve_old(int64_t* data, int64_t pivot, int n) { int nsve = svcntd(); int n8 = (n+nsve)/nsve; int nb = n8*nsve; int64_t __attribute__ ((aligned(64))) work[nb]; svbool_t ptrue =svptrue_b64(); for(int i=0;i<nb;i+=nsve){ svst1_s64(ptrue, work+i, svld1_s64(ptrue, data+i)); } int l= -1; int h=n; int i; int n8l = n/nsve; svint64_t pivotv = svdup_s64(pivot); for(int i8=0;i8<n8l*nsve;i8+=nsve){ #if 0 for(i=i8; i<i8+8; i++){ if(work[i]> pivot){ h--; dat<a[h]=work[i]; }else if(work[i]< pivot){ l++; data[l]=work[i]; } } #else svint64_t val =svld1_s64(ptrue, work+i8); svbool_t maskl = svcmpgt_s64(ptrue, pivotv,val); svbool_t masku = svcmpgt_s64(ptrue, val, pivotv); int dl = svcntp_b64(ptrue, maskl); int dh = svcntp_b64(ptrue, masku); svst1_s64(ptrue, data+l+1, svcompact_s64(maskl, val)); svbool_t maskustore = svwhilelt_b64(0,dh); svst1_s64(maskustore, data+h-dh, svcompact_s64(masku, val)); l+=dl; h-=dh; #endif } for(i=n8l*8;i<n;i++){ if(work[i]< pivot){ l++; data[l]=work[i]; }else if(work[i]> pivot){ h--; data[h]=work[i]; } } for(i=l+1; i<h; i++){ data[i]=pivot; } return i-1; } int simd_partition_sve(int64_t* data, int64_t pivot, int n, int* hi) { int nsve = svcntd(); int n8 = (n+nsve)/nsve; int nb = n8*nsve; int64_t __attribute__ ((aligned(64))) work[nb]; svbool_t ptrue =svptrue_b64(); for(int i=0;i<nb;i+=nsve){ svst1_s64(ptrue, work+i, svld1_s64(ptrue, data+i)); } int l= -1; int h=n; int i; int n8l = n/nsve; svint64_t pivotv = svdup_s64(pivot); #if 0 for(int i8=0;i8<n8l*nsve;i8+=nsve){ for(i=i8; i<i8+8; i++){ if(work[i]> pivot){ h--; dat<a[h]=work[i]; }else if(work[i]< pivot){ l++; data[l]=work[i]; } } } for(i=n8l*8;i<n;i++){ if(work[i]< pivot){ l++; data[l]=work[i]; }else if(work[i]> pivot){ h--; data[h]=work[i]; } } #else for(int i8=0;i8<n;i8+=nsve){ svbool_t pmask= svwhilelt_b64(i8,n); svint64_t val =svld1_s64(pmask, work+i8); svbool_t maskl = svcmpgt_s64(pmask, pivotv,val); svbool_t masku = svcmpgt_s64(pmask, val, pivotv); int dl = svcntp_b64(pmask, maskl); int dh = svcntp_b64(pmask, masku); svst1_s64(pmask, data+l+1, svcompact_s64(maskl, val)); svbool_t maskustore = svwhilelt_b64(0,dh); svst1_s64(maskustore, data+h-dh, svcompact_s64(masku, val)); l+=dl; h-=dh; } #endif for(i=l+1; i<h; i++){ data[i]=pivot; } *hi = h; return l+1; } #endif void dump_data(int64_t* data, int n, char* message) { printf("%s ", message); for(int i=0;i<n; i++){ printf(" %lx", data[i]); } printf("\n"); } void simd_sort_int64_array_2part( int64_t * r, int lo, int up ) { // printf("called with %d %d\n", lo, up); if (up-lo<1) return; int i, j; int64_t tempr; // dump_data( r+lo, up-lo+1, "before"); if (up-lo<1) return; #ifdef AVX2 i=simd_partition_2part_avx2(r+lo, r[lo], up-lo+1); #endif // dump_data( r+lo, up-lo+1, "after "); // printf("i=%d\n", i); simd_sort_int64_array_2part(r,lo,lo+i); simd_sort_int64_array_2part(r,lo+i+1,up); } void simd_sort_int64_array( int64_t * r, int lo, int up ) { // fprintf(stderr, "called with %d %d\n", lo, up); if (up-lo<1) return; #ifdef AVX2 if (up-lo+1<=8){ // fprintf(stderr, "call bitonic8 with %d\n", up-lo+1); bitonic8(r+lo, up-lo+1); return; } #endif #if defined(AVX512) || defined(SVE) if (up-lo+1<=16){ // fprintf(stderr, "call bitonic16 with %d\n", up-lo+1); bitonic16(r+lo, up-lo+1); return; } #endif int i, j, hi; int64_t tempr; // dump_data( r+lo, up-lo+1, "before"); #ifdef AVX2 i=simd_partition_avx2(r+lo, r[lo], up-lo+1, &hi); #endif #ifdef AVX512 i=simd_partition_avx512(r+lo, r[lo], up-lo+1, &hi); #endif #ifdef SVE i=simd_partition_sve(r+lo, r[lo], up-lo+1, &hi); #endif // dump_data( r+lo, up-lo+1, "after "); // printf("i=%d\n", i); simd_sort_int64_array(r,lo,lo+i-1); simd_sort_int64_array(r,lo+hi,up); } #if 0 // not implemented yet void simd_sort_uint64_arrays( int64_t ** r, int nwords, int lo, int up ) { printf("called with %d %d\n", lo, up); if (up-lo<1) return; int i, j; int64_t tempr; dump_data( r+lo, up-lo+1, "before"); #ifdef AVX2 i=simd_partition_avx2(r+lo, r[lo], up-lo+1); #endif #ifdef AVX512 i=simd_partition_arrays_avx512(r, nwords, lo, up-lo+1); #endif #ifdef SVE i=simd_partition_sve(r+lo, r[lo], up-lo+1); #endif dump_data( r+lo, up-lo+1, "after "); // printf("i=%d\n", i); simd_sort_int64_array(r,lo,lo+i-1); simd_sort_int64_array(r,lo+i+1,up); } #endif void simd_sort_int64( int64_t * r, int n) { static int initialized=0; if (initialized==0){ init_sort_table(); #ifdef AVX2 initialize_lsmask(); #endif initialized=1; } // simd_sort_int64_array_2part(r, 0, n-1); simd_sort_int64_array(r, 0, n-1); } #if 0 // not implemented yet void simd_sort_unt64s( uint64_t ** r, int nwords, int n) { static int initialized=0; if (initialized==0){ init_sort_table(); initialized=1; } simd_sort_uint64_arrays(r, nwords, 0, n-1); } #endif
TNV_core.c
/* * This work is part of the Core Imaging Library developed by * Visual Analytics and Imaging System Group of the Science Technology * Facilities Council, STFC * * Copyright 2017 Daniil Kazantsev * Copyright 2017 Srikanth Nagella, Edoardo Pasca * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "TNV_core.h" /* * C-OMP implementation of Total Nuclear Variation regularisation model (2D + channels) [1] * The code is modified from the implementation by Joan Duran <joan.duran@uib.es> see * "denoisingPDHG_ipol.cpp" in Joans Collaborative Total Variation package * * Input Parameters: * 1. Noisy volume of 2D + channel dimension, i.e. 3D volume * 2. lambda - regularisation parameter * 3. Number of iterations [OPTIONAL parameter] * 4. eplsilon - tolerance constant [OPTIONAL parameter] * 5. print information: 0 (off) or 1 (on) [OPTIONAL parameter] * * Output: * 1. Filtered/regularized image * * [1]. Duran, J., Moeller, M., Sbert, C. and Cremers, D., 2016. Collaborative total variation: a general framework for vectorial TV models. SIAM Journal on Imaging Sciences, 9(1), pp.116-151. */ float TNV_CPU_main(float *Input, float *u, float lambda, int maxIter, float tol, int dimX, int dimY, int dimZ) { long k, p, q, r, DimTotal; float taulambda; float *u_upd, *gx, *gy, *gx_upd, *gy_upd, *qx, *qy, *qx_upd, *qy_upd, *v, *vx, *vy, *gradx, *grady, *gradx_upd, *grady_upd, *gradx_ubar, *grady_ubar, *div, *div_upd; p = 1l; q = 1l; r = 0l; lambda = 1.0f/(2.0f*lambda); DimTotal = (long)(dimX*dimY*dimZ); /* PDHG algorithm parameters*/ float tau = 0.5f; float sigma = 0.5f; float theta = 1.0f; // Auxiliar vectors u_upd = calloc(DimTotal, sizeof(float)); gx = calloc(DimTotal, sizeof(float)); gy = calloc(DimTotal, sizeof(float)); gx_upd = calloc(DimTotal, sizeof(float)); gy_upd = calloc(DimTotal, sizeof(float)); qx = calloc(DimTotal, sizeof(float)); qy = calloc(DimTotal, sizeof(float)); qx_upd = calloc(DimTotal, sizeof(float)); qy_upd = calloc(DimTotal, sizeof(float)); v = calloc(DimTotal, sizeof(float)); vx = calloc(DimTotal, sizeof(float)); vy = calloc(DimTotal, sizeof(float)); gradx = calloc(DimTotal, sizeof(float)); grady = calloc(DimTotal, sizeof(float)); gradx_upd = calloc(DimTotal, sizeof(float)); grady_upd = calloc(DimTotal, sizeof(float)); gradx_ubar = calloc(DimTotal, sizeof(float)); grady_ubar = calloc(DimTotal, sizeof(float)); div = calloc(DimTotal, sizeof(float)); div_upd = calloc(DimTotal, sizeof(float)); // Backtracking parameters float s = 1.0f; float gamma = 0.75f; float beta = 0.95f; float alpha0 = 0.2f; float alpha = alpha0; float delta = 1.5f; float eta = 0.95f; // PDHG algorithm parameters taulambda = tau * lambda; float divtau = 1.0f / tau; float divsigma = 1.0f / sigma; float theta1 = 1.0f + theta; /*allocate memory for taulambda */ //taulambda = (float*) calloc(dimZ, sizeof(float)); //for(k=0; k < dimZ; k++) {taulambda[k] = tau*lambda[k];} // Apply Primal-Dual Hybrid Gradient scheme int iter = 0; float residual = fLarge; float ubarx, ubary; for(iter = 0; iter < maxIter; iter++) { // Argument of proximal mapping of fidelity term #pragma omp parallel for shared(v, u) private(k) for(k=0; k<dimX*dimY*dimZ; k++) {v[k] = u[k] + tau*div[k];} // Proximal solution of fidelity term proxG(u_upd, v, Input, taulambda, (long)(dimX), (long)(dimY), (long)(dimZ)); // Gradient of updated primal variable gradient(u_upd, gradx_upd, grady_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); // Argument of proximal mapping of regularization term #pragma omp parallel for shared(gradx_upd, grady_upd, gradx, grady) private(k, ubarx, ubary) for(k=0; k<dimX*dimY*dimZ; k++) { ubarx = theta1 * gradx_upd[k] - theta * gradx[k]; ubary = theta1 * grady_upd[k] - theta * grady[k]; vx[k] = ubarx + divsigma * qx[k]; vy[k] = ubary + divsigma * qy[k]; gradx_ubar[k] = ubarx; grady_ubar[k] = ubary; } proxF(gx_upd, gy_upd, vx, vy, sigma, p, q, r, (long)(dimX), (long)(dimY), (long)(dimZ)); // Update dual variable #pragma omp parallel for shared(qx_upd, qy_upd) private(k) for(k=0; k<dimX*dimY*dimZ; k++) { qx_upd[k] = qx[k] + sigma * (gradx_ubar[k] - gx_upd[k]); qy_upd[k] = qy[k] + sigma * (grady_ubar[k] - gy_upd[k]); } // Divergence of updated dual variable #pragma omp parallel for shared(div_upd) private(k) for(k=0; k<dimX*dimY*dimZ; k++) {div_upd[k] = 0.0f;} divergence(qx_upd, qy_upd, div_upd, dimX, dimY, dimZ); // Compute primal residual, dual residual, and backtracking condition float resprimal = 0.0f; float resdual = 0.0f; float product = 0.0f; float unorm = 0.0f; float qnorm = 0.0f; for(k=0; k<dimX*dimY*dimZ; k++) { float udiff = u[k] - u_upd[k]; float qxdiff = qx[k] - qx_upd[k]; float qydiff = qy[k] - qy_upd[k]; float divdiff = div[k] - div_upd[k]; float gradxdiff = gradx[k] - gradx_upd[k]; float gradydiff = grady[k] - grady_upd[k]; resprimal += fabs(divtau*udiff + divdiff); resdual += fabs(divsigma*qxdiff - gradxdiff); resdual += fabs(divsigma*qydiff - gradydiff); unorm += (udiff * udiff); qnorm += (qxdiff * qxdiff + qydiff * qydiff); product += (gradxdiff * qxdiff + gradydiff * qydiff); } float b = (2.0f * tau * sigma * product) / (gamma * sigma * unorm + gamma * tau * qnorm); // Adapt step-size parameters float dual_dot_delta = resdual * s * delta; float dual_div_delta = (resdual * s) / delta; if(b > 1) { // Decrease step-sizes to fit balancing principle tau = (beta * tau) / b; sigma = (beta * sigma) / b; alpha = alpha0; copyIm(u, u_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(gx, gx_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(gy, gy_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(qx, qx_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(qy, qy_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(gradx, gradx_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(grady, grady_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(div, div_upd, (long)(dimX), (long)(dimY), (long)(dimZ)); } else if(resprimal > dual_dot_delta) { // Increase primal step-size and decrease dual step-size tau = tau / (1.0f - alpha); sigma = sigma * (1.0f - alpha); alpha = alpha * eta; } else if(resprimal < dual_div_delta) { // Decrease primal step-size and increase dual step-size tau = tau * (1.0f - alpha); sigma = sigma / (1.0f - alpha); alpha = alpha * eta; } // Update variables taulambda = tau * lambda; //for(k=0; k < dimZ; k++) taulambda[k] = tau*lambda[k]; divsigma = 1.0f / sigma; divtau = 1.0f / tau; copyIm(u_upd, u, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(gx_upd, gx, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(gy_upd, gy, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(qx_upd, qx, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(qy_upd, qy, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(gradx_upd, gradx, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(grady_upd, grady, (long)(dimX), (long)(dimY), (long)(dimZ)); copyIm(div_upd, div, (long)(dimX), (long)(dimY), (long)(dimZ)); // Compute residual at current iteration residual = (resprimal + resdual) / ((float) (dimX*dimY*dimZ)); // printf("%f \n", residual); if (residual < tol) { printf("Iterations stopped at %i with the residual %f \n", iter, residual); break; } } printf("Iterations stopped at %i with the residual %f \n", iter, residual); free (u_upd); free(gx); free(gy); free(gx_upd); free(gy_upd); free(qx); free(qy); free(qx_upd); free(qy_upd); free(v); free(vx); free(vy); free(gradx); free(grady); free(gradx_upd); free(grady_upd); free(gradx_ubar); free(grady_ubar); free(div); free(div_upd); return *u; } float proxG(float *u_upd, float *v, float *f, float taulambda, long dimX, long dimY, long dimZ) { float constant; long k; constant = 1.0f + taulambda; #pragma omp parallel for shared(v, f, u_upd) private(k) for(k=0; k<dimZ*dimX*dimY; k++) { u_upd[k] = (v[k] + taulambda * f[k])/constant; //u_upd[(dimX*dimY)*k + l] = (v[(dimX*dimY)*k + l] + taulambda * f[(dimX*dimY)*k + l])/constant; } return *u_upd; } float gradient(float *u_upd, float *gradx_upd, float *grady_upd, long dimX, long dimY, long dimZ) { long i, j, k, l; // Compute discrete gradient using forward differences #pragma omp parallel for shared(gradx_upd,grady_upd,u_upd) private(i, j, k, l) for(k = 0; k < dimZ; k++) { for(j = 0; j < dimY; j++) { l = j * dimX; for(i = 0; i < dimX; i++) { // Derivatives in the x-direction if(i != dimX-1) gradx_upd[(dimX*dimY)*k + i+l] = u_upd[(dimX*dimY)*k + i+1+l] - u_upd[(dimX*dimY)*k + i+l]; else gradx_upd[(dimX*dimY)*k + i+l] = 0.0f; // Derivatives in the y-direction if(j != dimY-1) //grady_upd[(dimX*dimY)*k + i+l] = u_upd[(dimX*dimY)*k + i+dimY+l] -u_upd[(dimX*dimY)*k + i+l]; grady_upd[(dimX*dimY)*k + i+l] = u_upd[(dimX*dimY)*k + i+(j+1)*dimX] -u_upd[(dimX*dimY)*k + i+l]; else grady_upd[(dimX*dimY)*k + i+l] = 0.0f; }}} return 1; } float proxF(float *gx, float *gy, float *vx, float *vy, float sigma, int p, int q, int r, long dimX, long dimY, long dimZ) { // (S^p, \ell^1) norm decouples at each pixel // Spl1(gx, gy, vx, vy, sigma, p, num_channels, dim); float divsigma = 1.0f / sigma; // $\ell^{1,1,1}$-TV regularization // int i,j,k; // #pragma omp parallel for shared (gx,gy,vx,vy) private(i,j,k) // for(k = 0; k < dimZ; k++) { // for(i=0; i<dimX; i++) { // for(j=0; j<dimY; j++) { // gx[(dimX*dimY)*k + (i)*dimY + (j)] = SIGN(vx[(dimX*dimY)*k + (i)*dimY + (j)]) * MAX(fabs(vx[(dimX*dimY)*k + (i)*dimY + (j)]) - divsigma, 0.0f); // gy[(dimX*dimY)*k + (i)*dimY + (j)] = SIGN(vy[(dimX*dimY)*k + (i)*dimY + (j)]) * MAX(fabs(vy[(dimX*dimY)*k + (i)*dimY + (j)]) - divsigma, 0.0f); // }}} // Auxiliar vector float *proj, sum, shrinkfactor ; float M1,M2,M3,valuex,valuey,T,D,det,eig1,eig2,sig1,sig2,V1, V2, V3, V4, v0,v1,v2, mu1,mu2,sig1_upd,sig2_upd,t1,t2,t3; long i,j,k, ii, num; #pragma omp parallel for shared (gx,gy,vx,vy,p) private(i,ii,j,k,proj,num, sum, shrinkfactor, M1,M2,M3,valuex,valuey,T,D,det,eig1,eig2,sig1,sig2,V1, V2, V3, V4,v0,v1,v2,mu1,mu2,sig1_upd,sig2_upd,t1,t2,t3) for(i=0; i<dimX; i++) { for(j=0; j<dimY; j++) { proj = (float*) calloc (2,sizeof(float)); // Compute matrix $M\in\R^{2\times 2}$ M1 = 0.0f; M2 = 0.0f; M3 = 0.0f; for(k = 0; k < dimZ; k++) { valuex = vx[(dimX*dimY)*k + (j)*dimX + (i)]; valuey = vy[(dimX*dimY)*k + (j)*dimX + (i)]; M1 += (valuex * valuex); M2 += (valuex * valuey); M3 += (valuey * valuey); } // Compute eigenvalues of M T = M1 + M3; D = M1 * M3 - M2 * M2; det = sqrt(MAX((T * T / 4.0f) - D, 0.0f)); eig1 = MAX((T / 2.0f) + det, 0.0f); eig2 = MAX((T / 2.0f) - det, 0.0f); sig1 = sqrt(eig1); sig2 = sqrt(eig2); // Compute normalized eigenvectors V1 = V2 = V3 = V4 = 0.0f; if(M2 != 0.0f) { v0 = M2; v1 = eig1 - M3; v2 = eig2 - M3; mu1 = sqrtf(v0 * v0 + v1 * v1); mu2 = sqrtf(v0 * v0 + v2 * v2); if(mu1 > fTiny) { V1 = v1 / mu1; V3 = v0 / mu1; } if(mu2 > fTiny) { V2 = v2 / mu2; V4 = v0 / mu2; } } else { if(M1 > M3) { V1 = V4 = 1.0f; V2 = V3 = 0.0f; } else { V1 = V4 = 0.0f; V2 = V3 = 1.0f; } } // Compute prox_p of the diagonal entries sig1_upd = sig2_upd = 0.0f; if(p == 1) { sig1_upd = MAX(sig1 - divsigma, 0.0f); sig2_upd = MAX(sig2 - divsigma, 0.0f); } else if(p == INFNORM) { proj[0] = sigma * fabs(sig1); proj[1] = sigma * fabs(sig2); /*l1 projection part */ sum = fLarge; num = 0l; shrinkfactor = 0.0f; while(sum > 1.0f) { sum = 0.0f; num = 0; for(ii = 0; ii < 2; ii++) { proj[ii] = MAX(proj[ii] - shrinkfactor, 0.0f); sum += fabs(proj[ii]); if(proj[ii]!= 0.0f) num++; } if(num > 0) shrinkfactor = (sum - 1.0f) / num; else break; } /*l1 proj ends*/ sig1_upd = sig1 - divsigma * proj[0]; sig2_upd = sig2 - divsigma * proj[1]; } // Compute the diagonal entries of $\widehat{\Sigma}\Sigma^{\dagger}_0$ if(sig1 > fTiny) sig1_upd /= sig1; if(sig2 > fTiny) sig2_upd /= sig2; // Compute solution t1 = sig1_upd * V1 * V1 + sig2_upd * V2 * V2; t2 = sig1_upd * V1 * V3 + sig2_upd * V2 * V4; t3 = sig1_upd * V3 * V3 + sig2_upd * V4 * V4; for(k = 0; k < dimZ; k++) { gx[(dimX*dimY)*k + j*dimX + i] = vx[(dimX*dimY)*k + j*dimX + i] * t1 + vy[(dimX*dimY)*k + j*dimX + i] * t2; gy[(dimX*dimY)*k + j*dimX + i] = vx[(dimX*dimY)*k + j*dimX + i] * t2 + vy[(dimX*dimY)*k + j*dimX + i] * t3; } // Delete allocated memory free(proj); }} return 1; } float divergence(float *qx_upd, float *qy_upd, float *div_upd, long dimX, long dimY, long dimZ) { long i, j, k, l; #pragma omp parallel for shared(qx_upd,qy_upd,div_upd) private(i, j, k, l) for(k = 0; k < dimZ; k++) { for(j = 0; j < dimY; j++) { l = j * dimX; for(i = 0; i < dimX; i++) { if(i != dimX-1) { // ux[k][i+l] = u[k][i+1+l] - u[k][i+l] div_upd[(dimX*dimY)*k + i+1+l] -= qx_upd[(dimX*dimY)*k + i+l]; div_upd[(dimX*dimY)*k + i+l] += qx_upd[(dimX*dimY)*k + i+l]; } if(j != dimY-1) { // uy[k][i+l] = u[k][i+width+l] - u[k][i+l] //div_upd[(dimX*dimY)*k + i+dimY+l] -= qy_upd[(dimX*dimY)*k + i+l]; div_upd[(dimX*dimY)*k + i+(j+1)*dimX] -= qy_upd[(dimX*dimY)*k + i+l]; div_upd[(dimX*dimY)*k + i+l] += qy_upd[(dimX*dimY)*k + i+l]; } } } } return *div_upd; }
par_relax_more.c
/****************************************************************************** * * a few more relaxation schemes: Chebychev, FCF-Jacobi, CG - * these do not go through the CF interface (hypre_BoomerAMGRelaxIF) * *****************************************************************************/ #include "_hypre_parcsr_ls.h" #include "float.h" HYPRE_Int hypre_LINPACKcgtql1(HYPRE_Int*,double *,double *,HYPRE_Int *); /****************************************************************************** * *use max norm to estimate largest eigenvalue * *****************************************************************************/ HYPRE_Int hypre_ParCSRMaxEigEstimate(hypre_ParCSRMatrix *A, /* matrix to relax with */ HYPRE_Int scale, /* scale by diagonal?*/ double *max_eig) { double e_max; double row_sum, max_norm; double *col_val; double temp; double diag_value; HYPRE_Int pos_diag, neg_diag; HYPRE_Int start_row, end_row; HYPRE_Int row_length; HYPRE_Int *col_ind; HYPRE_Int j; HYPRE_Int i; /* estimate with the inf-norm of A - should be ok for SPD matrices */ start_row = hypre_ParCSRMatrixFirstRowIndex(A); end_row = hypre_ParCSRMatrixLastRowIndex(A); max_norm = 0.0; pos_diag = neg_diag = 0; for ( i = start_row; i <= end_row; i++ ) { HYPRE_ParCSRMatrixGetRow((HYPRE_ParCSRMatrix) A, i, &row_length, &col_ind, &col_val); row_sum = 0.0; for (j = 0; j < row_length; j++) { if (j==0) diag_value = fabs(col_val[j]); row_sum += fabs(col_val[j]); if ( col_ind[j] == i && col_val[j] > 0.0 ) pos_diag++; if ( col_ind[j] == i && col_val[j] < 0.0 ) neg_diag++; } if (scale) { if (diag_value != 0.0) row_sum = row_sum/diag_value; } if ( row_sum > max_norm ) max_norm = row_sum; HYPRE_ParCSRMatrixRestoreRow((HYPRE_ParCSRMatrix) A, i, &row_length, &col_ind, &col_val); } /* get max across procs */ hypre_MPI_Allreduce(&max_norm, &temp, 1, hypre_MPI_DOUBLE, hypre_MPI_MAX, hypre_ParCSRMatrixComm(A)); max_norm = temp; /* from Charles */ if ( pos_diag == 0 && neg_diag > 0 ) max_norm = - max_norm; /* eig estimates */ e_max = max_norm; /* return */ *max_eig = e_max; return hypre_error_flag; } /****************************************************************************** use CG to get the eigenvalue estimate scale means get eig est of (D^{-1/2} A D^{-1/2} ******************************************************************************/ HYPRE_Int hypre_ParCSRMaxEigEstimateCG(hypre_ParCSRMatrix *A, /* matrix to relax with */ HYPRE_Int scale, /* scale by diagonal?*/ HYPRE_Int max_iter, double *max_eig, double *min_eig) { HYPRE_Int i, j, err; hypre_ParVector *p; hypre_ParVector *s; hypre_ParVector *r; hypre_ParVector *ds; hypre_ParVector *u; double *tridiag; double *trioffd; double lambda_max , max_row_sum; double beta, gamma = 0.0, alpha, sdotp, gamma_old, alphainv; double diag; double lambda_min; double *s_data, *p_data, *ds_data, *u_data; HYPRE_Int local_size = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A)); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); double *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); /* check the size of A - don't iterate more than the size */ HYPRE_Int size = hypre_ParCSRMatrixGlobalNumRows(A); if (size < max_iter) max_iter = size; /* create some temp vectors: p, s, r , ds, u*/ r = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(r); hypre_ParVectorSetPartitioningOwner(r,0); p = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(p); hypre_ParVectorSetPartitioningOwner(p,0); s = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(s); hypre_ParVectorSetPartitioningOwner(s,0); ds = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(ds); hypre_ParVectorSetPartitioningOwner(ds,0); u = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(u); hypre_ParVectorSetPartitioningOwner(u,0); /* point to local data */ s_data = hypre_VectorData(hypre_ParVectorLocalVector(s)); p_data = hypre_VectorData(hypre_ParVectorLocalVector(p)); ds_data = hypre_VectorData(hypre_ParVectorLocalVector(ds)); u_data = hypre_VectorData(hypre_ParVectorLocalVector(u)); /* make room for tri-diag matrix */ tridiag = hypre_CTAlloc(double, max_iter+1); trioffd = hypre_CTAlloc(double, max_iter+1); for (i=0; i < max_iter + 1; i++) { tridiag[i] = 0; trioffd[i] = 0; } /* set residual to random */ hypre_ParVectorSetRandomValues(r,1); if (scale) { for (i = 0; i < local_size; i++) { diag = A_diag_data[A_diag_i[i]]; ds_data[i] = 1/sqrt(diag); } } else { /* set ds to 1 */ hypre_ParVectorSetConstantValues(ds,1.0); } /* gamma = <r,Cr> */ gamma = hypre_ParVectorInnerProd(r,p); /* for the initial filling of the tridiag matrix */ beta = 1.0; max_row_sum = 0.0; i = 0; while (i < max_iter) { /* s = C*r */ /* TO DO: C = diag scale */ hypre_ParVectorCopy(r, s); /*gamma = <r,Cr> */ gamma_old = gamma; gamma = hypre_ParVectorInnerProd(r,s); if (i==0) { beta = 1.0; /* p_0 = C*r */ hypre_ParVectorCopy(s, p); } else { /* beta = gamma / gamma_old */ beta = gamma / gamma_old; /* p = s + beta p */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j=0; j < local_size; j++) { p_data[j] = s_data[j] + beta*p_data[j]; } } if (scale) { /* s = D^{-1/2}A*D^{-1/2}*p */ for (j = 0; j < local_size; j++) { u_data[j] = ds_data[j] * p_data[j]; } hypre_ParCSRMatrixMatvec(1.0, A, u, 0.0, s); for (j = 0; j < local_size; j++) { s_data[j] = ds_data[j] * s_data[j]; } } else { /* s = A*p */ hypre_ParCSRMatrixMatvec(1.0, A, p, 0.0, s); } /* <s,p> */ sdotp = hypre_ParVectorInnerProd(s,p); /* alpha = gamma / <s,p> */ alpha = gamma/sdotp; /* get tridiagonal matrix */ alphainv = 1.0/alpha; tridiag[i+1] = alphainv; tridiag[i] *= beta; tridiag[i] += alphainv; trioffd[i+1] = alphainv; trioffd[i] *= sqrt(beta); /* x = x + alpha*p */ /* don't need */ /* r = r - alpha*s */ hypre_ParVectorAxpy( -alpha, s, r); i++; } /* eispack routine - eigenvalues return in tridiag and ordered*/ hypre_LINPACKcgtql1(&i,tridiag,trioffd,&err); lambda_max = tridiag[i-1]; lambda_min = tridiag[0]; /* hypre_printf("linpack max eig est = %g\n", lambda_max);*/ /* hypre_printf("linpack min eig est = %g\n", lambda_min);*/ hypre_ParVectorDestroy(r); hypre_ParVectorDestroy(s); hypre_ParVectorDestroy(p); hypre_ParVectorDestroy(ds); hypre_ParVectorDestroy(u); /* return */ *max_eig = lambda_max; *min_eig = lambda_min; return hypre_error_flag; } /****************************************************************************** Chebyshev relaxation Can specify order 1-4 (this is the order of the resid polynomial)- here we explicitly code the coefficients (instead of iteratively determining) variant 0: standard chebyshev this is rlx 11 if scale = 0, and 16 if scale == 1 variant 1: modified cheby: T(t)* f(t) where f(t) = (1-b/t) this is rlx 15 if scale = 0, and 17 if scale == 1 ratio indicates the percentage of the whole spectrum to use (so .5 means half, and .1 means 10percent) *******************************************************************************/ HYPRE_Int hypre_ParCSRRelax_Cheby(hypre_ParCSRMatrix *A, /* matrix to relax with */ hypre_ParVector *f, /* right-hand side */ double max_eig, double min_eig, double fraction, HYPRE_Int order, /* polynomial order */ HYPRE_Int scale, /* scale by diagonal?*/ HYPRE_Int variant, hypre_ParVector *u, /* initial/updated approximation */ hypre_ParVector *v /* temporary vector */, hypre_ParVector *r /*another temp vector */ ) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); double *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); double *u_data = hypre_VectorData(hypre_ParVectorLocalVector(u)); double *f_data = hypre_VectorData(hypre_ParVectorLocalVector(f)); double *v_data = hypre_VectorData(hypre_ParVectorLocalVector(v)); double *r_data = hypre_VectorData(hypre_ParVectorLocalVector(r)); double theta, delta; double den; double upper_bound, lower_bound; HYPRE_Int i, j; HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag); double coefs[5]; double mult; double *orig_u; double tmp_d; HYPRE_Int cheby_order; double *ds_data, *tmp_data; double diag; hypre_ParVector *ds; hypre_ParVector *tmp_vec; /* u = u + p(A)r */ if (order > 4) order = 4; if (order < 1) order = 1; /* we are using the order of p(A) */ cheby_order = order -1; /* make sure we are large enough - Adams et al. 2003 */ upper_bound = max_eig * 1.1; /* lower_bound = max_eig/fraction; */ lower_bound = (upper_bound - min_eig)* fraction + min_eig; /* theta and delta */ theta = (upper_bound + lower_bound)/2; delta = (upper_bound - lower_bound)/2; if (variant == 1 ) { switch ( cheby_order ) /* these are the corresponding cheby polynomials: u = u_o + s(A)r_0 - so order is one less that resid poly: r(t) = 1 - t*s(t) */ { case 0: coefs[0] = 1.0/theta; break; case 1: /* (del - t + 2*th)/(th^2 + del*th) */ den = (theta*theta + delta*theta); coefs[0] = (delta + 2*theta)/den; coefs[1] = -1.0/den; break; case 2: /* (4*del*th - del^2 - t*(2*del + 6*th) + 2*t^2 + 6*th^2)/(2*del*th^2 - del^2*th - del^3 + 2*th^3)*/ den = 2*delta*theta*theta - delta*delta*theta - pow(delta,3) + 2*pow(theta,3); coefs[0] = (4*delta*theta - pow(delta,2) + 6*pow(theta,2))/den; coefs[1] = -(2*delta + 6*theta)/den; coefs[2] = 2/den; break; case 3: /* -(6*del^2*th - 12*del*th^2 - t^2*(4*del + 16*th) + t*(12*del*th - 3*del^2 + 24*th^2) + 3*del^3 + 4*t^3 - 16*th^3)/(4*del*th^3 - 3*del^2*th^2 - 3*del^3*th + 4*th^4)*/ den = - (4*delta*pow(theta,3) - 3*pow(delta,2)*pow(theta,2) - 3*pow(delta,3)*theta + 4*pow(theta,4) ); coefs[0] = (6*pow(delta,2)*theta - 12*delta*pow(theta,2) + 3*pow(delta,3) - 16*pow(theta,3) )/den; coefs[1] = (12*delta*theta - 3*pow(delta,2) + 24*pow(theta,2))/den; coefs[2] = -( 4*delta + 16*theta)/den; coefs[3] = 4/den; break; } } else /* standard chebyshev */ { switch ( cheby_order ) /* these are the corresponding cheby polynomials: u = u_o + s(A)r_0 - so order is one less thatn resid poly: r(t) = 1 - t*s(t) */ { case 0: coefs[0] = 1.0/theta; break; case 1: /* ( 2*t - 4*th)/(del^2 - 2*th^2) */ den = delta*delta - 2*theta*theta; coefs[0] = -4*theta/den; coefs[1] = 2/den; break; case 2: /* (3*del^2 - 4*t^2 + 12*t*th - 12*th^2)/(3*del^2*th - 4*th^3)*/ den = 3*(delta*delta)*theta - 4*(theta*theta*theta); coefs[0] = (3*delta*delta - 12 *theta*theta)/den; coefs[1] = 12*theta/den; coefs[2] = -4/den; break; case 3: /*(t*(8*del^2 - 48*th^2) - 16*del^2*th + 32*t^2*th - 8*t^3 + 32*th^3)/(del^4 - 8*del^2*th^2 + 8*th^4)*/ den = pow(delta,4) - 8*delta*delta*theta*theta + 8*pow(theta,4); coefs[0] = (32*pow(theta,3)- 16*delta*delta*theta)/den; coefs[1] = (8*delta*delta - 48*theta*theta)/den; coefs[2] = 32*theta/den; coefs[3] = -8/den; break; } } orig_u = hypre_CTAlloc(double, num_rows); if (!scale) { /* get residual: r = f - A*u */ hypre_ParVectorCopy(f, r); hypre_ParCSRMatrixMatvec(-1.0, A, u, 1.0, r); for ( i = 0; i < num_rows; i++ ) { orig_u[i] = u_data[i]; u_data[i] = r_data[i] * coefs[cheby_order]; } for (i = cheby_order - 1; i >= 0; i-- ) { hypre_ParCSRMatrixMatvec(1.0, A, u, 0.0, v); mult = coefs[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { u_data[j] = mult * r_data[j] + v_data[j]; } } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for ( i = 0; i < num_rows; i++ ) { u_data[i] = orig_u[i] + u_data[i]; } } else /* scaling! */ { /*grab 1/sqrt(diagonal) */ ds = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(ds); hypre_ParVectorSetPartitioningOwner(ds,0); ds_data = hypre_VectorData(hypre_ParVectorLocalVector(ds)); tmp_vec = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(tmp_vec); hypre_ParVectorSetPartitioningOwner(tmp_vec,0); tmp_data = hypre_VectorData(hypre_ParVectorLocalVector(tmp_vec)); /* get ds_data and get scaled residual: r = D^(-1/2)f - * D^(-1/2)A*u */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j,diag) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_rows; j++) { diag = A_diag_data[A_diag_i[j]]; ds_data[j] = 1/sqrt(diag); r_data[j] = ds_data[j] * f_data[j]; } hypre_ParCSRMatrixMatvec(-1.0, A, u, 0.0, tmp_vec); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { r_data[j] += ds_data[j] * tmp_data[j]; } /* save original u, then start the iteration by multiplying r by the cheby coef.*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { orig_u[j] = u_data[j]; /* orig, unscaled u */ u_data[j] = r_data[j] * coefs[cheby_order]; } /* now do the other coefficients */ for (i = cheby_order - 1; i >= 0; i-- ) { /* v = D^(-1/2)AD^(-1/2)u */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { tmp_data[j] = ds_data[j] * u_data[j]; } hypre_ParCSRMatrixMatvec(1.0, A, tmp_vec, 0.0, v); /* u_new = coef*r + v*/ mult = coefs[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j,tmp_d) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { tmp_d = ds_data[j]* v_data[j]; u_data[j] = mult * r_data[j] + tmp_d; } } /* end of cheby_order loop */ /* now we have to scale u_data before adding it to u_orig*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { u_data[j] = orig_u[j] + ds_data[j]*u_data[j]; } hypre_ParVectorDestroy(ds); hypre_ParVectorDestroy(tmp_vec); }/* end of scaling code */ hypre_TFree(orig_u); return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_BoomerAMGRelax_FCFJacobi *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGRelax_FCFJacobi( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, double relax_weight, hypre_ParVector *u, hypre_ParVector *Vtemp) { HYPRE_Int i; HYPRE_Int relax_points[3]; HYPRE_Int relax_type = 0; hypre_ParVector *Ztemp = NULL; relax_points[0] = -1; /*F */ relax_points[1] = 1; /*C */ relax_points[2] = -1; /*F */ /* if we are on the coarsest level ,the cf_marker will be null and we just do one sweep regular jacobi */ if (cf_marker == NULL) { hypre_BoomerAMGRelax(A, f, cf_marker, relax_type, 0, relax_weight, 0.0, NULL, u, Vtemp, Ztemp); } else { for (i=0; i < 3; i++) hypre_BoomerAMGRelax(A, f, cf_marker, relax_type, relax_points[i], relax_weight, 0.0, NULL, u, Vtemp, Ztemp); } return hypre_error_flag; } /*-------------------------------------------------------------------------- * CG Smoother - * *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRRelax_CG( HYPRE_Solver solver, hypre_ParCSRMatrix *A, hypre_ParVector *f, hypre_ParVector *u, HYPRE_Int num_its) { HYPRE_PCGSetMaxIter(solver, num_its); /* max iterations */ HYPRE_ParCSRPCGSolve(solver, (HYPRE_ParCSRMatrix)A, (HYPRE_ParVector)f, (HYPRE_ParVector)u); #if 0 { HYPRE_Int myid; HYPRE_Int num_iterations; double final_res_norm; hypre_MPI_Comm_rank(hypre_MPI_COMM_WORLD, &myid); HYPRE_PCGGetNumIterations(solver, &num_iterations); HYPRE_PCGGetFinalRelativeResidualNorm(solver, &final_res_norm); if (myid ==0) { hypre_printf(" -----CG PCG Iterations = %d\n", num_iterations); hypre_printf(" -----CG PCG Final Relative Residual Norm = %e\n", final_res_norm); } } #endif return hypre_error_flag; } /* tql1.f -- this is the eispack translation - from Barry Smith in Petsc Note that this routine always uses real numbers (not complex) even if the underlying matrix is Hermitian. This is because the Lanczos process applied to Hermitian matrices always produces a real, symmetric tridiagonal matrix. */ double hypre_LINPACKcgpthy(double*,double*); HYPRE_Int hypre_LINPACKcgtql1(HYPRE_Int *n,double *d,double *e,HYPRE_Int *ierr) { /* System generated locals */ HYPRE_Int i__1,i__2; double d__1,d__2,c_b10 = 1.0; /* Local variables */ double c,f,g,h; HYPRE_Int i,j,l,m; double p,r,s,c2,c3 = 0.0; HYPRE_Int l1,l2; double s2 = 0.0; HYPRE_Int ii; double dl1,el1; HYPRE_Int mml; double tst1,tst2; /* THIS SUBROUTINE IS A TRANSLATION OF THE ALGOL PROCEDURE TQL1, */ /* NUM. MATH. 11, 293-306(1968) BY BOWDLER, MARTIN, REINSCH, AND */ /* WILKINSON. */ /* HANDBOOK FOR AUTO. COMP., VOL.II-LINEAR ALGEBRA, 227-240(1971). */ /* THIS SUBROUTINE FINDS THE EIGENVALUES OF A SYMMETRIC */ /* TRIDIAGONAL MATRIX BY THE QL METHOD. */ /* ON INPUT */ /* N IS THE ORDER OF THE MATRIX. */ /* D CONTAINS THE DIAGONAL ELEMENTS OF THE INPUT MATRIX. */ /* E CONTAINS THE SUBDIAGONAL ELEMENTS OF THE INPUT MATRIX */ /* IN ITS LAST N-1 POSITIONS. E(1) IS ARBITRARY. */ /* ON OUTPUT */ /* D CONTAINS THE EIGENVALUES IN ASCENDING ORDER. IF AN */ /* ERROR EXIT IS MADE, THE EIGENVALUES ARE CORRECT AND */ /* ORDERED FOR INDICES 1,2,...IERR-1, BUT MAY NOT BE */ /* THE SMALLEST EIGENVALUES. */ /* E HAS BEEN DESTROYED. */ /* IERR IS SET TO */ /* ZERO FOR NORMAL RETURN, */ /* J IF THE J-TH EIGENVALUE HAS NOT BEEN */ /* DETERMINED AFTER 30 ITERATIONS. */ /* CALLS CGPTHY FOR DSQRT(A*A + B*B) . */ /* QUESTIONS AND COMMENTS SHOULD BE DIRECTED TO BURTON S. GARBOW, */ /* MATHEMATICS AND COMPUTER SCIENCE DIV, ARGONNE NATIONAL LABORATORY */ /* THIS VERSION DATED AUGUST 1983. */ /* ------------------------------------------------------------------ */ double ds; --e; --d; *ierr = 0; if (*n == 1) { goto L1001; } i__1 = *n; for (i = 2; i <= i__1; ++i) { e[i - 1] = e[i]; } f = 0.; tst1 = 0.; e[*n] = 0.; i__1 = *n; for (l = 1; l <= i__1; ++l) { j = 0; h = (d__1 = d[l],fabs(d__1)) + (d__2 = e[l],fabs(d__2)); if (tst1 < h) { tst1 = h; } /* .......... LOOK FOR SMALL SUB-DIAGONAL ELEMENT .......... */ i__2 = *n; for (m = l; m <= i__2; ++m) { tst2 = tst1 + (d__1 = e[m],fabs(d__1)); if (tst2 == tst1) { goto L120; } /* .......... E(N) IS ALWAYS ZERO,SO THERE IS NO EXIT */ /* THROUGH THE BOTTOM OF THE LOOP .......... */ } L120: if (m == l) { goto L210; } L130: if (j == 30) { goto L1000; } ++j; /* .......... FORM SHIFT .......... */ l1 = l + 1; l2 = l1 + 1; g = d[l]; p = (d[l1] - g) / (e[l] * 2.); r = hypre_LINPACKcgpthy(&p,&c_b10); ds = 1.0; if (p < 0.0) ds = -1.0; d[l] = e[l] / (p + ds*r); d[l1] = e[l] * (p + ds*r); dl1 = d[l1]; h = g - d[l]; if (l2 > *n) { goto L145; } i__2 = *n; for (i = l2; i <= i__2; ++i) { d[i] -= h; } L145: f += h; /* .......... QL TRANSFORMATION .......... */ p = d[m]; c = 1.; c2 = c; el1 = e[l1]; s = 0.; mml = m - l; /* .......... FOR I=M-1 STEP -1 UNTIL L DO -- .......... */ i__2 = mml; for (ii = 1; ii <= i__2; ++ii) { c3 = c2; c2 = c; s2 = s; i = m - ii; g = c * e[i]; h = c * p; r = hypre_LINPACKcgpthy(&p,&e[i]); e[i + 1] = s * r; s = e[i] / r; c = p / r; p = c * d[i] - s * g; d[i + 1] = h + s * (c * g + s * d[i]); } p = -s * s2 * c3 * el1 * e[l] / dl1; e[l] = s * p; d[l] = c * p; tst2 = tst1 + (d__1 = e[l],fabs(d__1)); if (tst2 > tst1) { goto L130; } L210: p = d[l] + f; /* .......... ORDER EIGENVALUES .......... */ if (l == 1) { goto L250; } /* .......... FOR I=L STEP -1 UNTIL 2 DO -- .......... */ i__2 = l; for (ii = 2; ii <= i__2; ++ii) { i = l + 2 - ii; if (p >= d[i - 1]) { goto L270; } d[i] = d[i - 1]; } L250: i = 1; L270: d[i] = p; } goto L1001; /* .......... SET ERROR -- NO CONVERGENCE TO AN */ /* EIGENVALUE AFTER 30 ITERATIONS .......... */ L1000: *ierr = l; L1001: return 0; } /* cgtql1_ */ double hypre_LINPACKcgpthy(double *a,double *b) { /* System generated locals */ double ret_val,d__1,d__2,d__3; /* Local variables */ double p,r,s,t,u; /* FINDS DSQRT(A**2+B**2) WITHOUT OVERFLOW OR DESTRUCTIVE UNDERFLOW */ /* Computing MAX */ d__1 = fabs(*a),d__2 = fabs(*b); p = hypre_max(d__1,d__2); if (!p) { goto L20; } /* Computing MIN */ d__2 = fabs(*a),d__3 = fabs(*b); /* Computing 2nd power */ d__1 = hypre_min(d__2,d__3) / p; r = d__1 * d__1; L10: t = r + 4.; if (t == 4.) { goto L20; } s = r / t; u = s * 2. + 1.; p = u * p; /* Computing 2nd power */ d__1 = s / u; r = d__1 * d__1 * r; goto L10; L20: ret_val = p; return ret_val; } /* cgpthy_ */ /*-------------------------------------------------------------------------- * hypre_ParCSRRelax_L1_Jacobi (same as the one in AMS, but this allows CF) u += w D^{-1}(f - A u), where D_ii = ||A(i,:)||_1 *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRRelax_L1_Jacobi( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, double relax_weight, double *l1_norms, hypre_ParVector *u, hypre_ParVector *Vtemp ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); double *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); double *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle; HYPRE_Int n = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd); hypre_Vector *u_local = hypre_ParVectorLocalVector(u); double *u_data = hypre_VectorData(u_local); hypre_Vector *f_local = hypre_ParVectorLocalVector(f); double *f_data = hypre_VectorData(f_local); hypre_Vector *Vtemp_local = hypre_ParVectorLocalVector(Vtemp); double *Vtemp_data = hypre_VectorData(Vtemp_local); double *Vext_data = NULL; double *v_buf_data; HYPRE_Int i, j; HYPRE_Int ii, jj; HYPRE_Int num_sends; HYPRE_Int index, start; HYPRE_Int num_procs, my_id ; double zero = 0.0; double res; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(double, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); Vext_data = hypre_CTAlloc(double,num_cols_offd); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } if (num_procs > 1) { hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (relax_points == 0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += (relax_weight*res)/l1_norms[i]; } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += (relax_weight * res)/l1_norms[i]; } } } if (num_procs > 1) { hypre_TFree(Vext_data); hypre_TFree(v_buf_data); } return 0; }
files.c
/***************************************************************************** * * Elmer, A Finite Element Software for Multiphysical Problems * * Copyright 1st April 1995 - , CSC - IT Center for Science Ltd., Finland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library (in file ../LGPL-2.1); if not, write * to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ /******************************************************************************* * * IO handling for MATC. * ******************************************************************************* * * Author: Juha Ruokolainen * * Address: CSC - IT Center for Science Ltd. * Keilaranta 14, P.O. BOX 405 * 02101 Espoo, Finland * Tel. +358 0 457 2723 * Telefax: +358 0 457 2302 * EMail: Juha.Ruokolainen@csc.fi * * Date: 30 May 1996 * * Modified by: * * Date of modification: * ******************************************************************************/ /* * $Id: files.c,v 1.1.1.1 2005/04/14 13:29:14 vierinen Exp $ * * $Log: files.c,v $ * Revision 1.1.1.1 2005/04/14 13:29:14 vierinen * initial matc automake package * * Revision 1.2 1998/08/01 12:34:36 jpr * * Added Id, started Log. * * */ #include "elmer/matc.h" #include "str.h" /*********************************************************************** | | FILES.C - Last Edited 10. 8. 1988 | ***********************************************************************/ /*====================================================================== |Syntax of the manual pages: | |FUNCTION NAME(...) params ... | $ usage of the function and type of the parameters ? explane the effects of the function = return value and the type of value if not of type int @ globals effected directly by this routine ! current known bugs or limitations & functions called by this function ~ these functions may interest you as an alternative function or | because they control this function somehow ^=====================================================================*/ #define FILE_BINARY 0 #define FILE_ASCII 1 #define MAXFILES 32 static FILE *fil_fps[MAXFILES]; static FILE *fil_fps_save[3]; #pragma omp threadprivate(fil_fps, fil_fps_save) VARIABLE *fil_fread(var) VARIABLE *var; { VARIABLE *res; FILE *fp; int i, ind, len; ind = *MATR(var); if (ind < 0 || ind >= MAXFILES) { error("fread: Invalid file number.\n"); } else if (fil_fps[ind] == NULL) { error("fread: File not open.\n"); } fp = fil_fps[ind]; if (feof(fp)) { clearerr(fp); error("fread: end of file detected.\n"); } len = *MATR(NEXT(var)); if (len <= 0) { error("fread: invalid length specified.\n"); } res = var_temp_new(TYPE_DOUBLE, 1, (len+sizeof(double)-1)>>3); fread(MATR(res), 1, len, fp); if (feof(fp)) { clearerr(fp); error("fread: end of file detected.\n"); } if (ferror(fp)) { clearerr(fp); error("fread: error reading file.\n"); } return res; } VARIABLE *fil_fwrite(var) VARIABLE *var; { int i, ind, len; FILE *fp; ind = *MATR(var); if (ind < 0 || ind >= MAXFILES) { error("fwrite: Invalid file number.\n"); } else if (fil_fps[ind] == NULL) { error("fwrite: File not open.\n"); } fp = fil_fps[ind]; if (NEXT(NEXT(var)) != NULL) { len = *MATR(NEXT(NEXT(var))); if (len > MATSIZE(NEXT(var))) { error("fwrite: attempt to write more data than provided.\n"); } } else { len = MATSIZE(NEXT(var)); } fwrite(MATR(NEXT(var)), 1, len, fp); if (ferror(fp)) { clearerr(fp); error("fwrite: error writing file.\n"); } return (VARIABLE *)NULL; } VARIABLE *fil_fscanf(var) VARIABLE *var; { VARIABLE *res; FILE *fp; char *fmt = var_to_string(NEXT(var)); int i, ind, got; ind = *MATR(var); if (ind < 0 || ind >= MAXFILES) { error("fscanf: Invalid file number.\n"); } else if (fil_fps[ind] == NULL) { error("fscanf: File not open.\n"); } fp = fil_fps[ind]; if (feof(fp)) { clearerr(fp); error("fscanf: end of file detected.\n"); } got = fscanf(fp, fmt, &str_p[0], &str_p[1], &str_p[2], &str_p[3], &str_p[4], &str_p[5], &str_p[6], &str_p[7], &str_p[8], &str_p[9], &str_p[10], &str_p[11], &str_p[12], &str_p[13], &str_p[14], &str_p[15], &str_p[16], &str_p[17], &str_p[18], &str_p[19], &str_p[20], &str_p[21], &str_p[22], &str_p[23], &str_p[24], &str_p[25], &str_p[26], &str_p[27], &str_p[28], &str_p[29]); res = NULL; if (got > 0) { res = var_temp_new(TYPE_DOUBLE,1,got); for(i = 0; i < got; i++) { M(res,0,i) = str_p[i]; } } FREEMEM(fmt); if (feof(fp)) { clearerr(fp); error("fscanf: end of file detected.\n"); } if (ferror(fp)) { clearerr(fp); error("fscanf: error reading file.\n"); } return res; } VARIABLE *fil_fgets(var) VARIABLE *var; { VARIABLE *res; FILE *fp; int i, ind; ind = *MATR(var); if (ind < 0 || ind >= MAXFILES) { error("fgets: Invalid file number.\n"); } else if (fil_fps[ind] == NULL) { error("fgets: File not open.\n"); } fp = fil_fps[ind]; if (feof(fp)) { clearerr(fp); error("fgets: end of file detected.\n"); } fgets(str_pstr, STR_MAXLEN, fp); if (feof(fp)) { clearerr(fp); error("fgets: end of file detected.\n"); } if (ferror(fp)) { clearerr(fp); error("fgets: error reading file.\n"); } res = var_temp_new(TYPE_STRING, 1, strlen(str_pstr)-1); for(i = 0; i < strlen(str_pstr)-1; i++) M(res,0,i) = str_pstr[i]; return res; } VARIABLE *fil_fprintf(var) VARIABLE *var; { int i, ind; char *str; FILE *fp; ind = *MATR(var); if (ind < 0 || ind >= MAXFILES) { error("fprintf: Invalid file number.\n"); } else if (fil_fps[ind] == NULL) { error("fprintf: File not open.\n"); } fp = fil_fps[ind]; var = str_sprintf(NEXT(var)); str = var_to_string(var); fprintf(fp, "%s",str); var_delete_temp(var); FREEMEM(str); if (ferror(fp)) { clearerr(fp); error("fprintf: error writing file.\n"); } return (VARIABLE *)NULL; } VARIABLE *fil_fputs(var) VARIABLE *var; { char *str = var_to_string(NEXT(var)); int ind = *MATR(var); FILE *fp; if (ind < 0 || ind >= MAXFILES) { error("fputs: Invalid file number.\n"); } else if (fil_fps[ind] == NULL) { error("fputs: File not open.\n"); } fp = fil_fps[ind]; fprintf(fp, "%s", str); FREEMEM(str); if (ferror(fp)) { clearerr(fp); error("fprintf: error writing file.\n"); } return (VARIABLE *)NULL; } VARIABLE *fil_fopen(var) VARIABLE *var; { VARIABLE *res; char *name, *mode; int file; mode = var_to_string(NEXT(var)); name = var_to_string(var); for(file = 0; file < MAXFILES; file++) { if (fil_fps[file] == NULL) break; } if (file >= MAXFILES) { error("fopen: maximum number of files already open.\n"); } if ((fil_fps[file] = fopen(name, mode)) == (FILE *)NULL) { error("fopen: can't open file: %s.\n", name); } switch(file) { case 0: fil_fps_save[0] = math_in; math_in = fil_fps[0]; break; case 1: fil_fps_save[1] = math_out; math_out = fil_fps[1]; break; case 2: fil_fps_save[2] = math_err; math_err = fil_fps[2]; break; } res = var_temp_new(TYPE_DOUBLE, 1, 1); M(res,0,0) = file; FREEMEM(name); FREEMEM(mode); return res; } VARIABLE *fil_fclose(var) VARIABLE *var; { int file = *MATR(var); if (file < 0 || file >= MAXFILES) { error("fclose: Invalid file number.\n"); } switch(file) { case 0: math_in = fil_fps_save[0]; if ( fil_fps[0] != math_out && fil_fps[0] != NULL ) fclose(fil_fps[0]); fil_fps[0] = math_in; break; case 1: math_out = fil_fps_save[1]; if ( fil_fps[1] != math_out && fil_fps[1] != NULL ) fclose(fil_fps[1]); fil_fps[1] = math_out; break; case 2: math_err = fil_fps_save[2]; if ( fil_fps[2] != math_err && fil_fps[2] != NULL ) fclose(fil_fps[2]); fil_fps[2] = math_err; break; default: if (fil_fps[file] != NULL) fclose(fil_fps[file]); fil_fps[file] = NULL; break; } return (VARIABLE *)NULL; } VARIABLE *fil_freopen(var) VARIABLE *var; { int file = *MATR(var); fil_fclose(var); fil_fps[file] = NULL; var = fil_fopen(NEXT(var)); var_delete_temp(var); return (VARIABLE *)NULL; } VARIABLE *fil_save(ptr) VARIABLE *ptr; { VARIABLE *tmp; char *file; FILE *fp; int i, j, ascflg = FALSE; file = var_to_string(ptr); if ((fp = fopen(file, "w")) == (FILE *)NULL) { error( "save: can't open file: %s.\n", file ); } tmp = NEXT(ptr); if (NEXT(NEXT(ptr)) != (VARIABLE *)NULL) ascflg = M(NEXT(NEXT(ptr)), 0, 0); if (ascflg) { fprintf(fp, "%d %d %d %d\n", FILE_ASCII, TYPE(tmp), NROW(tmp), NCOL(tmp)); if (ferror(fp)) { fclose(fp); error("save: error writing file.\n"); } for(i = 0; i < NROW(tmp); i++) for(j = 0; j < NCOL(tmp); j++) { fprintf(fp, "%e\n", M(tmp, i, j)); if (ferror(fp)) { fclose(fp); error("save: error writing file.\n"); } } } else { fprintf(fp, "%d %d %d %d\n", FILE_BINARY, TYPE(tmp), NROW(tmp), NCOL(tmp)); if (ferror(fp)) { fclose(fp); error("save: error writing file.\n"); } fwrite(MATR(tmp), 1, MATSIZE(tmp), fp); if (ferror(fp)) { fclose(fp); error("save: error writing file.\n"); } } fclose(fp); FREEMEM(file); return NULL; } VARIABLE *fil_load(ptr) VARIABLE *ptr; { int i, j, ftype, type, ncol, nrow; VARIABLE *res; char *file; FILE *fp; file = var_to_string(ptr); if ((fp = fopen(file, "r")) == (FILE *)NULL) { error( "load: can't open file: %s.\n", file ); } fscanf(fp, "%d %d %d %d", &ftype, &type, &nrow, &ncol); if (ferror(fp)) { fclose(fp); error("load: error reading file.n"); } res = var_temp_new(type, nrow, ncol); if (ftype == FILE_ASCII) { for(i = 0; i < nrow; i++) for(j = 0; j < ncol; j++) { fscanf(fp, "%lf", &M(res, i, j)); if (ferror(fp)) { fclose(fp); error("load: error reading file.\n"); } } } else { fgetc(fp); fread(MATR(res), 1, MATSIZE(res), fp); if (ferror(fp)) { fclose(fp); error("load: error reading file.\n"); } } fclose(fp); FREEMEM(file); return res; } void fil_com_init() { static char *freadHelp = { "str = fread( fp,len )\n\n" "Read len character from file fp. File pointer fp shoud have been\n" "obtained from a call to fopen or freopen, or be the standard input\n" "file stdin. Characters are returned as function value.\n" "\n" "SEE ALSO: fopen,freopen,fgets,fscanf,matcvt,cvtmat.\n" }; static char *fscanfHelp = { "vec = fscanf( fp,format )\n\n" "Read file fp as given in format. Format is equal to C-language format\n" "File pointer fp shoud have been obtained from a call to fopen or freopen,\n" "or be the standard input.\n" "\n" "SEE ALSO: fopen,freopen,fgets,fread,matcvt,cvtmat.\n" }; static char *fgetsHelp = { "str = fgets( fp )\n\n" "Read next line from fp. File pointer fp shoud have been obtained from a call\n" "to fopen or freopen or be the standard input.\n" "\n" "SEE ALSO: fopen,freopen,fread,fscanf,matcvt,cvtmat.\n" }; static char *fwriteHelp = { "n = fwrite( fp, buf,len )\n\n" "Write len bytes form buf to file fp. File pointer fp shoud have been obtained\n" "from a call to fopen or freopen or be the standard output (stdout) or standard\n" "error (stderr). Return value is number of characters actually written.\n" "\n" "SEE ALSO: fopen,freopen,fputs,fprintf,matcvt,cvtmat.\n" }; static char *fprintfHelp = { "n = fprintf( fp, format[, vec] )\n\n" "Write formatted string to file fp. File pointer fp shoud have been obtained\n" "from a call to fopen or freopen or be the standard output (stdout) or standard\n" "error (stderr). The format is equal to C-language format.\n" "\n" "SEE ALSO: fopen,freopen,fputs,fwrite,matcvt,cvtmat.\n" }; static char *fputsHelp = { "fputs( fp, str )\n\n" "Write line to file fp. File pointer fp should have been obtained from a call\n" "to fopen or freopen or be the standard input (stdin).\n" "\n" "SEE ALSO: fopen,freopen,fwrite,matcvt,cvtmat.\n" }; static char *fopenHelp = { "fp = fopen( name, mode )\n\n" "Open file given name and access mode. The most usual modes are \"r\" for reading\n" "and \"w\" for writing. Return value fp is used in functions reading and writing\n" "the file.\n" "\n" "SEE ALSO: freopen.\n" }; static char *freopenHelp = { "fp = freopen( fp, name, mode )\n\n" "Reopen file given previous file pointer, name and access mode. The most usual modes\n" "are \"r\" for reading and \"w\" for writing. Return value fp is used in functions \n" "reading and writing the file.\n" "\n" "SEE ALSO: fopen.\n" }; static char *fcloseHelp = { "fclose( fp )\n\n" "Close file previously opened with fopen or freopen.\n" "\n" "SEE ALSO: fopen, freopen.\n" }; static char *saveHelp = { "save( name, matrix[, ascii_flag] )\n\n" "Save matrix in file with name given as first parameter. If ascii_flag is\n" "given and is not zero the file will be in ascii format, otherwise matrix\n" "is saved in double precsision binary format. In either case the first line\n" "of the file contains four digits (in ascii):\n\n" "ascii_flag 0 NROW(matrix) NCOL(matrix).\n" "\n" "SEE ALSO: load.\n" }; static char *loadHelp = { "matrix = load( name )\n\n" "Load matrix from a file given name and in format used by save-command.\n" "\n" "SEE ALSO: save.\n" }; com_init( "fread", FALSE, FALSE, fil_fread, 2, 2, freadHelp ); com_init( "fscanf", FALSE, FALSE, fil_fscanf, 2, 2, fscanfHelp ); com_init( "fgets", FALSE, FALSE, fil_fgets, 1, 1, fgetsHelp ); com_init( "fwrite", FALSE, FALSE, fil_fwrite, 2, 3, fwriteHelp ); com_init( "fprintf", FALSE, FALSE, fil_fprintf, 2, 3, fprintfHelp ); com_init( "fputs", FALSE, FALSE, fil_fputs, 2, 2, fputsHelp ); com_init( "fopen", FALSE, FALSE, fil_fopen, 2, 2, fopenHelp ); com_init( "freopen", FALSE, FALSE, fil_freopen, 3, 3, freopenHelp ); com_init( "fclose", FALSE, FALSE, fil_fclose, 1, 1, fcloseHelp ); com_init( "save", FALSE, FALSE, fil_save, 2, 3, saveHelp ); com_init( "load", FALSE, FALSE, fil_load, 1, 1, loadHelp ); fil_fps[0] = fil_fps_save[0] = stdin; fil_fps[1] = fil_fps_save[1] = stdout; fil_fps[2] = fil_fps_save[2] = stderr; }
convolution_3x3_pack8to1.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void conv3x3s1_pack8to1_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* bias = _bias; int remain_outch_start = 0; #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { Mat out0 = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out0.fill(bias0); const float* k0 = kernel.channel(p); for (int q = 0; q < inch; q++) { float* outptr0 = out0.row(0); const Mat img0 = bottom_blob.channel(q); __m256 _k00 = _mm256_loadu_ps(k0); __m256 _k01 = _mm256_loadu_ps(k0 + 8); __m256 _k02 = _mm256_loadu_ps(k0 + 16); __m256 _k10 = _mm256_loadu_ps(k0 + 24); __m256 _k11 = _mm256_loadu_ps(k0 + 32); __m256 _k12 = _mm256_loadu_ps(k0 + 40); __m256 _k20 = _mm256_loadu_ps(k0 + 48); __m256 _k21 = _mm256_loadu_ps(k0 + 56); __m256 _k22 = _mm256_loadu_ps(k0 + 64); int i = 0; for (; i < outh; i++) { const float* r0 = img0.row(i); const float* r1 = img0.row(i + 1); const float* r2 = img0.row(i + 2); int j = 0; for (; j < outw; j++) { __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _sum0 = _mm256_mul_ps(_k00, _r00); __m256 _sum1 = _mm256_mul_ps(_k01, _r01); __m256 _sum2 = _mm256_mul_ps(_k02, _r02); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); _sum0 = _mm256_comp_fmadd_ps(_k10, _r10, _sum0); _sum1 = _mm256_comp_fmadd_ps(_k11, _r11, _sum1); _sum2 = _mm256_comp_fmadd_ps(_k12, _r12, _sum2); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); _sum0 = _mm256_comp_fmadd_ps(_k20, _r20, _sum0); _sum1 = _mm256_comp_fmadd_ps(_k21, _r21, _sum1); _sum2 = _mm256_comp_fmadd_ps(_k22, _r22, _sum2); __m128 _sum = HorizontalSums(_sum0, _sum1, _sum2); *outptr0 += _mm_reduce_add_ps(_sum); // dot outptr0++; r0 += 8; r1 += 8; r2 += 8; } } k0 += 9 * 8; } } } static void conv3x3s1_winograd63_transform_kernel_pack8to1_avx(const Mat& kernel, Mat& kernel_tm_pack8, int inch, int outch, const Option& opt) { // winograd63 transform kernel Mat kernel_tm; kernel_tm.create(8 * 8, inch, outch); const float ktm[8][3] = { {1.0f, 0.0f, 0.0f}, {-2.0f / 9, -2.0f / 9, -2.0f / 9}, {-2.0f / 9, 2.0f / 9, -2.0f / 9}, {1.0f / 90, 1.0f / 45, 2.0f / 45}, {1.0f / 90, -1.0f / 45, 2.0f / 45}, {1.0f / 45, 1.0f / 90, 1.0f / 180}, {1.0f / 45, -1.0f / 90, 1.0f / 180}, {0.0f, 0.0f, 1.0f} }; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { for (int q = 0; q < inch; q++) { const float* kernel0 = (const float*)kernel + p * inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel, transposed const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[8][3]; for (int i = 0; i < 8; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // v for (int j = 0; j < 8; j++) { float* tmpp = &tmp[j][0]; for (int i = 0; i < 8; i++) { kernel_tm0[j * 8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } // interleave // src = 64-inch-outch // dst = 8a-inch/8a-64-outch; kernel_tm_pack8.create(8 * inch / 8, 64, outch / 8 + outch % 8, (size_t)4u * 8, 8); int p = 0; for (; p + 7 < outch; p += 8) { Mat g0 = kernel_tm_pack8.channel(p / 8); for (int k = 0; k < 64; k++) { float* g00 = g0.row(k); for (int q = 0; q + 7 < inch; q += 8) { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { const float* k00 = kernel_tm.channel(p + j).row(q + i); g00[0] = k00[k]; g00++; } } } } } for (; p < outch; p++) { const Mat k0 = kernel_tm.channel(p); Mat g0 = kernel_tm_pack8.channel(p / 8 + p % 8); for (int k = 0; k < 64; k++) { float* g00 = g0.row(k); for (int q = 0; q + 7 < inch; q += 8) { for (int i = 0; i < 8; i++) { const float* k00 = k0.row(q + i); g00[0] = k00[k]; g00++; } } } } } static void conv3x3s1_winograd63_pack8to1_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt); // BEGIN transform input Mat bottom_blob_tm; { int w_tiles = outw / 6; int h_tiles = outh / 6; const int tiles = w_tiles * h_tiles; bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator); conv3x3s1_winograd63_transform_input_pack8_avx(bottom_blob_bordered, bottom_blob_tm, opt); } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = h_tm / 8 * w_tm / 8; // permute // bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator); Mat bottom_blob_tm2; if (tiles >= 8) bottom_blob_tm2.create(8 * inch, tiles / 8 + tiles % 8, 64, elemsize, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 64, elemsize, elempack, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int r = 0; r < 64; r++) { Mat tm2 = bottom_blob_tm2.channel(r); // tile int i = 0; for (; i + 7 < tiles; i += 8) { float* tmpptr = tm2.row(i / 8); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 8; for (int q = 0; q < inch; q++) { // transpose 8x8 __m256 _r0 = _mm256_load_ps(r0); __m256 _r1 = _mm256_load_ps(r0 + 8); __m256 _r2 = _mm256_load_ps(r0 + 8 * 2); __m256 _r3 = _mm256_load_ps(r0 + 8 * 3); __m256 _r4 = _mm256_load_ps(r0 + 8 * 4); __m256 _r5 = _mm256_load_ps(r0 + 8 * 5); __m256 _r6 = _mm256_load_ps(r0 + 8 * 6); __m256 _r7 = _mm256_load_ps(r0 + 8 * 7); __m256 _tmp0 = _mm256_unpacklo_ps(_r0, _r1); __m256 _tmp1 = _mm256_unpackhi_ps(_r0, _r1); __m256 _tmp2 = _mm256_unpacklo_ps(_r2, _r3); __m256 _tmp3 = _mm256_unpackhi_ps(_r2, _r3); __m256 _tmp4 = _mm256_unpacklo_ps(_r4, _r5); __m256 _tmp5 = _mm256_unpackhi_ps(_r4, _r5); __m256 _tmp6 = _mm256_unpacklo_ps(_r6, _r7); __m256 _tmp7 = _mm256_unpackhi_ps(_r6, _r7); __m256 _tmp8 = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmp9 = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(3, 2, 3, 2)); __m256 _tmpa = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmpb = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(3, 2, 3, 2)); __m256 _tmpc = _mm256_shuffle_ps(_tmp4, _tmp6, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmpd = _mm256_shuffle_ps(_tmp4, _tmp6, _MM_SHUFFLE(3, 2, 3, 2)); __m256 _tmpe = _mm256_shuffle_ps(_tmp5, _tmp7, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmpf = _mm256_shuffle_ps(_tmp5, _tmp7, _MM_SHUFFLE(3, 2, 3, 2)); _r0 = _mm256_permute2f128_ps(_tmp8, _tmpc, _MM_SHUFFLE(0, 2, 0, 0)); _r1 = _mm256_permute2f128_ps(_tmp9, _tmpd, _MM_SHUFFLE(0, 2, 0, 0)); _r2 = _mm256_permute2f128_ps(_tmpa, _tmpe, _MM_SHUFFLE(0, 2, 0, 0)); _r3 = _mm256_permute2f128_ps(_tmpb, _tmpf, _MM_SHUFFLE(0, 2, 0, 0)); _r4 = _mm256_permute2f128_ps(_tmp8, _tmpc, _MM_SHUFFLE(0, 3, 0, 1)); _r5 = _mm256_permute2f128_ps(_tmp9, _tmpd, _MM_SHUFFLE(0, 3, 0, 1)); _r6 = _mm256_permute2f128_ps(_tmpa, _tmpe, _MM_SHUFFLE(0, 3, 0, 1)); _r7 = _mm256_permute2f128_ps(_tmpb, _tmpf, _MM_SHUFFLE(0, 3, 0, 1)); _mm256_store_ps(tmpptr, _r0); _mm256_store_ps(tmpptr + 8, _r1); _mm256_store_ps(tmpptr + 8 * 2, _r2); _mm256_store_ps(tmpptr + 8 * 3, _r3); _mm256_store_ps(tmpptr + 8 * 4, _r4); _mm256_store_ps(tmpptr + 8 * 5, _r5); _mm256_store_ps(tmpptr + 8 * 6, _r6); _mm256_store_ps(tmpptr + 8 * 7, _r7); tmpptr += 64; r0 += bottom_blob_tm.cstep * 8; } } for (; i < tiles; i++) { float* tmpptr = tm2.row(i / 8 + i % 8); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 8; for (int q = 0; q < inch; q++) { __m256 _val = _mm256_load_ps(r0); _mm256_store_ps(tmpptr, _val); tmpptr += 8; r0 += bottom_blob_tm.cstep * 8; } } } bottom_blob_tm = Mat(); // permute end top_blob_tm.create(tiles, 64, outch, 4u, 1, opt.workspace_allocator); int nn_outch = outch >> 3; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 8; float* outptr0_tm = top_blob_tm.channel(p); float* outptr1_tm = top_blob_tm.channel(p + 1); float* outptr2_tm = top_blob_tm.channel(p + 2); float* outptr3_tm = top_blob_tm.channel(p + 3); float* outptr4_tm = top_blob_tm.channel(p + 4); float* outptr5_tm = top_blob_tm.channel(p + 5); float* outptr6_tm = top_blob_tm.channel(p + 6); float* outptr7_tm = top_blob_tm.channel(p + 7); const Mat kernel01_tm = kernel_tm.channel(p / 8); for (int r = 0; r < 64; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + 7 < tiles; i += 8) { const float* r0 = bb2.row(i / 8); const float* kptr = kernel01_tm.row(r); int nn = inch * 8; // inch always > 0 __m256 _sum0 = _mm256_setzero_ps(); __m256 _sum1 = _mm256_setzero_ps(); __m256 _sum2 = _mm256_setzero_ps(); __m256 _sum3 = _mm256_setzero_ps(); __m256 _sum4 = _mm256_setzero_ps(); __m256 _sum5 = _mm256_setzero_ps(); __m256 _sum6 = _mm256_setzero_ps(); __m256 _sum7 = _mm256_setzero_ps(); for (int j = 0; j < nn; j++) { __m256 _val0 = _mm256_load_ps(r0); __m256 _w0 = _mm256_broadcast_ss(kptr); __m256 _w1 = _mm256_broadcast_ss(kptr + 1); _sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0); _sum1 = _mm256_comp_fmadd_ps(_val0, _w1, _sum1); __m256 _w2 = _mm256_broadcast_ss(kptr + 2); __m256 _w3 = _mm256_broadcast_ss(kptr + 3); _sum2 = _mm256_comp_fmadd_ps(_val0, _w2, _sum2); _sum3 = _mm256_comp_fmadd_ps(_val0, _w3, _sum3); __m256 _w4 = _mm256_broadcast_ss(kptr + 4); __m256 _w5 = _mm256_broadcast_ss(kptr + 5); _sum4 = _mm256_comp_fmadd_ps(_val0, _w4, _sum4); _sum5 = _mm256_comp_fmadd_ps(_val0, _w5, _sum5); __m256 _w6 = _mm256_broadcast_ss(kptr + 6); __m256 _w7 = _mm256_broadcast_ss(kptr + 7); _sum6 = _mm256_comp_fmadd_ps(_val0, _w6, _sum6); _sum7 = _mm256_comp_fmadd_ps(_val0, _w7, _sum7); r0 += 8; kptr += 8; } _mm256_storeu_ps(outptr0_tm, _sum0); _mm256_storeu_ps(outptr1_tm, _sum1); _mm256_storeu_ps(outptr2_tm, _sum2); _mm256_storeu_ps(outptr3_tm, _sum3); _mm256_storeu_ps(outptr4_tm, _sum4); _mm256_storeu_ps(outptr5_tm, _sum5); _mm256_storeu_ps(outptr6_tm, _sum6); _mm256_storeu_ps(outptr7_tm, _sum7); outptr0_tm += 8; outptr1_tm += 8; outptr2_tm += 8; outptr3_tm += 8; outptr4_tm += 8; outptr5_tm += 8; outptr6_tm += 8; outptr7_tm += 8; } for (; i < tiles; i++) { const float* r0 = bb2.row(i / 8 + i % 8); const float* kptr = kernel01_tm.row(r); int nn = inch * 8; // inch always > 0 __m256 _sum = _mm256_setzero_ps(); for (int j = 0; j < nn; j++) { __m256 _val0 = _mm256_broadcast_ss(r0); __m256 _w0 = _mm256_load_ps(kptr); _sum = _mm256_comp_fmadd_ps(_val0, _w0, _sum); r0 += 1; kptr += 8; } float sum[8]; _mm256_storeu_ps(sum, _sum); outptr0_tm[0] = sum[0]; outptr1_tm[0] = sum[1]; outptr2_tm[0] = sum[2]; outptr3_tm[0] = sum[3]; outptr4_tm[0] = sum[4]; outptr5_tm[0] = sum[5]; outptr6_tm[0] = sum[6]; outptr7_tm[0] = sum[7]; outptr0_tm += 1; outptr1_tm += 1; outptr2_tm += 1; outptr3_tm += 1; outptr4_tm += 1; outptr5_tm += 1; outptr6_tm += 1; outptr7_tm += 1; } } } int remain_outch_start = nn_outch << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { float* outptr0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p / 8 + p % 8); for (int r = 0; r < 64; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + 7 < tiles; i += 8) { const float* r0 = bb2.row(i / 8); const float* kptr = kernel0_tm.row(r); int nn = inch * 8; // inch always > 0 __m256 _sum0 = _mm256_setzero_ps(); for (int j = 0; j < nn; j++) { __m256 _val0 = _mm256_load_ps(r0); __m256 _w0 = _mm256_broadcast_ss(kptr); _sum0 = _mm256_comp_fmadd_ps(_w0, _val0, _sum0); r0 += 8; kptr += 1; } _mm256_storeu_ps(outptr0_tm, _sum0); outptr0_tm += 8; } for (; i < tiles; i++) { const float* r0 = bb2.row(i / 8 + i % 8); const float* kptr = kernel0_tm.row(r); __m256 _sum0 = _mm256_setzero_ps(); for (int q = 0; q < inch; q++) { __m256 _val0 = _mm256_load_ps(r0); __m256 _w0 = _mm256_load_ps(kptr); _sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0); r0 += 8; kptr += 8; } float sum0 = _mm256_reduce_add_ps(_sum0); outptr0_tm[0] = sum0; outptr0_tm++; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; if (outw == top_blob.w && outh == top_blob.h) { top_blob_bordered = top_blob; } else { top_blob_bordered.create(outw, outh, outch, 4u, 1, opt.workspace_allocator); } { conv3x3s1_winograd63_transform_output_sse(top_blob_tm, top_blob_bordered, bias, opt); } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt); }
fntext.c
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <math.h> #include <time.h> #include <string.h> #include <assert.h> #include <omp.h> #define EM_RANGE (0.01) typedef float floatx; struct model_t { floatx *em, *w, *b; int64_t em_dim, vocab_num, category_num; }; struct dataset_t { int64_t *text_indices, *text_lens, *text_categories; int64_t *start_pos; int64_t text_num; }; void init_model(struct model_t *model, int64_t em_dim, int64_t vocab_num, int64_t category_num, int64_t is_init) { model->em_dim = em_dim; model->vocab_num = vocab_num; model->category_num = category_num; model->em = (floatx *)malloc(em_dim * vocab_num * sizeof(floatx)); model->w = (floatx *)malloc(em_dim * category_num * sizeof(floatx)); model->b = (floatx *)malloc(category_num * sizeof(floatx)); floatx *em = model->em; floatx *w = model->w; floatx *b = model->b; int64_t i; if (is_init) { srand(time(NULL)); // [-EM_RANGE, EM_RANGE] for (i = 0; i < em_dim * vocab_num; i++) em[i] = ((floatx)rand() / RAND_MAX) * 2. * EM_RANGE - EM_RANGE; floatx stdv = 1. / (floatx)sqrt((double)em_dim); for (i = 0; i < em_dim * category_num; i++) w[i] = (floatx)rand() / RAND_MAX * 2. * stdv - stdv; for (i = 0; i < category_num; i++) b[i] = (floatx)rand() / RAND_MAX * 2. * stdv - stdv; } else { for (i = 0; i < em_dim * vocab_num; i++) em[i] = 0.; for (i = 0; i < em_dim * category_num; i++) w[i] = 0.; for (i = 0; i < category_num; i++) b[i] = 0.; } } void free_model(struct model_t *model) { free(model->em); free(model->w); free(model->b); } int preread(FILE *fp) { int ch = fgetc(fp); if (ch == EOF) return ch; else { fseek(fp, -1, SEEK_CUR); return ch; } } void load_data(struct dataset_t *data, const char *path, int64_t max_voc) { FILE *fp = NULL; fp = fopen(path, "r"); if (fp == NULL) { perror("error"); exit(EXIT_FAILURE); } int next_i, next_ch; int64_t text_num = 0, ch_num = 0, ignore_text_num = 0; int64_t text_len = 0; ; int64_t cat, text_i; enum state_t { READ_CAT, READ_INDEX } state = READ_CAT; while (1) { int is_break = 0; switch (state) { case READ_CAT: if (fscanf(fp, "%ld,", &cat) > 0) { if (preread(fp) == '\n') { ignore_text_num++; fgetc(fp); } else state = READ_INDEX; } else { assert(feof(fp)); is_break = 1; } break; case READ_INDEX: assert(fscanf(fp, "%ld", &text_i) > 0); if (text_i < max_voc) { ch_num++; text_len++; } next_ch = fgetc(fp); if (next_ch == '\n') { if (text_len == 0) { ignore_text_num++; } else { text_num++; text_len = 0; } state = READ_CAT; } } if (is_break) break; } printf("load data from %s\n", path); printf("#lines: %ld, #chs: %ld\n", text_num, ch_num); printf("#ignore lines: %ld\n", ignore_text_num); data->text_num = text_num; data->text_indices = (int64_t *)malloc(ch_num * sizeof(int64_t)); data->text_lens = (int64_t *)malloc(text_num * sizeof(int64_t)); data->text_categories = (int64_t *)malloc(text_num * sizeof(int64_t)); data->start_pos = (int64_t *)malloc(text_num * sizeof(int64_t)); text_len = 0; int64_t *text_indices = data->text_indices; int64_t *text_lens = data->text_lens; int64_t *text_categories = data->text_categories; int64_t *start_pos = data->start_pos; rewind(fp); while (1) { int is_break = 0; switch (state) { case READ_CAT: if (fscanf(fp, "%ld,", &cat) > 0) { if (preread(fp) == '\n') { fgetc(fp); } else state = READ_INDEX; } else { assert(feof(fp)); is_break = 1; } break; case READ_INDEX: assert(fscanf(fp, "%ld", &text_i) > 0); if (text_i < max_voc) { text_len++; *text_indices = text_i; text_indices++; } next_ch = fgetc(fp); if (next_ch == '\n') { state = READ_CAT; if (text_len > 0) { *text_lens = text_len; text_lens++; text_len = 0; *text_categories = cat; text_categories++; } } } if (is_break) break; } start_pos[0] = 0; for (int64_t i = 1; i < text_num; i++) start_pos[i] = start_pos[i - 1] + data->text_lens[i - 1]; fclose(fp); } void free_data(struct dataset_t *data) { free(data->text_indices); free(data->text_lens); free(data->text_categories); free(data->start_pos); } floatx forward(struct model_t *model, struct dataset_t *train_data, int64_t text_i, floatx *max_fea, int64_t *max_fea_index, floatx *softmax_fea) { int64_t *text_indices = &train_data->text_indices[train_data->start_pos[text_i]]; int64_t text_len = train_data->text_lens[text_i]; assert(text_len >= 1); int64_t text_category = train_data->text_categories[text_i]; int64_t i, j; int64_t em_pos; // max_pool // 先赋预值 em_pos = text_indices[0] * model->em_dim; for (i = 0; i < model->em_dim; i++) { max_fea[i] = model->em[em_pos + i]; max_fea_index[i] = em_pos + i; } floatx fea; int64_t fea_i; for (i = 1; i < text_len; i++) { em_pos = text_indices[i] * model->em_dim; for (j = 0; j < model->em_dim; j++) { max_fea[j] = max_fea[j] > (model->em[em_pos + j]) ? max_fea[j] : (model->em[em_pos + j]); max_fea_index[j] = max_fea[j] > (model->em[em_pos + j]) ? max_fea_index[j] : (em_pos + j); } } // mlp for (i = 0; i < model->category_num; i++) softmax_fea[i] = model->b[i]; for (i = 0; i < model->category_num; i++) for (j = 0; j < model->em_dim; j++) softmax_fea[i] += max_fea[j] * model->w[i * model->em_dim + j]; floatx loss = 0.; floatx tmp = 0.; loss -= softmax_fea[text_category]; for (i = 0; i < model->category_num; i++) { softmax_fea[i] = (floatx)exp((double)softmax_fea[i]); tmp += softmax_fea[i]; } loss += (floatx)log(tmp); return loss; } void backward(struct model_t *model, struct dataset_t *train_data, int64_t text_i, floatx *max_fea, floatx *softmax_fea, floatx *grad_em, floatx *grad_w, floatx *grad_b) { int64_t *text_indices = &(train_data->text_indices[train_data->start_pos[text_i]]); int64_t text_len = train_data->text_lens[text_i]; int64_t text_category = train_data->text_categories[text_i]; floatx tmp_sum = 0.; int64_t i, j; for (i = 0; i < model->category_num; i++) tmp_sum += softmax_fea[i]; for (i = 0; i < model->category_num; i++) grad_b[i] = softmax_fea[i] / tmp_sum; grad_b[text_category] -= 1.; for (i = 0; i < model->category_num; i++) for (j = 0; j < model->em_dim; j++) grad_w[i * model->em_dim + j] = max_fea[j] * grad_b[i]; for (j = 0; j < model->em_dim; j++) grad_em[j] = 0.; for (i = 0; i < model->category_num; i++) for (j = 0; j < model->em_dim; j++) grad_em[j] += (model->w[i * model->em_dim + j]) * grad_b[i]; } void evaluate(struct model_t *model, struct dataset_t *vali_data, int64_t batch_size, int64_t threads_n) { printf("evaluating...\n"); time_t eva_start, eva_end; eva_start = time(NULL); floatx *max_feas = (floatx *)malloc(model->em_dim * batch_size * sizeof(floatx)); int64_t *max_fea_indexs = (int64_t *)malloc(model->em_dim * batch_size * sizeof(int64_t)); floatx *softmax_feas = (floatx *)malloc(model->category_num * batch_size * sizeof(floatx)); int64_t *pre_labels = (int64_t *)malloc(batch_size * sizeof(int64_t)); int64_t *real_labels = (int64_t *)malloc(batch_size * sizeof(int64_t)); // 临界资源 floatx *cat_all = (floatx *)malloc(model->category_num * sizeof(floatx)); floatx *cat_true = (floatx *)malloc(model->category_num * sizeof(floatx)); for (int64_t i = 0; i < model->category_num; i++) { cat_all[i] = 0.; cat_true[i] = 0.; } for (int64_t batch_i = 0; batch_i < (vali_data->text_num + batch_size - 1) / batch_size; batch_i++) { int64_t real_batch_size = (vali_data->text_num - batch_i * batch_size) > batch_size ? batch_size : (vali_data->text_num - batch_i * batch_size); #pragma omp parallel for schedule(dynamic) num_threads(threads_n) for (int64_t batch_j = 0; batch_j < real_batch_size; batch_j++) { int64_t text_i = (batch_i)*batch_size + batch_j; assert(text_i < vali_data->text_num); int64_t text_category = vali_data->text_categories[text_i]; // 长度为0的text,不计算梯度 // 会导致问题,比如梯度没有更新 // 应该在生成数据时避免 if (vali_data->text_lens[text_i] == 0) { printf("error: vali text length can not be zero.[text id: %ld]", text_i); exit(-1); } floatx *max_fea = &max_feas[batch_j * model->em_dim]; int64_t *max_fea_index = &max_fea_indexs[batch_j * model->em_dim]; floatx *softmax_fea = &softmax_feas[batch_j * model->category_num]; int64_t *pre_label = &pre_labels[batch_j]; int64_t *real_label = &real_labels[batch_j]; *real_label = text_category; forward(model, vali_data, text_i, max_fea, max_fea_index, softmax_fea); *pre_label = 0; floatx fea = softmax_fea[0]; for (int64_t c = 1; c < model->category_num; c++) { if (softmax_fea[c] > fea) { *pre_label = c; fea = softmax_fea[c]; } } } // 访问临界资源 for (int64_t batch_j = 0; batch_j < real_batch_size; batch_j++) { cat_all[real_labels[batch_j]] += 1; if (real_labels[batch_j] == pre_labels[batch_j]) cat_true[real_labels[batch_j]] += 1; } } floatx cat_all_sum = 0.; floatx cat_true_sum = 0.; for (int64_t k = 0; k < model->category_num; k++) { cat_all_sum += cat_all[k]; cat_true_sum += cat_true[k]; } printf("#samples: %.0f\n", cat_all_sum); printf("macro precision: %.5f\n", cat_true_sum / cat_all_sum); for (int64_t k = 0; k < model->category_num; k++) printf(" category #%ld precision: %.5f\n", k, cat_true[k] / cat_all[k]); free(max_feas); free(max_fea_indexs); free(softmax_feas); free(pre_labels); free(real_labels); free(cat_all); free(cat_true); eva_end = time(NULL); printf(" evaluating time: %lds\n", eva_end-eva_start); } void train_sgd(struct model_t *model, struct dataset_t *train_data, struct dataset_t *vali_data, int64_t epochs, int64_t batch_size, floatx lr, int64_t threads_n) { int64_t *shuffle_index = (int64_t *)malloc(train_data->text_num * sizeof(int64_t)); int64_t tmp, i, sel; floatx *grads_em = (floatx *)malloc(model->em_dim * batch_size * sizeof(floatx)); floatx *grads_w = (floatx *)malloc(model->em_dim * model->category_num * batch_size * sizeof(floatx)); floatx *grads_b = (floatx *)malloc(model->category_num * batch_size * sizeof(floatx)); floatx *max_feas = (floatx *)malloc(model->em_dim * batch_size * sizeof(floatx)); int64_t *max_fea_indexs = (int64_t *)malloc(model->em_dim * batch_size * sizeof(int64_t)); floatx *softmax_feas = (floatx *)malloc(model->category_num * batch_size * sizeof(floatx)); floatx *losses = (floatx *)malloc(batch_size * sizeof(floatx)); for (i = 0; i < train_data->text_num; i++) shuffle_index[i] = i; for (int64_t epoch = 0; epoch < epochs; epoch++) { printf("#epoch: %ld\n", epoch); floatx s_loss = 0.; time_t epoch_start, epoch_end; // shuffle for (i = 0; i < train_data->text_num; i++) { sel = rand() % (train_data->text_num - i) + i; tmp = shuffle_index[i]; shuffle_index[i] = shuffle_index[sel]; shuffle_index[sel] = tmp; } /* for (i=0; i<model->em_dim*batch_size; i++) grads_em[i] = 0.; */ /* for (i=0; i<model->em_dim*model->category_num*batch_size; i++) grads_w[i] = 0.; */ /* for (i=0; i<model->category_num->batch_size; i++) grads_b = 0.; */ epoch_start = time(NULL); for (int64_t batch_i = 0; batch_i < (train_data->text_num + batch_size - 1) / batch_size; batch_i++) { int64_t real_batch_size = (train_data->text_num - batch_i * batch_size) > batch_size ? batch_size : (train_data->text_num - batch_i * batch_size); // 可以加速 #pragma omp parallel for schedule(dynamic) num_threads(threads_n) for (int64_t batch_j = 0; batch_j < real_batch_size; batch_j++) { int64_t text_i = (batch_i)*batch_size + batch_j; assert(text_i < train_data->text_num); text_i = shuffle_index[text_i]; // 长度为0的text,不计算梯度 // 会导致问题,比如梯度没有更新 // 应该在生成数据时避免 if (train_data->text_lens[text_i] == 0) { printf("error: training text length can not be zero.[text id: %ld]", text_i); exit(-1); } floatx *grad_em = &grads_em[batch_j * model->em_dim]; floatx *grad_w = &grads_w[batch_j * model->em_dim * model->category_num]; floatx *grad_b = &grads_b[batch_j * model->category_num]; floatx *max_fea = &max_feas[batch_j * model->em_dim]; int64_t *max_fea_index = &max_fea_indexs[batch_j * model->em_dim]; floatx *softmax_fea = &softmax_feas[batch_j * model->category_num]; losses[batch_j] = forward(model, train_data, text_i, max_fea, max_fea_index, softmax_fea); backward(model, train_data, text_i, max_fea, softmax_fea, grad_em, grad_w, grad_b); } for (int64_t batch_j = 0; batch_j < real_batch_size; batch_j++) s_loss += losses[batch_j]; // update param for (int64_t batch_j = 0; batch_j < real_batch_size; batch_j++) { floatx *grad_em = &grads_em[batch_j * model->em_dim]; floatx *grad_w = &grads_w[batch_j * model->em_dim * model->category_num]; floatx *grad_b = &grads_b[batch_j * model->category_num]; int64_t *max_fea_index = &max_fea_indexs[batch_j * model->em_dim]; for (int64_t w_j = 0; w_j < model->em_dim * model->category_num; w_j++) model->w[w_j] -= (lr * (1. / real_batch_size) * grad_w[w_j]); for (int64_t b_j = 0; b_j < model->category_num; b_j++) model->b[b_j] -= (lr * (1. / real_batch_size) * grad_b[b_j]); for (int64_t em_j = 0; em_j < model->em_dim; em_j++) model->em[max_fea_index[em_j]] -= (lr * (1. / real_batch_size) * grad_em[em_j]); /* model->em[max_fea_index[em_j]] -= (lr*grad_em[em_j]); */ } } // end_batch epoch_end = time(NULL); s_loss /= train_data->text_num; printf(" loss: %.4f\n", s_loss); printf(" time: %lds\n", epoch_end - epoch_start); if (vali_data != NULL) { printf("evaluate vali data...\n"); evaluate(model, vali_data, batch_size, threads_n); } printf("\n"); } //end_epoch free(shuffle_index); free(grads_em); free(grads_w); free(grads_b); free(max_feas); free(max_fea_indexs); free(softmax_feas); free(losses); } void train_adam(struct model_t *model, struct dataset_t *train_data, struct dataset_t *vali_data, int64_t epochs, int64_t batch_size, int64_t threads_n) { printf("start training(Adam)...\n"); // omp_lock_t omplock; // omp_init_lock(&omplock); int64_t tmp, i, sel; floatx alpha = 0.001, beta1 = 0.9, beta2 = 0.999, epsilon = 1e-8; floatx beta1t = beta1; floatx beta2t = beta2; int64_t *shuffle_index = (int64_t *)malloc(train_data->text_num * sizeof(int64_t)); struct model_t adam_m, adam_v, gt; init_model(&adam_m, model->em_dim, model->vocab_num, model->category_num, 0); init_model(&adam_v, model->em_dim, model->vocab_num, model->category_num, 0); init_model(&gt, model->em_dim, model->vocab_num, model->category_num, 0); floatx *grads_em = (floatx *)malloc(model->em_dim * batch_size * sizeof(floatx)); floatx *grads_w = (floatx *)malloc(model->em_dim * model->category_num * batch_size * sizeof(floatx)); floatx *grads_b = (floatx *)malloc(model->category_num * batch_size * sizeof(floatx)); floatx *max_feas = (floatx *)malloc(model->em_dim * batch_size * sizeof(floatx)); int64_t *max_fea_indexs = (int64_t *)malloc(model->em_dim * batch_size * sizeof(int64_t)); floatx *softmax_feas = (floatx *)malloc(model->category_num * batch_size * sizeof(floatx)); floatx *losses = (floatx *)malloc(batch_size * sizeof(floatx)); printf("init grad end...\n"); for (i = 0; i < train_data->text_num; i++) shuffle_index[i] = i; for (int64_t epoch = 0; epoch < epochs; epoch++) { printf("#epoch: %ld\n", epoch); floatx s_loss = 0.; time_t epoch_start, epoch_end; // shuffle for (i = 0; i < train_data->text_num; i++) { sel = rand() % (train_data->text_num - i) + i; tmp = shuffle_index[i]; shuffle_index[i] = shuffle_index[sel]; shuffle_index[sel] = tmp; } epoch_start = time(NULL); for (int64_t batch_i = 0; batch_i < (train_data->text_num + batch_size - 1) / batch_size; batch_i++) { int64_t real_batch_size = (train_data->text_num - batch_i * batch_size) > batch_size ? batch_size : (train_data->text_num - batch_i * batch_size); // 可以加速 #pragma omp parallel for schedule(dynamic) num_threads(threads_n) for (int64_t batch_j = 0; batch_j < real_batch_size; batch_j++) { int64_t text_i = (batch_i)*batch_size + batch_j; assert(text_i < train_data->text_num); text_i = shuffle_index[text_i]; // 长度为0的text,不计算梯度 // 会导致问题,比如梯度没有更新 // 应该在生成数据时避免 if (train_data->text_lens[text_i] == 0) { printf("error: training text length can not be zero.[text id: %ld]", text_i); exit(-1); } floatx *grad_em = &grads_em[batch_j * model->em_dim]; floatx *grad_w = &grads_w[batch_j * model->em_dim * model->category_num]; floatx *grad_b = &grads_b[batch_j * model->category_num]; floatx *max_fea = &max_feas[batch_j * model->em_dim]; int64_t *max_fea_index = &max_fea_indexs[batch_j * model->em_dim]; floatx *softmax_fea = &softmax_feas[batch_j * model->category_num]; losses[batch_j] = forward(model, train_data, text_i, max_fea, max_fea_index, softmax_fea); backward(model, train_data, text_i, max_fea, softmax_fea, grad_em, grad_w, grad_b); } for (int64_t batch_j = 0; batch_j < real_batch_size; batch_j++) s_loss += losses[batch_j]; // 把多个batch的梯度累加起来 不可以加速,因为gt.em是临界资源 for (int64_t batch_j = 0; batch_j < real_batch_size; batch_j++) { for (int64_t batch_k = 0; batch_k < model->em_dim * model->category_num; batch_k++) gt.w[batch_k] += grads_w[batch_j * model->em_dim * model->category_num + batch_k] / (floatx)batch_size; for (int64_t batch_k = 0; batch_k < model->category_num; batch_k++) gt.b[batch_k] += grads_b[batch_j * model->category_num + batch_k] / (floatx)batch_size; // em的grad 特殊对待 for (int64_t batch_k = 0; batch_k < model->em_dim; batch_k++) { int64_t em_index = max_fea_indexs[batch_j * model->em_dim + batch_k]; gt.em[em_index] += grads_em[batch_j * model->em_dim + batch_k] / (floatx)batch_size; } } // 计算m,v update param 可以加速 #pragma omp parallel for schedule(static) num_threads(threads_n) for (int64_t batch_k = 0; batch_k < model->em_dim * model->category_num; batch_k++) { adam_m.w[batch_k] = beta1 * adam_m.w[batch_k] + (1 - beta1) * gt.w[batch_k]; adam_v.w[batch_k] = beta2 * adam_v.w[batch_k] + (1 - beta2) * gt.w[batch_k] * gt.w[batch_k]; gt.w[batch_k] = 0.; floatx m_hat = adam_m.w[batch_k] / (1 - beta1t); floatx v_hat = adam_v.w[batch_k] / (1 - beta2t); model->w[batch_k] -= alpha * m_hat / ((floatx)sqrt((floatx)v_hat) + epsilon); } // 循环数量少,不用加速 for (int64_t batch_k = 0; batch_k < model->category_num; batch_k++) { adam_m.b[batch_k] = beta1 * adam_m.b[batch_k] + (1 - beta1) * gt.b[batch_k]; adam_v.b[batch_k] = beta2 * adam_v.b[batch_k] + (1 - beta2) * gt.b[batch_k] * gt.b[batch_k]; gt.b[batch_k] = 0.; floatx m_hat = adam_m.b[batch_k] / (1 - beta1t); floatx v_hat = adam_v.b[batch_k] / (1 - beta2t); model->b[batch_k] -= alpha * m_hat / ((floatx)sqrt((floatx)v_hat) + epsilon); } // model->em是临界资源加锁 for (int64_t batch_j = 0; batch_j < real_batch_size; batch_j++) { // em的grad 特殊对待 for (int64_t batch_k = 0; batch_k < model->em_dim; batch_k++) { int64_t em_index = max_fea_indexs[batch_j * model->em_dim + batch_k]; if (gt.em[em_index] != 0.) { adam_m.em[em_index] = beta1 * adam_m.em[em_index] + (1 - beta1) * gt.em[em_index]; adam_v.em[em_index] = beta2 * adam_v.em[em_index] + (1 - beta2) * gt.em[em_index] * gt.em[em_index]; gt.em[em_index] = 0.; floatx m_hat = adam_m.em[em_index] / (1 - beta1t); floatx v_hat = adam_v.em[em_index] / (1 - beta2t); model->em[em_index] -= alpha * m_hat / ((floatx)sqrt((floatx)v_hat) + epsilon); } } } beta1t *= beta1t; beta2t *= beta2t; } // end_batch epoch_end = time(NULL); s_loss /= train_data->text_num; printf(" loss: %.4f\n", s_loss); printf(" time: %lds\n", epoch_end - epoch_start); if (vali_data != NULL) { printf("evaluate vali data...\n"); evaluate(model, vali_data, batch_size, threads_n); } printf("\n"); } //end_epoch free(shuffle_index); free_model(&adam_m); free_model(&adam_v); free_model(&gt); free(grads_em); free(grads_w); free(grads_b); free(max_feas); free(max_fea_indexs); free(softmax_feas); free(losses); } void show(int64_t *a, int64_t n) { for (int64_t i = 0; i < n; i++) printf("%ld ", a[i]); printf("\n"); } int arg_helper(char *str, int argc, char **argv) { int pos; for (pos = 1; pos < argc; pos++) if (strcmp(str, argv[pos]) == 0) return pos; return -1; } int main(int argc, char **argv) { struct model_t model; struct dataset_t train_data, vali_data, test_data; int64_t em_dim = 200, vocab_num = 0, category_num = 0; int64_t epochs = 10, batch_size = 2000, threads_n = 20; floatx lr = 0.5, limit_vocab=1.; char *train_data_path = NULL, *vali_data_path = NULL, *test_data_path = NULL; int i; if ((i = arg_helper("-dim", argc, argv)) > 0) em_dim = (int64_t)atoi(argv[i + 1]); if ((i = arg_helper("-vocab", argc, argv)) > 0) vocab_num = (int64_t)atoi(argv[i + 1]); if ((i = arg_helper("-category", argc, argv)) > 0) category_num = (int64_t)atoi(argv[i + 1]); if ((i = arg_helper("-epoch", argc, argv)) > 0) epochs = (int64_t)atoi(argv[i + 1]); if ((i = arg_helper("-batch-size", argc, argv)) > 0) batch_size = (int64_t)atoi(argv[i + 1]); if ((i = arg_helper("-thread", argc, argv)) > 0) threads_n = (int64_t)atoi(argv[i + 1]); if ((i = arg_helper("-lr", argc, argv)) > 0) lr = (floatx)atof(argv[i + 1]); if ((i = arg_helper("-train", argc, argv)) > 0) train_data_path = argv[i + 1]; if ((i = arg_helper("-vali", argc, argv)) > 0) vali_data_path = argv[i + 1]; if ((i = arg_helper("-test", argc, argv)) > 0) test_data_path = argv[i + 1]; if ((i = arg_helper("-limit-vocab", argc, argv)) > 0) limit_vocab = (floatx)atof(argv[i + 1]); if (vocab_num == 0) { printf("error: miss -vocab"); exit(-1); } if (category_num == 0) { printf("error: miss -category"); exit(-1); } if (train_data_path == NULL) { printf("error: need train data!"); exit(-1); } init_model(&model, em_dim, vocab_num, category_num, 1); if (train_data_path != NULL) load_data(&train_data, train_data_path,(int64_t)(limit_vocab*vocab_num)); if (test_data_path != NULL) load_data(&test_data, test_data_path,(int64_t)(limit_vocab*vocab_num)); if (vali_data_path != NULL) load_data(&vali_data, vali_data_path,(int64_t)(limit_vocab*vocab_num)); if (vali_data_path != NULL) train_adam(&model, &train_data, &vali_data, epochs, batch_size, threads_n); else train_adam(&model, &train_data, NULL, epochs, batch_size, threads_n); if (test_data_path != NULL) { printf("evaluate test data...\n"); evaluate(&model, &test_data, batch_size, threads_n); } free_model(&model); if (train_data_path != NULL) free_data(&train_data); if (test_data_path != NULL) free_data(&test_data); if (vali_data_path != NULL) free_data(&vali_data); return 0; }
multiply.h
#pragma once #include "intgemm/intgemm_config.h" #include "interleave.h" #include "intrinsics.h" #include "vec_traits.h" #include "callbacks.h" namespace intgemm { INTGEMM_SSE2 static inline dvector_t<CPUType::SSE2, int> PermuteSummer(__m128i pack0123, __m128i pack4567) { // No op for 128 bits: already reduced fully. return { pack0123, pack4567 }; } INTGEMM_AVX2 static inline __m256i PermuteSummer(__m256i pack0123, __m256i pack4567) { // This instruction generates 1s 2s 3s 4s 5f 6f 7f 8f __m256i rev = _mm256_permute2f128_si256(pack0123, pack4567, 0x21); // This instruction generates 1f 2f 3f 4f 5s 6s 7s 8s __m256i blended = _mm256_blend_epi32(pack0123, pack4567, 0xf0); return _mm256_add_epi32(rev, blended); } #ifdef INTGEMM_COMPILER_SUPPORTS_AVX512BW /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_AVX512BW static inline __m256i PermuteSummer(__m512i pack0123, __m512i pack4567) { // Form [0th 128-bit register of pack0123, 0st 128-bit register of pack4567, 2nd 128-bit register of pack0123, 2nd 128-bit register of pack4567] __m512i mix0 = _mm512_mask_permutex_epi64(pack0123, 0xcc, pack4567, (0 << 4) | (1 << 6)); // Form [1st 128-bit register of pack0123, 1st 128-bit register of pack4567, 3rd 128-bit register of pack0123, 3rd 128-bit register of pack4567] __m512i mix1 = _mm512_mask_permutex_epi64(pack4567, 0x33, pack0123, 2 | (3 << 2)); __m512i added = _mm512_add_epi32(mix0, mix1); // Now we have 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7. // Fold register over itself. return _mm256_add_epi32(_mm512_castsi512_si256(added), _mm512_extracti64x4_epi64(added, 1)); } #endif #ifdef _MSC_VER #define INTGEMM_OMP_FOR __pragma(omp for) #define INTGEMM_OMP_PARALLEL __pragma(omp parallel) #else #define INTGEMM_OMP_FOR _Pragma("omp for") #define INTGEMM_OMP_PARALLEL _Pragma("omp parallel") #endif // Quantize function used for SSSE3 and AVX2. // Separate function for thread to work around gcc 7 bug that doesn't imbue // target attributes across #pragma omp parallel. #define INTGEMM_QUANTIZE_THREAD(target) \ target static void QuantizeThread(const float *input, int8_t *output, float quant_mult, std::size_t count) { \ FRegister q = set1_ps<FRegister>(quant_mult); \ INTGEMM_OMP_FOR \ for (std::size_t i = 0; i < count; i += sizeof(Register)) { \ *reinterpret_cast<Register*>(output + i) = QuantizeTile8::Consecutive(q, input + i); \ } \ } #define INTGEMM_QUANTIZE(target) \ target static void Quantize(const float *const input, int8_t *const output, float quant_mult, Index size) { \ assert(reinterpret_cast<uintptr_t>(input) % sizeof(Register) == 0); \ assert(reinterpret_cast<uintptr_t>(output) % sizeof(Register) == 0); \ const std::size_t kBatch = sizeof(Register); \ const std::size_t fast_end = size & ~(kBatch - 1); \ INTGEMM_OMP_PARALLEL \ { \ QuantizeThread(input, output, quant_mult, fast_end); \ } \ std::size_t overhang = size & (kBatch - 1); \ if (!overhang) return; \ FRegister q = set1_ps<FRegister>(quant_mult); \ /* Each does size(Register) / 32 == kBatch / 4 floats at a time. * If we're allowed to read one of them, then we can read the whole register. */ \ const float *inputs[4]; \ std::size_t i; \ for (i = 0; i < (overhang + (kBatch / 4) - 1) / (kBatch / 4); ++i) { \ inputs[i] = &input[fast_end + i * (kBatch / 4)]; \ } \ /* These will be clipped off. */ \ for (; i < 4; ++i) { \ inputs[i] = &input[fast_end]; \ } \ Register result = QuantizeTile8::Tile(q, inputs[0], inputs[1], inputs[2], inputs[3]); \ std::memcpy(output + (size & ~(kBatch - 1)), &result, overhang); \ } /* Take 4 registers with 32-bit values to be horizontally added. Reduce them * to one register with 32-bit values in the pattern 1 2 3 4 1 2 3 4, leaving * the final addition (which crosses 128-bit lanes) to the caller. */ #define INTGEMM_PACK0123(target, Register) \ target inline Register Pack0123(Register sum0, Register sum1, Register sum2, Register sum3) { \ Interleave32(sum0, sum1); \ Register pack01 = add_epi32(sum0, sum1); \ Interleave32(sum2, sum3); \ Register pack23 = add_epi32(sum2, sum3); \ Interleave64(pack01, pack23); \ return add_epi32(pack01, pack23); \ } \ INTGEMM_PACK0123(INTGEMM_SSE2, __m128i) INTGEMM_PACK0123(INTGEMM_AVX2, __m256i) #ifdef INTGEMM_COMPILER_SUPPORTS_AVX512BW /* Only INTGEMM_AVX512F is necessary but due to GCC 5.4 bug we have to set INTGEMM_AVX512BW */ INTGEMM_PACK0123(INTGEMM_AVX512BW, __m512i) #endif template <typename Callback> INTGEMM_SSE2 static inline void RunCallback(Callback& callback_impl, dvector_t<CPUType::SSE2, int> total, Index row_idx, Index col_idx, Index rows, Index cols) { callback_impl(total.first, callbacks::OutputBufferInfo(row_idx, col_idx, rows, cols)); callback_impl(total.second, callbacks::OutputBufferInfo(row_idx, col_idx + 4, rows, cols)); } template <typename Callback> INTGEMM_AVX2 static inline void RunCallback(Callback& callback_impl, vector_t<CPUType::AVX2, int> total, Index row_idx, Index col_idx, Index rows, Index cols) { callback_impl(total, callbacks::OutputBufferInfo(row_idx, col_idx, rows, cols)); } // 16-bit multiplier for INTGEMM_SSE2, INTGEMM_AVX2, and AVX512. // C = A * B * unquant_mult // // This has been substantially revised from Jacob Devlin's SSE code which is: // Copyright (c) 2017 Microsoft Corporation // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // A is a row-major quantized matrix (from PrepareA) // B is a rearranged quantized matrix (from PrepareB) // C is output in row-major form. // // All of A, B, and C must be in aligned to a multiple of the register size: // INTGEMM_SSE2: 16 bytes // INTGEMM_AVX2: 32 bytes // AVX512: 64 bytes. // // A_rows can be anything non-negative. // width must be a multiple of the register size. // B_cols must be a multiple of 8. // Multiply16 #define INTGEMM_MULTIPLY16(Register, target, cpu_type) \ template <typename Callback> target static void Multiply(const int16_t *A, const int16_t *B, Index A_rows, Index width, Index B_cols, Callback callback) { \ assert(width % (sizeof(Register) / sizeof(int16_t)) == 0); \ assert(B_cols % 8 == 0); \ assert(reinterpret_cast<uintptr_t>(A) % sizeof(Register) == 0); \ assert(reinterpret_cast<uintptr_t>(B) % sizeof(Register) == 0); \ const Index simd_width = width / (sizeof(Register) / sizeof(int16_t)); \ auto callback_impl = callbacks::CallbackImpl<cpu_type, Callback>(callback); \ INTGEMM_OMP_FOR \ for (Index B0_colidx = 0; B0_colidx < B_cols; B0_colidx += 8) { \ const Register *B0_col = reinterpret_cast<const Register *>(B) + simd_width * B0_colidx; \ /* Process one row of A at a time. Doesn't seem to be faster to do multiple rows of A at once.*/ \ for (Index A_rowidx = 0; A_rowidx < A_rows; ++A_rowidx) { \ const Register *A_row = reinterpret_cast<const Register*>(A + A_rowidx * width); \ /* These will be packed 32-bit integers containing sums for each row of B multiplied by the row of A. \ Iterate over shared (inner) dimension.*/ \ Index k = 0; \ Register a = *(A_row + k); \ Register sum0 = madd_epi16(a, *(B0_col + k * 8)); \ Register sum1 = madd_epi16(a, *(B0_col + k * 8 + 1)); \ Register sum2 = madd_epi16(a, *(B0_col + k * 8 + 2)); \ Register sum3 = madd_epi16(a, *(B0_col + k * 8 + 3)); \ Register sum4 = madd_epi16(a, *(B0_col + k * 8 + 4)); \ Register sum5 = madd_epi16(a, *(B0_col + k * 8 + 5)); \ Register sum6 = madd_epi16(a, *(B0_col + k * 8 + 6)); \ Register sum7 = madd_epi16(a, *(B0_col + k * 8 + 7)); \ for (k = 1; k < simd_width; ++k) { \ a = *(A_row + k); \ /* Multiply 16-bit, horizontally add to packed 32-bit integers.*/ \ Register mult0 = madd_epi16(a, *(B0_col + k * 8)); \ Register mult1 = madd_epi16(a, *(B0_col + k * 8 + 1)); \ Register mult2 = madd_epi16(a, *(B0_col + k * 8 + 2)); \ Register mult3 = madd_epi16(a, *(B0_col + k * 8 + 3)); \ Register mult4 = madd_epi16(a, *(B0_col + k * 8 + 4)); \ Register mult5 = madd_epi16(a, *(B0_col + k * 8 + 5)); \ Register mult6 = madd_epi16(a, *(B0_col + k * 8 + 6)); \ Register mult7 = madd_epi16(a, *(B0_col + k * 8 + 7)); \ /* Sum packed 32-bit integers with danger of overflow. TODO: accumulate in 64-bit every so often.*/ \ sum0 = add_epi32(sum0, mult0); \ sum1 = add_epi32(sum1, mult1); \ sum2 = add_epi32(sum2, mult2); \ sum3 = add_epi32(sum3, mult3); \ sum4 = add_epi32(sum4, mult4); \ sum5 = add_epi32(sum5, mult5); \ sum6 = add_epi32(sum6, mult6); \ sum7 = add_epi32(sum7, mult7); \ } \ /* Reduce sums within 128-bit lanes.*/ \ Register pack0123 = Pack0123(sum0, sum1, sum2, sum3); \ Register pack4567 = Pack0123(sum4, sum5, sum6, sum7); \ /*The specific implementation may need to reduce further.*/ \ auto total = PermuteSummer(pack0123, pack4567); \ RunCallback(callback_impl, total, A_rowidx, B0_colidx, A_rows, B_cols); \ } \ } \ } \ //An int8_prepbias version of the above code, using the add 127 technique #define INTGEMM_PREPAREBIASFOR8(Register, target, cpu_type) \ template <class Callback> target static void PrepareBias(const int8_t *B, Index width, Index B_cols, Callback callback) { \ assert(width % (sizeof(Register) / sizeof(int8_t)) == 0); \ assert(B_cols % 8 == 0); \ assert(reinterpret_cast<uintptr_t>(B) % sizeof(Register) == 0); \ const Index simd_width = width / (sizeof(Register) / sizeof(int8_t)); \ auto callback_impl = callbacks::CallbackImpl<cpu_type, Callback>(callback); \ const Register a = set1_epi8<Register>(1); \ INTGEMM_OMP_FOR \ for (Index B0_colidx = 0; B0_colidx < B_cols; B0_colidx += 8) { \ const Register *B0_col = reinterpret_cast<const Register *>(B) + simd_width * B0_colidx; \ /*const Register *A_row = reinterpret_cast<const Register*>(A + A_rowidx * width);*/ \ /* These will be packed 16-bit integers containing sums for each row of B multiplied by the row of A. \ Iterate over shared (inner) dimension.*/ \ Index k = 0; \ Register sum0 = maddubs_epi16(a, *(B0_col + k * 8)); \ Register sum1 = maddubs_epi16(a, *(B0_col + k * 8 + 1)); \ Register sum2 = maddubs_epi16(a, *(B0_col + k * 8 + 2)); \ Register sum3 = maddubs_epi16(a, *(B0_col + k * 8 + 3)); \ Register sum4 = maddubs_epi16(a, *(B0_col + k * 8 + 4)); \ Register sum5 = maddubs_epi16(a, *(B0_col + k * 8 + 5)); \ Register sum6 = maddubs_epi16(a, *(B0_col + k * 8 + 6)); \ Register sum7 = maddubs_epi16(a, *(B0_col + k * 8 + 7)); \ /* Upcast to 32-bit and horizontally add. Seems a bit faster if this is declared here.*/ \ Register ones = set1_epi16<Register>(1); \ sum0 = madd_epi16(sum0, ones); \ sum1 = madd_epi16(sum1, ones); \ sum2 = madd_epi16(sum2, ones); \ sum3 = madd_epi16(sum3, ones); \ sum4 = madd_epi16(sum4, ones); \ sum5 = madd_epi16(sum5, ones); \ sum6 = madd_epi16(sum6, ones); \ sum7 = madd_epi16(sum7, ones); \ for (k = 1; k < simd_width; ++k) { \ /*Register a = *(A_row + k);*/ \ /* Multiply 8-bit, horizontally add to packed 16-bit integers.*/ \ Register mult0 = maddubs_epi16(a, *(B0_col + k * 8)); \ Register mult1 = maddubs_epi16(a, *(B0_col + k * 8 + 1)); \ Register mult2 = maddubs_epi16(a, *(B0_col + k * 8 + 2)); \ Register mult3 = maddubs_epi16(a, *(B0_col + k * 8 + 3)); \ Register mult4 = maddubs_epi16(a, *(B0_col + k * 8 + 4)); \ Register mult5 = maddubs_epi16(a, *(B0_col + k * 8 + 5)); \ Register mult6 = maddubs_epi16(a, *(B0_col + k * 8 + 6)); \ Register mult7 = maddubs_epi16(a, *(B0_col + k * 8 + 7)); \ /* Upcast to 32-bit and horizontally add.*/ \ mult0 = madd_epi16(mult0, ones); \ mult1 = madd_epi16(mult1, ones); \ mult2 = madd_epi16(mult2, ones); \ mult3 = madd_epi16(mult3, ones); \ mult4 = madd_epi16(mult4, ones); \ mult5 = madd_epi16(mult5, ones); \ mult6 = madd_epi16(mult6, ones); \ mult7 = madd_epi16(mult7, ones); \ /*Add in 32bit*/ \ sum0 = add_epi32(sum0, mult0); \ sum1 = add_epi32(sum1, mult1); \ sum2 = add_epi32(sum2, mult2); \ sum3 = add_epi32(sum3, mult3); \ sum4 = add_epi32(sum4, mult4); \ sum5 = add_epi32(sum5, mult5); \ sum6 = add_epi32(sum6, mult6); \ sum7 = add_epi32(sum7, mult7); \ \ } \ /* Reduce sums within 128-bit lanes.*/ \ Register pack0123 = Pack0123(sum0, sum1, sum2, sum3); \ Register pack4567 = Pack0123(sum4, sum5, sum6, sum7); \ /*The specific implementation may need to reduce further.*/ \ auto total = PermuteSummer(pack0123, pack4567); \ RunCallback(callback_impl, total, 0, B0_colidx, 1, B_cols); \ } \ } \ //An int8 version of the above code, using the add 127 technique #define INTGEMM_MULTIPLY8SHIFT(Register, target, cpu_type) \ template <class Callback> target static void Multiply8Shift(const uint8_t *A, const int8_t *B, Index A_rows, Index width, Index B_cols, Callback callback) { \ assert(width % (sizeof(Register) / sizeof(int8_t)) == 0); \ assert(B_cols % 8 == 0); \ assert(reinterpret_cast<uintptr_t>(A) % sizeof(Register) == 0); \ assert(reinterpret_cast<uintptr_t>(B) % sizeof(Register) == 0); \ const Index simd_width = width / (sizeof(Register) / sizeof(int8_t)); \ auto callback_impl = callbacks::CallbackImpl<cpu_type, Callback>(callback); \ INTGEMM_OMP_FOR \ for (Index B0_colidx = 0; B0_colidx < B_cols; B0_colidx += 8) { \ const Register *B0_col = reinterpret_cast<const Register *>(B) + simd_width * B0_colidx; \ /* Process one row of A at a time. Doesn't seem to be faster to do multiple rows of A at once.*/ \ for (Index A_rowidx = 0; A_rowidx < A_rows; ++A_rowidx) { \ const Register *A_row = reinterpret_cast<const Register*>(A + A_rowidx * width); \ /* These will be packed 16-bit integers containing sums for each row of B multiplied by the row of A. \ Iterate over shared (inner) dimension.*/ \ Index k = 0; \ Register a = *(A_row + k); \ Register sum0 = maddubs_epi16(a, *(B0_col + k * 8)); \ Register sum1 = maddubs_epi16(a, *(B0_col + k * 8 + 1)); \ Register sum2 = maddubs_epi16(a, *(B0_col + k * 8 + 2)); \ Register sum3 = maddubs_epi16(a, *(B0_col + k * 8 + 3)); \ Register sum4 = maddubs_epi16(a, *(B0_col + k * 8 + 4)); \ Register sum5 = maddubs_epi16(a, *(B0_col + k * 8 + 5)); \ Register sum6 = maddubs_epi16(a, *(B0_col + k * 8 + 6)); \ Register sum7 = maddubs_epi16(a, *(B0_col + k * 8 + 7)); \ /* Upcast to 32-bit and horizontally add. Seems a bit faster if this is declared here.*/ \ Register ones = set1_epi16<Register>(1); \ sum0 = madd_epi16(sum0, ones); \ sum1 = madd_epi16(sum1, ones); \ sum2 = madd_epi16(sum2, ones); \ sum3 = madd_epi16(sum3, ones); \ sum4 = madd_epi16(sum4, ones); \ sum5 = madd_epi16(sum5, ones); \ sum6 = madd_epi16(sum6, ones); \ sum7 = madd_epi16(sum7, ones); \ for (k = 1; k < simd_width; ++k) { \ a = *(A_row + k); \ /* Multiply 8-bit, horizontally add to packed 16-bit integers.*/ \ Register mult0 = maddubs_epi16(a, *(B0_col + k * 8)); \ Register mult1 = maddubs_epi16(a, *(B0_col + k * 8 + 1)); \ Register mult2 = maddubs_epi16(a, *(B0_col + k * 8 + 2)); \ Register mult3 = maddubs_epi16(a, *(B0_col + k * 8 + 3)); \ Register mult4 = maddubs_epi16(a, *(B0_col + k * 8 + 4)); \ Register mult5 = maddubs_epi16(a, *(B0_col + k * 8 + 5)); \ Register mult6 = maddubs_epi16(a, *(B0_col + k * 8 + 6)); \ Register mult7 = maddubs_epi16(a, *(B0_col + k * 8 + 7)); \ /* Upcast to 32-bit and horizontally add.*/ \ mult0 = madd_epi16(mult0, ones); \ mult1 = madd_epi16(mult1, ones); \ mult2 = madd_epi16(mult2, ones); \ mult3 = madd_epi16(mult3, ones); \ mult4 = madd_epi16(mult4, ones); \ mult5 = madd_epi16(mult5, ones); \ mult6 = madd_epi16(mult6, ones); \ mult7 = madd_epi16(mult7, ones); \ /*Add in 32bit*/ \ sum0 = add_epi32(sum0, mult0); \ sum1 = add_epi32(sum1, mult1); \ sum2 = add_epi32(sum2, mult2); \ sum3 = add_epi32(sum3, mult3); \ sum4 = add_epi32(sum4, mult4); \ sum5 = add_epi32(sum5, mult5); \ sum6 = add_epi32(sum6, mult6); \ sum7 = add_epi32(sum7, mult7); \ \ } \ /* Reduce sums within 128-bit lanes.*/ \ Register pack0123 = Pack0123(sum0, sum1, sum2, sum3); \ Register pack4567 = Pack0123(sum4, sum5, sum6, sum7); \ /*The specific implementation may need to reduce further.*/ \ auto total = PermuteSummer(pack0123, pack4567); \ RunCallback(callback_impl, total, A_rowidx, B0_colidx, A_rows, B_cols); \ } \ } \ } \ /* 8-bit matrix multiply used by AVX and AVX2. * These have two peculiar properties: * 1. The sign instructions don't exist in AVX512. * 2. 16 registers means gcc's register allocation failed so I wrote it in my * own asm. * 3. They support 3-argument vpsignb and vpmaddubsw. * * Fun fact: AVX introduced the three-argument vpsignb and vpmaddubsw but only * for 128-bit, despite the primary change in AVX being the addition of * 256-bit. We had to wait for INTGEMM_AVX2 to get 256-bit versions of vpsignb and * vpmaddubsw. That's why this code is generic over 128-bit or 256-bit. */ INTGEMM_AVX2 inline static void InnerINTGEMM_AVX2( __m256i a, const __m256i *b, __m256i &sum0, __m256i &sum1, __m256i &sum2, __m256i &sum3, __m256i &sum4, __m256i &sum5, __m256i &sum6, __m256i &sum7) { // Annoyingly the only 8-bit multiply is signed * unsigned (maddubs). // So we take the sign bits off of a and apply them each b in a * b. // // We have only 16 YMM registers but we want to store: // 1 for a (or |a|) // 8 temporaries for applying sign to each column of B. // 8 sums. #if defined(__GNUC__) && !defined(__clang__) // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94663 // gcc's register allocator does: // 1 for a, do all the sign application, then overwrite with |a| // 8 temporaries // 7 sums in registers + 1 on the stack // // But it's possible to complete an operation early, freeing up its // temporary register for reuse. But completing an operation early // requires us to have |a| for vpmaddubsw while completing the later // operation needs a again to apply sign. // // So we do two columns, 0 and 1, early. This allows b0_b6 and b1_b7 // to be reused by columns 6 and 7, respectively. And there's enough // registers to store both a and |a|. // // These are the temporary variables used to process each column of b. // We let the compiler choose which register number is which, but force // it to allocate all registers. __m256i absa; __m256i b0_b6, b1_b7, b2, b3, b4, b5; // Maybe this will tell gcc that we're accessing 8 registers starting // at B_live. Though I doubt it because we're passing the address as a // register. typedef struct { __m256i x[8]; } B_range; asm( // Copy the first 6 columns of b to registers. We assume B has // been rearranged so that these 8 columns are consecutive. // vpsignb does not take a memory address as its second argument, // so this can't be inlined into vsignb. "vmovdqa (%[B]), %[b0_b6]\n" "vmovdqa %c[size](%[B]), %[b1_b7]\n" // These multiplies are executed by the assembler, not by the CPU // at run time. // I would have liked to just initialize b2 etc above but that // would make it an input argument "+x" instead of "=&x". And +x // counts as two operands for purposes of gcc's annoying 30-operand // limit. "vmovdqa 2*%c[size](%[B]), %[b2]\n" "vmovdqa 3*%c[size](%[B]), %[b3]\n" "vmovdqa 4*%c[size](%[B]), %[b4]\n" "vmovdqa 5*%c[size](%[B]), %[b5]\n" // Store the absolute value of a in absa. "vpabsb %[a], %[absa]\n" // If a byte of a is negative, negate the corresponding byte in // b0_b6 etc. "vpsignb %[a], %[b0_b6], %[b0_b6]\n" "vpsignb %[a], %[b1_b7], %[b1_b7]\n" // Multiply signed * unsigned then horizontally add to form packed // 16-bit integers: // b0[0] * |a|[0] + b0[1] * |a|[1], b0[2] * |a|[2] + b0[3] * |a|[3], ... "vpmaddubsw %[b0_b6], %[absa], %[b0_b6]\n" "vpmaddubsw %[b1_b7], %[absa], %[b1_b7]\n" // vpmaddubsw has latency 5 so work on some other sign bits while // we're at it. "vpsignb %[a], %[b2], %[b2]\n" "vpsignb %[a], %[b3], %[b3]\n" "vpsignb %[a], %[b4], %[b4]\n" "vpsignb %[a], %[b5], %[b5]\n" // Perform a 16-bit add with saturation to accumlate sums. "vpaddsw %[b0_b6], %[sum0], %[sum0]\n" // Now we can reuse b0_b6 for b6 "vmovdqa 6*%c[size](%[B]), %[b0_b6]\n" "vpaddsw %[b1_b7], %[sum1], %[sum1]\n" // Now we can reuse b1_b7 for b7 "vmovdqa 7*%c[size](%[B]), %[b1_b7]\n" // More crunching while the load happens. "vpmaddubsw %[b2], %[absa], %[b2]\n" "vpmaddubsw %[b3], %[absa], %[b3]\n" "vpmaddubsw %[b4], %[absa], %[b4]\n" "vpsignb %[a], %[b0_b6], %[b0_b6]\n" "vpsignb %[a], %[b1_b7], %[b1_b7]\n" "vpmaddubsw %[b5], %[absa], %[b5]\n" "vpmaddubsw %[b0_b6], %[absa], %[b0_b6]\n" "vpmaddubsw %[b1_b7], %[absa], %[b1_b7]\n" "vpaddsw %[b2], %[sum2], %[sum2]\n" "vpaddsw %[b3], %[sum3], %[sum3]\n" "vpaddsw %[b4], %[sum4], %[sum4]\n" "vpaddsw %[b5], %[sum5], %[sum5]\n" "vpaddsw %[b0_b6], %[sum6], %[sum6]\n" "vpaddsw %[b1_b7], %[sum7], %[sum7]\n" : [sum0] "+x" (sum0), [sum1] "+x" (sum1), [sum2] "+x" (sum2), [sum3] "+x" (sum3), [sum4] "+x" (sum4), [sum5] "+x" (sum5), [sum6] "+x" (sum6), [sum7] "+x" (sum7), [b0_b6] "=&x" (b0_b6), [b1_b7] "=&x" (b1_b7), [b2] "=&x" (b2), [b3] "=&x" (b3), [b4] "=&x" (b4), [b5] "=&x" (b5), [absa] "=&x" (absa) : // I would like to use m here but that non-deterministically // chooses %(eax) or -256$(eax) and there's no way to add to that // memory address: // https://gcc.gnu.org/ml/gcc-help/2011-04/msg00518.html // [B] "r" (reinterpret_cast<const B_range*>(b)), [a] "x" (a), [size] "i" (sizeof(__m256i)) ); #else // https://bugs.llvm.org/show_bug.cgi?id=41482 // clang has a bug: target attribute avx2 doesn't allow inline assembly with // +x for YMM registers. For example, this will not compile with default // arguments: // __attribute__ ((target ("avx2"))) void Foo(__m256i sum0) { // asm("" : [sum0] "+x" (sum0)); // } // but it will compile with -mavx2. // However, clang does allow intrinsics and has a better register allocator // than gcc. So here we just use intrinsics. __m256i a_positive = abs_epi8(a); sum0 = adds_epi16(sum0, maddubs_epi16(a_positive, sign_epi8(b[0], a))); sum1 = adds_epi16(sum1, maddubs_epi16(a_positive, sign_epi8(b[1], a))); sum2 = adds_epi16(sum2, maddubs_epi16(a_positive, sign_epi8(b[2], a))); sum3 = adds_epi16(sum3, maddubs_epi16(a_positive, sign_epi8(b[3], a))); sum4 = adds_epi16(sum4, maddubs_epi16(a_positive, sign_epi8(b[4], a))); sum5 = adds_epi16(sum5, maddubs_epi16(a_positive, sign_epi8(b[5], a))); sum6 = adds_epi16(sum6, maddubs_epi16(a_positive, sign_epi8(b[6], a))); sum7 = adds_epi16(sum7, maddubs_epi16(a_positive, sign_epi8(b[7], a))); #endif } // For INTGEMM_SSSE3 without AVX INTGEMM_SSSE3 inline static void InnerINTGEMM_SSSE3( __m128i a, const __m128i *b, __m128i &sum0, __m128i &sum1, __m128i &sum2, __m128i &sum3, __m128i &sum4, __m128i &sum5, __m128i &sum6, __m128i &sum7) { __m128i a_positive = abs_epi8(a); sum0 = adds_epi16(sum0, maddubs_epi16(a_positive, sign_epi8(b[0], a))); sum1 = adds_epi16(sum1, maddubs_epi16(a_positive, sign_epi8(b[1], a))); sum2 = adds_epi16(sum2, maddubs_epi16(a_positive, sign_epi8(b[2], a))); sum3 = adds_epi16(sum3, maddubs_epi16(a_positive, sign_epi8(b[3], a))); sum4 = adds_epi16(sum4, maddubs_epi16(a_positive, sign_epi8(b[4], a))); sum5 = adds_epi16(sum5, maddubs_epi16(a_positive, sign_epi8(b[5], a))); sum6 = adds_epi16(sum6, maddubs_epi16(a_positive, sign_epi8(b[6], a))); sum7 = adds_epi16(sum7, maddubs_epi16(a_positive, sign_epi8(b[7], a))); } //INTGEMM_AVX2 or INTGEMM_SSSE3 multiply #define INTGEMM_MULTIPLY8(Register, target, cpu_type) \ template <typename Callback> target static void Multiply(const int8_t *A, const int8_t *B, Index A_rows, Index width, Index B_cols, Callback callback) { \ assert(width % sizeof(Register) == 0); \ assert(B_cols % 8 == 0); \ assert(reinterpret_cast<uintptr_t>(A) % sizeof(Register) == 0); \ assert(reinterpret_cast<uintptr_t>(B) % sizeof(Register) == 0); \ const Index simd_width = width / sizeof(Register); \ auto callback_impl = callbacks::CallbackImpl<cpu_type, Callback>(callback); \ INTGEMM_OMP_FOR \ for (Index B0_colidx = 0; B0_colidx < B_cols; B0_colidx += 8) { \ const Register *B0_col = reinterpret_cast<const Register *>(B) + simd_width * B0_colidx; \ /*Process one row of A at a time. Doesn't seem to be faster to do multiple rows of A at once.*/ \ for (Index A_rowidx = 0; A_rowidx < A_rows; ++A_rowidx) { \ /*Iterate over shared (inner) dimension.*/ \ const Register *A_live = reinterpret_cast<const Register *>(A + A_rowidx * width); \ const Register *A_end = A_live + simd_width; \ const Register *B_live = B0_col; \ /* Rather than initializing as zeros and adding, just initialize the first.*/ \ Register a = *(A_live++); \ Register a_positive = abs_epi8(a); \ /* These will be packed 16-bit integers containing sums for each column of B multiplied by the row of A.*/ \ Register sum0 = maddubs_epi16(a_positive, sign_epi8(B_live[0], a)); \ Register sum1 = maddubs_epi16(a_positive, sign_epi8(B_live[1], a)); \ Register sum2 = maddubs_epi16(a_positive, sign_epi8(B_live[2], a)); \ Register sum3 = maddubs_epi16(a_positive, sign_epi8(B_live[3], a)); \ Register sum4 = maddubs_epi16(a_positive, sign_epi8(B_live[4], a)); \ Register sum5 = maddubs_epi16(a_positive, sign_epi8(B_live[5], a)); \ Register sum6 = maddubs_epi16(a_positive, sign_epi8(B_live[6], a)); \ Register sum7 = maddubs_epi16(a_positive, sign_epi8(B_live[7], a)); \ B_live += 8; \ /* Use A as the loop variable so the add can be done where gcc likes it for branch prediction.*/ \ for (; A_live != A_end; ++A_live, B_live += 8) { \ Inner##target(*A_live, B_live, sum0, sum1, sum2, sum3, sum4, sum5, sum6, sum7); \ } \ /* Convert 16-bit to 32-bit and add, not caring what parts are added. * Implementations: * 1. https://github.com/tesseract-ocr/tesseract/blob/master/src/arch/intsimdmatrixavx2.cpp#L67 under Apache license: * This does a multiply by 1 and horizontal add: * _mm512_madd_epi16(sum, _mm512_set1_epi16(1)) * Current fastest. * * 2. Signed extension and fold halves: * sum = _mm512_add_epi32( * _mm512_cvtepi16_epi32(_mm512_castsi512_si256(sum)), * _mm512_cvtepi16_epi32(_mm512_extracti64x4_epi64(sum, 1))); * * 3. Sign extend by abuse of bitshift, then add. * sum = _mm512_add_epi32( * _mm512_srai_epi32(_mm512_slli_epi32(sum, 16), 16), * _mm512_srai_epi32(sum, 16)); */ \ Register ones = set1_epi16<Register>(1); \ sum0 = madd_epi16(sum0, ones); \ sum1 = madd_epi16(sum1, ones); \ sum2 = madd_epi16(sum2, ones); \ sum3 = madd_epi16(sum3, ones); \ sum4 = madd_epi16(sum4, ones); \ sum5 = madd_epi16(sum5, ones); \ sum6 = madd_epi16(sum6, ones); \ sum7 = madd_epi16(sum7, ones); \ Register pack0123 = Pack0123(sum0, sum1, sum2, sum3); \ Register pack4567 = Pack0123(sum4, sum5, sum6, sum7); \ auto total = PermuteSummer(pack0123, pack4567); \ RunCallback(callback_impl, total, A_rowidx, B0_colidx, A_rows, B_cols); \ } \ } \ } /* Wrap a multiply call in OMP parallelism. Here it launches threads then * inside the implementation there is a pragma omp for. In gcc >= 8 these * could have been the same but older compilers don't imbue target attributes * on the hidden function created by pragma omp parallel. * * Also, gcc 7 is unable to deduce the function pointer type (for ChooseCPU) if * I use typename Backend::Integer directly in the arguments. As a workaround, * have a default template argument Integer then use that so it's resolved. */ template <class Callback, class Backend, class Integer = typename Backend::Integer> static inline void OMPParallelWrap(const Integer *A, const Integer *B, Index A_rows, Index width, Index B_cols, Callback callback) { #pragma omp parallel Backend::template Multiply<Callback>(A, B, A_rows, width, B_cols, callback); } template <class Callback, class Backend> static inline void OMPParallelWrap8Shift(const uint8_t *A, const int8_t *B, Index A_rows, Index width, Index B_cols, Callback callback) { #pragma omp parallel Backend::template Multiply8Shift<Callback>(A, B, A_rows, width, B_cols, callback); } } // namespace intgemm
analyze.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % AAA N N AAA L Y Y ZZZZZ EEEEE % % A A NN N A A L Y Y ZZ E % % AAAAA N N N AAAAA L Y ZZZ EEE % % A A N NN A A L Y ZZ E % % A A N N A A LLLLL Y ZZZZZ EEEEE % % % % Analyze An Image % % % % Software Design % % Bill Corbis % % December 1998 % % % % % % Copyright 1999-2011 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % */ /* Include declarations. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <assert.h> #include <math.h> #include "magick/MagickCore.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % a n a l y z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % analyzeImage() computes the brightness and saturation mean, standard % deviation, kurtosis and skewness and stores these values as attributes % of the image. % % The format of the analyzeImage method is: % % size_t analyzeImage(Image *images,const int argc, % char **argv,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the address of a structure of type Image. % % o argc: Specifies a pointer to an integer describing the number of % elements in the argument vector. % % o argv: Specifies a pointer to a text array containing the command line % arguments. % % o exception: return any errors or warnings in this structure. % */ ModuleExport size_t analyzeImage(Image **images,const int argc, const char **argv,ExceptionInfo *exception) { char text[MaxTextExtent]; double area, brightness, brightness_mean, brightness_standard_deviation, brightness_kurtosis, brightness_skewness, brightness_sum_x, brightness_sum_x2, brightness_sum_x3, brightness_sum_x4, hue, saturation, saturation_mean, saturation_standard_deviation, saturation_kurtosis, saturation_skewness, saturation_sum_x, saturation_sum_x2, saturation_sum_x3, saturation_sum_x4; Image *image; assert(images != (Image **) NULL); assert(*images != (Image *) NULL); assert((*images)->signature == MagickSignature); (void) argc; (void) argv; image=(*images); for ( ; image != (Image *) NULL; image=GetNextImageInList(image)) { CacheView *image_view; MagickBooleanType status; ssize_t y; brightness_sum_x=0.0; brightness_sum_x2=0.0; brightness_sum_x3=0.0; brightness_sum_x4=0.0; brightness_mean=0.0; brightness_standard_deviation=0.0; brightness_kurtosis=0.0; brightness_skewness=0.0; saturation_sum_x=0.0; saturation_sum_x2=0.0; saturation_sum_x3=0.0; saturation_sum_x4=0.0; saturation_mean=0.0; saturation_standard_deviation=0.0; saturation_kurtosis=0.0; saturation_skewness=0.0; area=0.0; status=MagickTrue; image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ConvertRGBToHSB(p->red,p->green,p->blue,&hue,&saturation,&brightness); brightness*=QuantumRange; brightness_sum_x+=brightness; brightness_sum_x2+=brightness*brightness; brightness_sum_x3+=brightness*brightness*brightness; brightness_sum_x4+=brightness*brightness*brightness*brightness; saturation*=QuantumRange; saturation_sum_x+=saturation; saturation_sum_x2+=saturation*saturation; saturation_sum_x3+=saturation*saturation*saturation; saturation_sum_x4+=saturation*saturation*saturation*saturation; area++; p++; } } image_view=DestroyCacheView(image_view); if (area <= 0.0) break; brightness_mean=brightness_sum_x/area; (void) FormatMagickString(text,MaxTextExtent,"%g",brightness_mean); (void) SetImageProperty(image,"filter:brightness:mean",text); brightness_standard_deviation=sqrt(brightness_sum_x2/area-(brightness_sum_x/ area*brightness_sum_x/area)); (void) FormatMagickString(text,MaxTextExtent,"%g", brightness_standard_deviation); (void) SetImageProperty(image,"filter:brightness:standard-deviation",text); if (brightness_standard_deviation != 0) brightness_kurtosis=(brightness_sum_x4/area-4.0*brightness_mean* brightness_sum_x3/area+6.0*brightness_mean*brightness_mean* brightness_sum_x2/area-3.0*brightness_mean*brightness_mean* brightness_mean*brightness_mean)/(brightness_standard_deviation* brightness_standard_deviation*brightness_standard_deviation* brightness_standard_deviation)-3.0; (void) FormatMagickString(text,MaxTextExtent,"%g",brightness_kurtosis); (void) SetImageProperty(image,"filter:brightness:kurtosis",text); if (brightness_standard_deviation != 0) brightness_skewness=(brightness_sum_x3/area-3.0*brightness_mean* brightness_sum_x2/area+2.0*brightness_mean*brightness_mean* brightness_mean)/(brightness_standard_deviation* brightness_standard_deviation*brightness_standard_deviation); (void) FormatMagickString(text,MaxTextExtent,"%g",brightness_skewness); (void) SetImageProperty(image,"filter:brightness:skewness",text); saturation_mean=saturation_sum_x/area; (void) FormatMagickString(text,MaxTextExtent,"%g",saturation_mean); (void) SetImageProperty(image,"filter:saturation:mean",text); saturation_standard_deviation=sqrt(saturation_sum_x2/area-(saturation_sum_x/ area*saturation_sum_x/area)); (void) FormatMagickString(text,MaxTextExtent,"%g", saturation_standard_deviation); (void) SetImageProperty(image,"filter:saturation:standard-deviation",text); if (saturation_standard_deviation != 0) saturation_kurtosis=(saturation_sum_x4/area-4.0*saturation_mean* saturation_sum_x3/area+6.0*saturation_mean*saturation_mean* saturation_sum_x2/area-3.0*saturation_mean*saturation_mean* saturation_mean*saturation_mean)/(saturation_standard_deviation* saturation_standard_deviation*saturation_standard_deviation* saturation_standard_deviation)-3.0; (void) FormatMagickString(text,MaxTextExtent,"%g",saturation_kurtosis); (void) SetImageProperty(image,"filter:saturation:kurtosis",text); if (saturation_standard_deviation != 0) saturation_skewness=(saturation_sum_x3/area-3.0*saturation_mean* saturation_sum_x2/area+2.0*saturation_mean*saturation_mean* saturation_mean)/(saturation_standard_deviation* saturation_standard_deviation*saturation_standard_deviation); (void) FormatMagickString(text,MaxTextExtent,"%g",saturation_skewness); (void) SetImageProperty(image,"filter:saturation:skewness",text); } return(MagickImageFilterSignature); }
omp_fib.c
#include <stdio.h> #include <omp.h> // Compile with "gcc -O3 -fopenmp benchmarks/fibonacci/omp_fib.c" // and "clang -O3 -fopenmp benchmarks/fibonacci/omp_fib.c" // GCC will be very slow due to their OpenMP implementation // using a global task queue which will be a huge contention point. // Clang uses work-stealing with each thread owning a private deque. long long fib(long long n) { long long i, j; if (n<2) // Note: be sure to compare n<2 -> return n return n; // instead of n<=2 -> return 1 else { #pragma omp task shared(i) firstprivate(n) { i=fib(n-1); } j=fib(n-2); #pragma omp taskwait return i+j; } } int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: fib <n-th fibonacci number requested>\n"); exit(0); } long long n = atoi(argv[1]); #pragma omp parallel shared(n) { #pragma omp single printf ("fib(%lld) = %lld\n", n, fib(n)); } }
GB_unop__log10_fc64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__log10_fc64_fc64) // op(A') function: GB (_unop_tran__log10_fc64_fc64) // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = GB_clog10 (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_clog10 (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = GB_clog10 (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LOG10 || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__log10_fc64_fc64) ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = GB_clog10 (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = GB_clog10 (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__log10_fc64_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
bcnn_maxpool_layer.c
/* * Copyright (c) 2016-present Jean-Noel Braun. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "bcnn_maxpool_layer.h" #include <float.h> #include <math.h> #include <bh/bh_log.h> #include <bh/bh_string.h> #include "bcnn_net.h" #include "bcnn_tensor.h" #include "bcnn_utils.h" #include <bh/bh_timer.h> #ifdef BCNN_USE_NEON #include <arm_neon.h> #include <bh/bh_macros.h> #endif bcnn_status bcnn_add_maxpool_layer(bcnn_net *net, int size, int stride, bcnn_padding padding, const char *src_id, const char *dst_id) { bcnn_node node = {0}; bcnn_tensor dst_tensor = {0}; if (net->num_nodes > 0) { int is_src_node_found = 0; for (int i = net->num_tensors - 1; i >= 0; --i) { if (strcmp(net->tensors[i].name, src_id) == 0) { bcnn_node_add_input(net, &node, i); is_src_node_found = 1; break; } } BCNN_CHECK_AND_LOG( net->log_ctx, is_src_node_found, BCNN_INVALID_PARAMETER, "Maxpool layer: invalid input node name %s\n", src_id); } else { bcnn_node_add_input(net, &node, 0); } // Compute output size according to padding option int out_h = (padding == BCNN_PADDING_SAME) ? (net->tensors[node.src[0]].h + stride - 1) / stride : (padding == BCNN_PADDING_VALID) ? (net->tensors[node.src[0]].h - size + stride) / stride : (padding == BCNN_PADDING_CAFFE) ? ((int)(ceil( (float)(net->tensors[node.src[0]].h - size) / stride)) + 1) : 0; int out_w = (padding == BCNN_PADDING_SAME) ? (net->tensors[node.src[0]].w + stride - 1) / stride : (padding == BCNN_PADDING_VALID) ? (net->tensors[node.src[0]].w - size + stride) / stride : (padding == BCNN_PADDING_CAFFE) ? ((int)(ceil( (float)(net->tensors[node.src[0]].w - size) / stride)) + 1) : 0; bcnn_tensor_set_shape(&dst_tensor, net->tensors[node.src[0]].n, // batch size net->tensors[node.src[0]].c, // depth out_h, // height out_w, // width 1); bcnn_tensor_allocate(&dst_tensor, net->mode); bh_strfill(&dst_tensor.name, dst_id); // Add node to net bcnn_net_add_tensor(net, dst_tensor); // Add tensor output index to node bcnn_node_add_output(net, &node, net->num_tensors - 1); int sz = bcnn_tensor_size(&net->tensors[node.dst[0]]); node.type = BCNN_LAYER_MAXPOOL; node.param_size = sizeof(bcnn_maxpool_param); node.param = (bcnn_maxpool_param *)calloc(1, node.param_size); bcnn_maxpool_param *param = (bcnn_maxpool_param *)node.param; param->size = size; param->stride = stride; param->padding = padding; param->indexes = (int *)calloc(sz, sizeof(int)); #ifdef BCNN_USE_CUDA param->indexes_gpu = bcnn_cuda_malloc_i32(sz); #ifdef BCNN_USE_CUDNN bcnn_cudnn_check(cudnnCreateTensorDescriptor(&param->src_tensor_desc)); bcnn_cudnn_check(cudnnCreateTensorDescriptor(&param->dst_tensor_desc)); bcnn_cudnn_check(cudnnCreatePoolingDescriptor(&param->pooling_desc)); bcnn_cudnn_check(cudnnSetPooling2dDescriptor( param->pooling_desc, CUDNN_POOLING_MAX, CUDNN_NOT_PROPAGATE_NAN, param->size, param->size, 0, 0, param->stride, param->stride)); bcnn_cudnn_check(cudnnSetTensor4dDescriptor( param->src_tensor_desc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, net->tensors[node.src[0]].n, net->tensors[node.src[0]].c, net->tensors[node.src[0]].h, net->tensors[node.src[0]].w)); bcnn_cudnn_check(cudnnSetTensor4dDescriptor( param->dst_tensor_desc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, net->tensors[node.dst[0]].n, net->tensors[node.dst[0]].c, net->tensors[node.dst[0]].h, net->tensors[node.dst[0]].w)); #endif #endif node.forward = bcnn_forward_maxpool_layer; node.backward = bcnn_backward_maxpool_layer; node.release_param = bcnn_release_param_maxpool_layer; bcnn_net_add_node(net, node); char node_opname[256]; snprintf(node_opname, 256, BH_LOG_BOLDBLUE "[Maxpool]" BH_LOG_RESET " "); BCNN_INFO( net->log_ctx, "%-48s %-8s (%4d x%4d x%4d) -> %-8s (%4d x%4d x%4d) %12d x %2d / %2d\n", node_opname, net->tensors[node.src[0]].name, net->tensors[node.src[0]].w, net->tensors[node.src[0]].h, net->tensors[node.src[0]].c, net->tensors[node.dst[0]].name, net->tensors[node.dst[0]].w, net->tensors[node.dst[0]].h, net->tensors[node.dst[0]].c, size, size, stride); return 0; } void bcnn_forward_maxpool_layer_cpu(bcnn_net *net, bcnn_node *node) { bcnn_tensor *src_tensor = &net->tensors[node->src[0]]; bcnn_tensor *dst_tensor = &net->tensors[node->dst[0]]; bcnn_maxpool_param *param = (bcnn_maxpool_param *)node->param; int size = param->size; int stride = param->stride; int *indexes = param->indexes; int batch_size = dst_tensor->n; for (int b = 0; b < batch_size; ++b) { // batch_size int offset0 = dst_tensor->c * b; #pragma omp parallel for num_threads(net->num_threads) for (int k = 0; k < dst_tensor->c; ++k) { // depth int offset1 = dst_tensor->h * (k + offset0); for (int i = 0; i < dst_tensor->h; ++i) { // height int offset2 = dst_tensor->w * (offset1 + i); for (int j = 0; j < dst_tensor->w; ++j) { // width int dst_index = j + offset2; float max_f = -FLT_MAX; int max_i = -1; for (int n = 0; n < size; ++n) { // pooling window for (int m = 0; m < size; ++m) { int cur_h = i * stride + n; int cur_w = j * stride + m; int src_index = cur_w + src_tensor->w * (cur_h + src_tensor->h * (k + b * src_tensor->c)); int valid = (cur_h >= 0 && cur_h < src_tensor->h && cur_w >= 0 && cur_w < src_tensor->w); float val = (valid != 0) ? src_tensor->data[src_index] : -FLT_MAX; if (val > max_f) { max_f = val; max_i = src_index; } } } dst_tensor->data[dst_index] = max_f; indexes[dst_index] = max_i; } } } } return; } #ifdef BCNN_USE_NEON void bcnn_forward_maxpool_layer_cpu_neon_2x2(bcnn_tensor *src_tensor, bcnn_tensor *dst_tensor) { const int tail = src_tensor->w + (src_tensor->w - 2 * dst_tensor->w); for (int b = 0; b < dst_tensor->n; ++b) { // batch_size int offset0 = dst_tensor->c * b; for (int k = 0; k < dst_tensor->c; ++k) { // depth const float *p_src0 = src_tensor->data + src_tensor->h * src_tensor->w * (k + src_tensor->c * b); const float *p_src1 = src_tensor->data + src_tensor->h * src_tensor->w * (k + offset0) + src_tensor->w; float *outptr = dst_tensor->data + dst_tensor->h * dst_tensor->w * (k + offset0); for (int i = 0; i < dst_tensor->h; i++) { int half = dst_tensor->w >> 2; int last = dst_tensor->w - (half << 2); for (int x = 0; x < (half << 2); ++x) { float32x2_t max0, max1; max0 = vld1_f32(p_src0); p_src0 += 2; max1 = vld1_f32(p_src1); p_src1 += 2; max0 = vmax_f32(max0, max1); max0 = vpmax_f32(max0, max0); vst1_lane_f32(outptr, max0, 0); outptr++; } for (; last > 0; last--) { float max0 = bh_max(p_src0[0], p_src0[1]); float max1 = bh_max(p_src1[0], p_src1[1]); *outptr = bh_max(max0, max1); p_src0 += 2; p_src1 += 2; outptr++; } p_src0 += tail; p_src1 += tail; } } } return; } #endif void bcnn_forward_maxpool_layer(bcnn_net *net, bcnn_node *node) { #ifdef BCNN_USE_CUDA return bcnn_forward_maxpool_layer_gpu(net, node); #else #ifdef BCNN_USE_NEON bcnn_maxpool_param *param = (bcnn_maxpool_param *)node->param; if (param->size == 2 && param->stride == 2) { bcnn_tensor *src = &net->tensors[node->src[0]]; bcnn_tensor *dst = &net->tensors[node->dst[0]]; return bcnn_forward_maxpool_layer_cpu_neon_2x2(src, dst); } else { return bcnn_forward_maxpool_layer_cpu(net, node); } #else return bcnn_forward_maxpool_layer_cpu(net, node); #endif // BCNN_USE_NEON #endif // BCNN_USE_CUDA } void bcnn_backward_maxpool_layer_cpu(bcnn_net *net, bcnn_node *node) { bcnn_tensor *src_tensor = &net->tensors[node->src[0]]; bcnn_tensor *dst_tensor = &net->tensors[node->dst[0]]; bcnn_maxpool_param *param = (bcnn_maxpool_param *)node->param; int *indexes = param->indexes; int i, index; int sz = bcnn_tensor_size(dst_tensor); for (i = 0; i < sz; ++i) { index = indexes[i]; src_tensor->grad_data[index] += dst_tensor->grad_data[i]; } return; } void bcnn_backward_maxpool_layer(bcnn_net *net, bcnn_node *node) { #ifdef BCNN_USE_CUDA return bcnn_backward_maxpool_layer_gpu(net, node); #else return bcnn_backward_maxpool_layer_cpu(net, node); #endif return; } void bcnn_release_param_maxpool_layer(bcnn_node *node) { bcnn_maxpool_param *param = (bcnn_maxpool_param *)node->param; bh_free(param->indexes); #ifdef BCNN_USE_CUDA if (param->indexes_gpu) { bcnn_cuda_free(param->indexes_gpu); } #ifdef BCNN_USE_CUDNN cudnnDestroyTensorDescriptor(param->src_tensor_desc); cudnnDestroyTensorDescriptor(param->dst_tensor_desc); cudnnDestroyPoolingDescriptor(param->pooling_desc); #endif #endif return; }
mkldnn_common.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2019 by Contributors * \file mkldnn_common.h * \brief Common header file for MKLDNN backend subgraph * \author Ciyong Chen */ #ifndef MXNET_OPERATOR_SUBGRAPH_MKLDNN_MKLDNN_COMMON_H_ #define MXNET_OPERATOR_SUBGRAPH_MKLDNN_MKLDNN_COMMON_H_ #if MXNET_USE_ONEDNN == 1 #include <vector> #include "../../numpy/np_matrix_op-inl.h" namespace mxnet { namespace op { template <typename DType> static std::vector<float> GetWeightScales(const NDArray& weight, const NDArray* bias, const float data_scale, bool weight_channelwise_scale) { auto nthreads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); std::vector<float> weight_scales; const DType* weight_ptr = weight.data().dptr<DType>(); const DType* bias_ptr = bias ? bias->data().dptr<DType>() : nullptr; const auto wshape = weight.shape(); size_t channel = wshape[0]; size_t offset = wshape.ProdShape(1, wshape.ndim()); std::vector<DType> weight_c_min(channel, MaxValue<DType>()); std::vector<DType> weight_c_max(channel, MinValue<DType>()); for (int c = 0; c < static_cast<int>(channel); ++c) { const DType* p1 = weight_ptr + c * offset; for (size_t k = 0; k < offset; ++k) { if (weight_c_min[c] > p1[k]) weight_c_min[c] = p1[k]; if (weight_c_max[c] < p1[k]) weight_c_max[c] = p1[k]; } } if (weight_channelwise_scale) { weight_scales.resize(channel); #pragma omp parallel for num_threads(nthreads) for (int c = 0; c < static_cast<int>(channel); ++c) { float scale = GetQuantizeScale(mshadow::kInt8, weight_c_min[c], weight_c_max[c]); if (bias_ptr && bias_ptr[c]) { // avoid overflow on bias // TODO(zhennan): mkldnn has bug to handle INT_MAX in bias, so set the maximum value of bias // to INT_MAX / 2. float scale_max = static_cast<float>(bias_ptr[c] > 0 ? MaxValue<int32_t>() : MinValue<int32_t>()) / 2 / bias_ptr[c] / data_scale; scale = Min(scale, scale_max); } weight_scales[c] = scale; } } else { DType total_min = weight_c_min[0]; DType total_max = weight_c_max[0]; for (size_t c = 0; c < channel; ++c) { if (total_min > weight_c_min[c]) total_min = weight_c_min[c]; if (total_max < weight_c_max[c]) total_max = weight_c_max[c]; } weight_scales.resize(3); weight_scales[0] = GetQuantizeScale(mshadow::kInt8, total_min, total_max); weight_scales[1] = total_min; weight_scales[2] = total_max; } return weight_scales; } static inline void ConvertWeightBias2MKLDNN(NDArray* weight, NDArray* bias, bool has_bias, const mkldnn::memory::desc& weight_md, const mkldnn::memory::desc* bias_md, const int num_group, float data_scale, const std::vector<float>& weight_scales, const bool submit = true) { MKLDNNStream* stream = MKLDNNStream::Get(); const auto new_weight = NDArray(weight_md); const auto conv_weights_memory = new_weight.GetMKLDNNData(); mkldnn::primitive_attr weight_attr; if (weight_scales.size()) { const int weight_mask = (weight_scales.size()) == 1 ? 0 : 1; weight_attr.set_output_scales(weight_mask, weight_scales); } auto default_weights_memory = GetWeights(*weight, num_group); if (default_weights_memory == nullptr) default_weights_memory = weight->GetMKLDNNData(); const auto weight_reorder_pd = mkldnn::reorder::primitive_desc(*default_weights_memory, *conv_weights_memory, weight_attr); MKLDNNStream::Get()->RegisterPrimArgs( mkldnn::reorder(weight_reorder_pd), {{MKLDNN_ARG_FROM, *default_weights_memory}, {MKLDNN_ARG_TO, *conv_weights_memory}}); NDArray new_bias; if (has_bias && data_scale) { std::vector<float> bias_scales(weight_scales.size()); for (size_t c = 0; c < weight_scales.size(); ++c) { bias_scales[c] = weight_scales[c] * data_scale; } new_bias = NDArray(*bias_md); const auto conv_bias_memory = new_bias.GetMKLDNNData(); const int bias_mask = (bias_scales.size()) == 1 ? 0 : 1; mkldnn::primitive_attr bias_attr; bias_attr.set_output_scales(bias_mask, bias_scales); auto bias_weights_memory = bias->GetMKLDNNData(); const auto bias_reorder_pd = mkldnn::reorder::primitive_desc(*bias_weights_memory, *conv_bias_memory, bias_attr); MKLDNNStream::Get()->RegisterPrimArgs( mkldnn::reorder(bias_reorder_pd), {{MKLDNN_ARG_FROM, *bias_weights_memory}, {MKLDNN_ARG_TO, *conv_bias_memory}}); } if (submit) stream->Submit(); *weight = new_weight; if (has_bias && data_scale) *bias = new_bias; } static inline bool CheckReshapeConditions(const nnvm::Node& node, const index_t out_index) { const index_t split_output_index = node.inputs[0].index; if (split_output_index != out_index) return false; const auto& reshape_param = nnvm::get<NumpyXReshapeParam>(node.attrs.parsed); const auto newshape = reshape_param.newshape; if (newshape.ndim() != 4 || !(newshape[0] == newshape[1] && newshape[0] == -2)) return false; return true; } static inline bool CheckSwapAxisConditions(const nnvm::Node& node) { auto params = node.attrs.dict; int dim1 = 0, dim2 = 0; if (params.count("dim1") && params.count("dim2")) { dim1 = std::stoi(params.at("dim1")); dim2 = std::stoi(params.at("dim2")); } else { return false; } return ((dim1 == 1 && dim2 == 2) || (dim1 == 2 && dim2 == 1)); } } // namespace op } // namespace mxnet #endif // if MXNET_USE_ONEDNN == 1 #endif // MXNET_OPERATOR_SUBGRAPH_MKLDNN_MKLDNN_COMMON_H_
SpatialMaxUnpooling.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/SpatialMaxUnpooling.c" #else static void THNN_(SpatialMaxUnpooling_updateOutput_frame)(real *input_p, real *output_p, THIndex_t *ind_p, int nslices, int iwidth, int iheight, int owidth, int oheight) { int k; int has_error = 0; THIndex_t error_index; #pragma omp parallel for private(k) for (k = 0; k < nslices; k++) { real *output_p_k = output_p + k*owidth*oheight; real *input_p_k = input_p + k*iwidth*iheight; THIndex_t *ind_p_k = ind_p + k*iwidth*iheight; int i, j; THIndex_t maxp; for(i = 0; i < iheight; i++) { for(j = 0; j < iwidth; j++) { maxp = ind_p_k[i*iwidth + j] - TH_INDEX_BASE; /* retrieve position of max */ if(maxp<0 || maxp>=owidth*oheight){ #pragma omp critical { has_error = 1; error_index = maxp; } } else { output_p_k[maxp] = input_p_k[i*iwidth + j]; /* update output */ } } } } if (has_error) { THError("found an invalid max index %ld (output volumes are of size %dx%d)", error_index, oheight, owidth); } } void THNN_(SpatialMaxUnpooling_updateOutput)( THNNState *state, THTensor *input, THTensor *output, THIndexTensor *indices, int owidth, int oheight) { int dimw = 2; int dimh = 1; int nbatch = 1; int nslices; int iheight; int iwidth; real *input_data; real *output_data; THIndex_t *indices_data; THNN_ARGCHECK(input->nDimension == 3 || input->nDimension == 4, 2, input, "3D or 4D (batch mode) tensor expected for input, but got: %s"); THNN_CHECK_SHAPE_INDICES(input, indices); if (input->nDimension == 4) { nbatch = input->size[0]; dimw++; dimh++; } /* sizes */ nslices = input->size[dimh-1]; iheight = input->size[dimh]; iwidth = input->size[dimw]; /* get contiguous input and indices */ input = THTensor_(newContiguous)(input); indices = THIndexTensor_(newContiguous)(indices); /* resize output */ if (input->nDimension == 3) { THTensor_(resize3d)(output, nslices, oheight, owidth); THTensor_(zero)(output); input_data = THTensor_(data)(input); output_data = THTensor_(data)(output); indices_data = THIndexTensor_(data)(indices); THNN_(SpatialMaxUnpooling_updateOutput_frame)(input_data, output_data, indices_data, nslices, iwidth, iheight, owidth, oheight); } else { int p; THTensor_(resize4d)(output, nbatch, nslices, oheight, owidth); THTensor_(zero)(output); input_data = THTensor_(data)(input); output_data = THTensor_(data)(output); indices_data = THIndexTensor_(data)(indices); for (p = 0; p < nbatch; p++) { THNN_(SpatialMaxUnpooling_updateOutput_frame)( input_data+p*nslices*iwidth*iheight, output_data+p*nslices*owidth*oheight, indices_data+p*nslices*iwidth*iheight, nslices, iwidth, iheight, owidth, oheight); } } /* cleanup */ THTensor_(free)(input); THIndexTensor_(free)(indices); } static void THNN_(SpatialMaxUnpooling_updateGradInput_frame)(real *gradInput_p, real *gradOutput_p, THIndex_t *ind_p, int nslices, int iwidth, int iheight, int owidth, int oheight) { int k; #pragma omp parallel for private(k) for (k = 0; k < nslices; k++) { real *gradInput_p_k = gradInput_p + k*iwidth*iheight; real *gradOutput_p_k = gradOutput_p + k*owidth*oheight; THIndex_t *ind_p_k = ind_p + k*iwidth*iheight; int i, j; THIndex_t maxp; for(i = 0; i < iheight; i++) { for(j = 0; j < iwidth; j++) { maxp = ind_p_k[i*iwidth + j] - TH_INDEX_BASE; /* retrieve position of max */ if(maxp < 0 || maxp >= owidth * oheight) { THError("invalid max index %ld, owidth= %d, oheight= %d", maxp, owidth, oheight); } gradInput_p_k[i*iwidth + j] = gradOutput_p_k[maxp]; /* update gradient */ } } } } void THNN_(SpatialMaxUnpooling_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THIndexTensor *indices, int owidth, int oheight) { int dimw = 2; int dimh = 1; int nbatch = 1; int nslices; int iheight; int iwidth; real *gradInput_data; real *gradOutput_data; THIndex_t *indices_data; THNN_CHECK_SHAPE_INDICES(input, indices); /* get contiguous gradOutput and indices */ gradOutput = THTensor_(newContiguous)(gradOutput); indices = THIndexTensor_(newContiguous)(indices); /* resize */ THTensor_(resizeAs)(gradInput, input); THTensor_(zero)(gradInput); if (input->nDimension == 4) { nbatch = input->size[0]; dimw++; dimh++; } /* sizes */ nslices = input->size[dimh-1]; iheight = input->size[dimh]; iwidth = input->size[dimw]; if(owidth!=gradOutput->size[dimw] || oheight!=gradOutput->size[dimh]){ THError("Inconsistent gradOutput size. oheight= %d, owidth= %d, gradOutput: %dx%d", oheight, owidth, gradOutput->size[dimh], gradOutput->size[dimw]); } /* get raw pointers */ gradInput_data = THTensor_(data)(gradInput); gradOutput_data = THTensor_(data)(gradOutput); indices_data = THIndexTensor_(data)(indices); /* backprop */ if (input->nDimension == 3) { THNN_(SpatialMaxUnpooling_updateGradInput_frame)(gradInput_data, gradOutput_data, indices_data, nslices, iwidth, iheight, owidth, oheight); } else { int p; for (p = 0; p < nbatch; p++) { THNN_(SpatialMaxUnpooling_updateGradInput_frame)(gradInput_data+p*nslices*iwidth*iheight, gradOutput_data+p*nslices*owidth*oheight, indices_data+p*nslices*iwidth*iheight, nslices, iwidth, iheight, owidth, oheight); } } /* cleanup */ THTensor_(free)(gradOutput); THIndexTensor_(free)(indices); } #endif
implicit_blender.c
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) Blender Foundation * All rights reserved. */ /** \file * \ingroup bph */ #include "implicit.h" #ifdef IMPLICIT_SOLVER_BLENDER # include "MEM_guardedalloc.h" # include "DNA_meshdata_types.h" # include "DNA_object_force_types.h" # include "DNA_object_types.h" # include "DNA_scene_types.h" # include "DNA_texture_types.h" # include "BLI_math.h" # include "BLI_utildefines.h" # include "BKE_cloth.h" # include "BKE_collision.h" # include "BKE_effect.h" # include "BPH_mass_spring.h" # ifdef __GNUC__ # pragma GCC diagnostic ignored "-Wtype-limits" # endif # ifdef _OPENMP # define CLOTH_OPENMP_LIMIT 512 # endif //#define DEBUG_TIME # ifdef DEBUG_TIME # include "PIL_time.h" # endif static float I[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; static float ZERO[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; # if 0 # define C99 # ifdef C99 # defineDO_INLINE inline # else # defineDO_INLINE static # endif # endif /* if 0 */ struct Cloth; ////////////////////////////////////////// /* fast vector / matrix library, enhancements are welcome :) -dg */ ///////////////////////////////////////// /* DEFINITIONS */ typedef float lfVector[3]; typedef struct fmatrix3x3 { float m[3][3]; /* 3x3 matrix */ unsigned int c, r; /* column and row number */ /* int pinned; // is this vertex allowed to move? */ float n1, n2, n3; /* three normal vectors for collision constrains */ unsigned int vcount; /* vertex count */ unsigned int scount; /* spring count */ } fmatrix3x3; /////////////////////////// // float[3] vector /////////////////////////// /* simple vector code */ /* STATUS: verified */ DO_INLINE void mul_fvector_S(float to[3], float from[3], float scalar) { to[0] = from[0] * scalar; to[1] = from[1] * scalar; to[2] = from[2] * scalar; } /* simple v^T * v product ("outer product") */ /* STATUS: HAS TO BE verified (*should* work) */ DO_INLINE void mul_fvectorT_fvector(float to[3][3], float vectorA[3], float vectorB[3]) { mul_fvector_S(to[0], vectorB, vectorA[0]); mul_fvector_S(to[1], vectorB, vectorA[1]); mul_fvector_S(to[2], vectorB, vectorA[2]); } /* simple v^T * v product with scalar ("outer product") */ /* STATUS: HAS TO BE verified (*should* work) */ DO_INLINE void mul_fvectorT_fvectorS(float to[3][3], float vectorA[3], float vectorB[3], float aS) { mul_fvectorT_fvector(to, vectorA, vectorB); mul_fvector_S(to[0], to[0], aS); mul_fvector_S(to[1], to[1], aS); mul_fvector_S(to[2], to[2], aS); } # if 0 /* printf vector[3] on console: for debug output */ static void print_fvector(float m3[3]) { printf("%f\n%f\n%f\n\n", m3[0], m3[1], m3[2]); } /////////////////////////// // long float vector float (*)[3] /////////////////////////// /* print long vector on console: for debug output */ DO_INLINE void print_lfvector(float (*fLongVector)[3], unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { print_fvector(fLongVector[i]); } } # endif /* create long vector */ DO_INLINE lfVector *create_lfvector(unsigned int verts) { /* TODO: check if memory allocation was successful */ return (lfVector *)MEM_callocN(verts * sizeof(lfVector), "cloth_implicit_alloc_vector"); // return (lfVector *)cloth_aligned_malloc(&MEMORY_BASE, verts * sizeof(lfVector)); } /* delete long vector */ DO_INLINE void del_lfvector(float (*fLongVector)[3]) { if (fLongVector != NULL) { MEM_freeN(fLongVector); // cloth_aligned_free(&MEMORY_BASE, fLongVector); } } /* copy long vector */ DO_INLINE void cp_lfvector(float (*to)[3], float (*from)[3], unsigned int verts) { memcpy(to, from, verts * sizeof(lfVector)); } /* init long vector with float[3] */ DO_INLINE void init_lfvector(float (*fLongVector)[3], float vector[3], unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { copy_v3_v3(fLongVector[i], vector); } } /* zero long vector with float[3] */ DO_INLINE void zero_lfvector(float (*to)[3], unsigned int verts) { memset(to, 0.0f, verts * sizeof(lfVector)); } /* multiply long vector with scalar*/ DO_INLINE void mul_lfvectorS(float (*to)[3], float (*fLongVector)[3], float scalar, unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { mul_fvector_S(to[i], fLongVector[i], scalar); } } /* multiply long vector with scalar*/ /* A -= B * float */ DO_INLINE void submul_lfvectorS(float (*to)[3], float (*fLongVector)[3], float scalar, unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { VECSUBMUL(to[i], fLongVector[i], scalar); } } /* dot product for big vector */ DO_INLINE float dot_lfvector(float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts) { long i = 0; float temp = 0.0; // XXX brecht, disabled this for now (first schedule line was already disabled), // due to non-commutative nature of floating point ops this makes the sim give // different results each time you run it! // schedule(guided, 2) //#pragma omp parallel for reduction(+: temp) if (verts > CLOTH_OPENMP_LIMIT) for (i = 0; i < (long)verts; i++) { temp += dot_v3v3(fLongVectorA[i], fLongVectorB[i]); } return temp; } /* A = B + C --> for big vector */ DO_INLINE void add_lfvector_lfvector(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { add_v3_v3v3(to[i], fLongVectorA[i], fLongVectorB[i]); } } /* A = B + C * float --> for big vector */ DO_INLINE void add_lfvector_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], float bS, unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { VECADDS(to[i], fLongVectorA[i], fLongVectorB[i], bS); } } /* A = B * float + C * float --> for big vector */ DO_INLINE void add_lfvectorS_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float aS, float (*fLongVectorB)[3], float bS, unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { VECADDSS(to[i], fLongVectorA[i], aS, fLongVectorB[i], bS); } } /* A = B - C * float --> for big vector */ DO_INLINE void sub_lfvector_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], float bS, unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { VECSUBS(to[i], fLongVectorA[i], fLongVectorB[i], bS); } } /* A = B - C --> for big vector */ DO_INLINE void sub_lfvector_lfvector(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts) { unsigned int i = 0; for (i = 0; i < verts; i++) { sub_v3_v3v3(to[i], fLongVectorA[i], fLongVectorB[i]); } } /////////////////////////// // 3x3 matrix /////////////////////////// # if 0 /* printf 3x3 matrix on console: for debug output */ static void print_fmatrix(float m3[3][3]) { printf("%f\t%f\t%f\n", m3[0][0], m3[0][1], m3[0][2]); printf("%f\t%f\t%f\n", m3[1][0], m3[1][1], m3[1][2]); printf("%f\t%f\t%f\n\n", m3[2][0], m3[2][1], m3[2][2]); } static void print_sparse_matrix(fmatrix3x3 *m) { if (m) { unsigned int i; for (i = 0; i < m[0].vcount + m[0].scount; i++) { printf("%d:\n", i); print_fmatrix(m[i].m); } } } # endif # if 0 static void print_lvector(lfVector *v, int numverts) { int i; for (i = 0; i < numverts; i++) { if (i > 0) { printf("\n"); } printf("%f,\n", v[i][0]); printf("%f,\n", v[i][1]); printf("%f,\n", v[i][2]); } } # endif # if 0 static void print_bfmatrix(fmatrix3x3 *m) { int tot = m[0].vcount + m[0].scount; int size = m[0].vcount * 3; float *t = MEM_callocN(sizeof(float) * size * size, "bfmatrix"); int q, i, j; for (q = 0; q < tot; q++) { int k = 3 * m[q].r; int l = 3 * m[q].c; for (j = 0; j < 3; j++) { for (i = 0; i < 3; i++) { // if (t[k + i + (l + j) * size] != 0.0f) { // printf("warning: overwriting value at %d, %d\n", m[q].r, m[q].c); // } if (k == l) { t[k + i + (k + j) * size] += m[q].m[i][j]; } else { t[k + i + (l + j) * size] += m[q].m[i][j]; t[l + j + (k + i) * size] += m[q].m[j][i]; } } } } for (j = 0; j < size; j++) { if (j > 0 && j % 3 == 0) { printf("\n"); } for (i = 0; i < size; i++) { if (i > 0 && i % 3 == 0) { printf(" "); } implicit_print_matrix_elem(t[i + j * size]); } printf("\n"); } MEM_freeN(t); } # endif /* copy 3x3 matrix */ DO_INLINE void cp_fmatrix(float to[3][3], float from[3][3]) { // memcpy(to, from, sizeof (float) * 9); copy_v3_v3(to[0], from[0]); copy_v3_v3(to[1], from[1]); copy_v3_v3(to[2], from[2]); } /* copy 3x3 matrix */ DO_INLINE void initdiag_fmatrixS(float to[3][3], float aS) { cp_fmatrix(to, ZERO); to[0][0] = aS; to[1][1] = aS; to[2][2] = aS; } # if 0 /* calculate determinant of 3x3 matrix */ DO_INLINE float det_fmatrix(float m[3][3]) { return m[0][0] * m[1][1] * m[2][2] + m[1][0] * m[2][1] * m[0][2] + m[0][1] * m[1][2] * m[2][0] - m[0][0] * m[1][2] * m[2][1] - m[0][1] * m[1][0] * m[2][2] - m[2][0] * m[1][1] * m[0][2]; } DO_INLINE void inverse_fmatrix(float to[3][3], float from[3][3]) { unsigned int i, j; float d; if ((d = det_fmatrix(from)) == 0) { printf("can't build inverse"); exit(0); } for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { int i1 = (i + 1) % 3; int i2 = (i + 2) % 3; int j1 = (j + 1) % 3; int j2 = (j + 2) % 3; /** Reverse indexes i&j to take transpose. */ to[j][i] = (from[i1][j1] * from[i2][j2] - from[i1][j2] * from[i2][j1]) / d; /** * <pre> * if (i == j) { * to[i][j] = 1.0f / from[i][j]; * } * else { * to[i][j] = 0; * } * </pre> */ } } } # endif /* 3x3 matrix multiplied by a scalar */ /* STATUS: verified */ DO_INLINE void mul_fmatrix_S(float matrix[3][3], float scalar) { mul_fvector_S(matrix[0], matrix[0], scalar); mul_fvector_S(matrix[1], matrix[1], scalar); mul_fvector_S(matrix[2], matrix[2], scalar); } /* a vector multiplied by a 3x3 matrix */ /* STATUS: verified */ DO_INLINE void mul_fvector_fmatrix(float *to, float *from, float matrix[3][3]) { to[0] = matrix[0][0] * from[0] + matrix[1][0] * from[1] + matrix[2][0] * from[2]; to[1] = matrix[0][1] * from[0] + matrix[1][1] * from[1] + matrix[2][1] * from[2]; to[2] = matrix[0][2] * from[0] + matrix[1][2] * from[1] + matrix[2][2] * from[2]; } /* 3x3 matrix multiplied by a vector */ /* STATUS: verified */ DO_INLINE void mul_fmatrix_fvector(float *to, float matrix[3][3], float from[3]) { to[0] = dot_v3v3(matrix[0], from); to[1] = dot_v3v3(matrix[1], from); to[2] = dot_v3v3(matrix[2], from); } /* 3x3 matrix addition with 3x3 matrix */ DO_INLINE void add_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3]) { add_v3_v3v3(to[0], matrixA[0], matrixB[0]); add_v3_v3v3(to[1], matrixA[1], matrixB[1]); add_v3_v3v3(to[2], matrixA[2], matrixB[2]); } /* A -= B*x + C*y (3x3 matrix sub-addition with 3x3 matrix) */ DO_INLINE void subadd_fmatrixS_fmatrixS( float to[3][3], float matrixA[3][3], float aS, float matrixB[3][3], float bS) { VECSUBADDSS(to[0], matrixA[0], aS, matrixB[0], bS); VECSUBADDSS(to[1], matrixA[1], aS, matrixB[1], bS); VECSUBADDSS(to[2], matrixA[2], aS, matrixB[2], bS); } /* A = B - C (3x3 matrix subtraction with 3x3 matrix) */ DO_INLINE void sub_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3]) { sub_v3_v3v3(to[0], matrixA[0], matrixB[0]); sub_v3_v3v3(to[1], matrixA[1], matrixB[1]); sub_v3_v3v3(to[2], matrixA[2], matrixB[2]); } ///////////////////////////////////////////////////////////////// // special functions ///////////////////////////////////////////////////////////////// /* 3x3 matrix multiplied+added by a vector */ /* STATUS: verified */ DO_INLINE void muladd_fmatrix_fvector(float to[3], float matrix[3][3], float from[3]) { to[0] += dot_v3v3(matrix[0], from); to[1] += dot_v3v3(matrix[1], from); to[2] += dot_v3v3(matrix[2], from); } DO_INLINE void muladd_fmatrixT_fvector(float to[3], float matrix[3][3], float from[3]) { to[0] += matrix[0][0] * from[0] + matrix[1][0] * from[1] + matrix[2][0] * from[2]; to[1] += matrix[0][1] * from[0] + matrix[1][1] * from[1] + matrix[2][1] * from[2]; to[2] += matrix[0][2] * from[0] + matrix[1][2] * from[1] + matrix[2][2] * from[2]; } BLI_INLINE void outerproduct(float r[3][3], const float a[3], const float b[3]) { mul_v3_v3fl(r[0], a, b[0]); mul_v3_v3fl(r[1], a, b[1]); mul_v3_v3fl(r[2], a, b[2]); } BLI_INLINE void cross_m3_v3m3(float r[3][3], const float v[3], float m[3][3]) { cross_v3_v3v3(r[0], v, m[0]); cross_v3_v3v3(r[1], v, m[1]); cross_v3_v3v3(r[2], v, m[2]); } BLI_INLINE void cross_v3_identity(float r[3][3], const float v[3]) { r[0][0] = 0.0f; r[1][0] = v[2]; r[2][0] = -v[1]; r[0][1] = -v[2]; r[1][1] = 0.0f; r[2][1] = v[0]; r[0][2] = v[1]; r[1][2] = -v[0]; r[2][2] = 0.0f; } BLI_INLINE void madd_m3_m3fl(float r[3][3], float m[3][3], float f) { r[0][0] += m[0][0] * f; r[0][1] += m[0][1] * f; r[0][2] += m[0][2] * f; r[1][0] += m[1][0] * f; r[1][1] += m[1][1] * f; r[1][2] += m[1][2] * f; r[2][0] += m[2][0] * f; r[2][1] += m[2][1] * f; r[2][2] += m[2][2] * f; } ///////////////////////////////////////////////////////////////// /////////////////////////// // SPARSE SYMMETRIC big matrix with 3x3 matrix entries /////////////////////////// /* printf a big matrix on console: for debug output */ # if 0 static void print_bfmatrix(fmatrix3x3 *m3) { unsigned int i = 0; for (i = 0; i < m3[0].vcount + m3[0].scount; i++) { print_fmatrix(m3[i].m); } } # endif BLI_INLINE void init_fmatrix(fmatrix3x3 *matrix, int r, int c) { matrix->r = r; matrix->c = c; } /* create big matrix */ DO_INLINE fmatrix3x3 *create_bfmatrix(unsigned int verts, unsigned int springs) { // TODO: check if memory allocation was successful */ fmatrix3x3 *temp = (fmatrix3x3 *)MEM_callocN(sizeof(fmatrix3x3) * (verts + springs), "cloth_implicit_alloc_matrix"); int i; temp[0].vcount = verts; temp[0].scount = springs; /* vertex part of the matrix is diagonal blocks */ for (i = 0; i < verts; i++) { init_fmatrix(temp + i, i, i); } return temp; } /* delete big matrix */ DO_INLINE void del_bfmatrix(fmatrix3x3 *matrix) { if (matrix != NULL) { MEM_freeN(matrix); } } /* copy big matrix */ DO_INLINE void cp_bfmatrix(fmatrix3x3 *to, fmatrix3x3 *from) { // TODO bounds checking memcpy(to, from, sizeof(fmatrix3x3) * (from[0].vcount + from[0].scount)); } /* init big matrix */ // slow in parallel DO_INLINE void init_bfmatrix(fmatrix3x3 *matrix, float m3[3][3]) { unsigned int i; for (i = 0; i < matrix[0].vcount + matrix[0].scount; i++) { cp_fmatrix(matrix[i].m, m3); } } /* init the diagonal of big matrix */ // slow in parallel DO_INLINE void initdiag_bfmatrix(fmatrix3x3 *matrix, float m3[3][3]) { unsigned int i, j; float tmatrix[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; for (i = 0; i < matrix[0].vcount; i++) { cp_fmatrix(matrix[i].m, m3); } for (j = matrix[0].vcount; j < matrix[0].vcount + matrix[0].scount; j++) { cp_fmatrix(matrix[j].m, tmatrix); } } /* SPARSE SYMMETRIC multiply big matrix with long vector*/ /* STATUS: verified */ DO_INLINE void mul_bfmatrix_lfvector(float (*to)[3], fmatrix3x3 *from, lfVector *fLongVector) { unsigned int vcount = from[0].vcount; lfVector *temp = create_lfvector(vcount); zero_lfvector(to, vcount); # pragma omp parallel sections if (vcount > CLOTH_OPENMP_LIMIT) { # pragma omp section { for (unsigned int i = from[0].vcount; i < from[0].vcount + from[0].scount; i++) { /* This is the lower triangle of the sparse matrix, * therefore multiplication occurs with transposed submatrices. */ muladd_fmatrixT_fvector(to[from[i].c], from[i].m, fLongVector[from[i].r]); } } # pragma omp section { for (unsigned int i = 0; i < from[0].vcount + from[0].scount; i++) { muladd_fmatrix_fvector(temp[from[i].r], from[i].m, fLongVector[from[i].c]); } } } add_lfvector_lfvector(to, to, temp, from[0].vcount); del_lfvector(temp); } /* SPARSE SYMMETRIC sub big matrix with big matrix*/ /* A -= B * float + C * float --> for big matrix */ /* VERIFIED */ DO_INLINE void subadd_bfmatrixS_bfmatrixS( fmatrix3x3 *to, fmatrix3x3 *from, float aS, fmatrix3x3 *matrix, float bS) { unsigned int i = 0; /* process diagonal elements */ for (i = 0; i < matrix[0].vcount + matrix[0].scount; i++) { subadd_fmatrixS_fmatrixS(to[i].m, from[i].m, aS, matrix[i].m, bS); } } /////////////////////////////////////////////////////////////////// // simulator start /////////////////////////////////////////////////////////////////// typedef struct Implicit_Data { /* inputs */ fmatrix3x3 *bigI; /* identity (constant) */ fmatrix3x3 *tfm; /* local coordinate transform */ fmatrix3x3 *M; /* masses */ lfVector *F; /* forces */ fmatrix3x3 *dFdV, *dFdX; /* force jacobians */ int num_blocks; /* number of off-diagonal blocks (springs) */ /* motion state data */ lfVector *X, *Xnew; /* positions */ lfVector *V, *Vnew; /* velocities */ /* internal solver data */ lfVector *B; /* B for A*dV = B */ fmatrix3x3 *A; /* A for A*dV = B */ lfVector *dV; /* velocity change (solution of A*dV = B) */ lfVector *z; /* target velocity in constrained directions */ fmatrix3x3 *S; /* filtering matrix for constraints */ fmatrix3x3 *P, *Pinv; /* pre-conditioning matrix */ } Implicit_Data; Implicit_Data *BPH_mass_spring_solver_create(int numverts, int numsprings) { Implicit_Data *id = (Implicit_Data *)MEM_callocN(sizeof(Implicit_Data), "implicit vecmat"); /* process diagonal elements */ id->tfm = create_bfmatrix(numverts, 0); id->A = create_bfmatrix(numverts, numsprings); id->dFdV = create_bfmatrix(numverts, numsprings); id->dFdX = create_bfmatrix(numverts, numsprings); id->S = create_bfmatrix(numverts, 0); id->Pinv = create_bfmatrix(numverts, numsprings); id->P = create_bfmatrix(numverts, numsprings); id->bigI = create_bfmatrix(numverts, numsprings); // TODO 0 springs id->M = create_bfmatrix(numverts, numsprings); id->X = create_lfvector(numverts); id->Xnew = create_lfvector(numverts); id->V = create_lfvector(numverts); id->Vnew = create_lfvector(numverts); id->F = create_lfvector(numverts); id->B = create_lfvector(numverts); id->dV = create_lfvector(numverts); id->z = create_lfvector(numverts); initdiag_bfmatrix(id->bigI, I); return id; } void BPH_mass_spring_solver_free(Implicit_Data *id) { del_bfmatrix(id->tfm); del_bfmatrix(id->A); del_bfmatrix(id->dFdV); del_bfmatrix(id->dFdX); del_bfmatrix(id->S); del_bfmatrix(id->P); del_bfmatrix(id->Pinv); del_bfmatrix(id->bigI); del_bfmatrix(id->M); del_lfvector(id->X); del_lfvector(id->Xnew); del_lfvector(id->V); del_lfvector(id->Vnew); del_lfvector(id->F); del_lfvector(id->B); del_lfvector(id->dV); del_lfvector(id->z); MEM_freeN(id); } /* ==== Transformation from/to root reference frames ==== */ BLI_INLINE void world_to_root_v3(Implicit_Data *data, int index, float r[3], const float v[3]) { copy_v3_v3(r, v); mul_transposed_m3_v3(data->tfm[index].m, r); } BLI_INLINE void root_to_world_v3(Implicit_Data *data, int index, float r[3], const float v[3]) { mul_v3_m3v3(r, data->tfm[index].m, v); } BLI_INLINE void world_to_root_m3(Implicit_Data *data, int index, float r[3][3], float m[3][3]) { float trot[3][3]; copy_m3_m3(trot, data->tfm[index].m); transpose_m3(trot); mul_m3_m3m3(r, trot, m); } BLI_INLINE void root_to_world_m3(Implicit_Data *data, int index, float r[3][3], float m[3][3]) { mul_m3_m3m3(r, data->tfm[index].m, m); } /* ================================ */ DO_INLINE void filter(lfVector *V, fmatrix3x3 *S) { unsigned int i = 0; for (i = 0; i < S[0].vcount; i++) { mul_m3_v3(S[i].m, V[S[i].r]); } } /* this version of the CG algorithm does not work very well with partial constraints * (where S has non-zero elements). */ # if 0 static int cg_filtered(lfVector *ldV, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S) { // Solves for unknown X in equation AX=B unsigned int conjgrad_loopcount = 0, conjgrad_looplimit = 100; float conjgrad_epsilon = 0.0001f /* , conjgrad_lasterror=0 */ /* UNUSED */; lfVector *q, *d, *tmp, *r; float s, starget, a, s_prev; unsigned int numverts = lA[0].vcount; q = create_lfvector(numverts); d = create_lfvector(numverts); tmp = create_lfvector(numverts); r = create_lfvector(numverts); // zero_lfvector(ldV, CLOTHPARTICLES); filter(ldV, S); add_lfvector_lfvector(ldV, ldV, z, numverts); // r = B - Mul(tmp, A, X); // just use B if X known to be zero cp_lfvector(r, lB, numverts); mul_bfmatrix_lfvector(tmp, lA, ldV); sub_lfvector_lfvector(r, r, tmp, numverts); filter(r, S); cp_lfvector(d, r, numverts); s = dot_lfvector(r, r, numverts); starget = s * sqrtf(conjgrad_epsilon); while (s > starget && conjgrad_loopcount < conjgrad_looplimit) { // Mul(q, A, d); // q = A*d; mul_bfmatrix_lfvector(q, lA, d); filter(q, S); a = s / dot_lfvector(d, q, numverts); // X = X + d*a; add_lfvector_lfvectorS(ldV, ldV, d, a, numverts); // r = r - q*a; sub_lfvector_lfvectorS(r, r, q, a, numverts); s_prev = s; s = dot_lfvector(r, r, numverts); //d = r+d*(s/s_prev); add_lfvector_lfvectorS(d, r, d, (s / s_prev), numverts); filter(d, S); conjgrad_loopcount++; } /* conjgrad_lasterror = s; */ /* UNUSED */ del_lfvector(q); del_lfvector(d); del_lfvector(tmp); del_lfvector(r); // printf("W/O conjgrad_loopcount: %d\n", conjgrad_loopcount); return conjgrad_loopcount < conjgrad_looplimit; // true means we reached desired accuracy in given time - ie stable } # endif static int cg_filtered(lfVector *ldV, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S, ImplicitSolverResult *result) { // Solves for unknown X in equation AX=B unsigned int conjgrad_loopcount = 0, conjgrad_looplimit = 100; float conjgrad_epsilon = 0.01f; unsigned int numverts = lA[0].vcount; lfVector *fB = create_lfvector(numverts); lfVector *AdV = create_lfvector(numverts); lfVector *r = create_lfvector(numverts); lfVector *c = create_lfvector(numverts); lfVector *q = create_lfvector(numverts); lfVector *s = create_lfvector(numverts); float bnorm2, delta_new, delta_old, delta_target, alpha; cp_lfvector(ldV, z, numverts); /* d0 = filter(B)^T * P * filter(B) */ cp_lfvector(fB, lB, numverts); filter(fB, S); bnorm2 = dot_lfvector(fB, fB, numverts); delta_target = conjgrad_epsilon * conjgrad_epsilon * bnorm2; /* r = filter(B - A * dV) */ mul_bfmatrix_lfvector(AdV, lA, ldV); sub_lfvector_lfvector(r, lB, AdV, numverts); filter(r, S); /* c = filter(P^-1 * r) */ cp_lfvector(c, r, numverts); filter(c, S); /* delta = r^T * c */ delta_new = dot_lfvector(r, c, numverts); # ifdef IMPLICIT_PRINT_SOLVER_INPUT_OUTPUT printf("==== A ====\n"); print_bfmatrix(lA); printf("==== z ====\n"); print_lvector(z, numverts); printf("==== B ====\n"); print_lvector(lB, numverts); printf("==== S ====\n"); print_bfmatrix(S); # endif while (delta_new > delta_target && conjgrad_loopcount < conjgrad_looplimit) { mul_bfmatrix_lfvector(q, lA, c); filter(q, S); alpha = delta_new / dot_lfvector(c, q, numverts); add_lfvector_lfvectorS(ldV, ldV, c, alpha, numverts); add_lfvector_lfvectorS(r, r, q, -alpha, numverts); /* s = P^-1 * r */ cp_lfvector(s, r, numverts); delta_old = delta_new; delta_new = dot_lfvector(r, s, numverts); add_lfvector_lfvectorS(c, s, c, delta_new / delta_old, numverts); filter(c, S); conjgrad_loopcount++; } # ifdef IMPLICIT_PRINT_SOLVER_INPUT_OUTPUT printf("==== dV ====\n"); print_lvector(ldV, numverts); printf("========\n"); # endif del_lfvector(fB); del_lfvector(AdV); del_lfvector(r); del_lfvector(c); del_lfvector(q); del_lfvector(s); // printf("W/O conjgrad_loopcount: %d\n", conjgrad_loopcount); result->status = conjgrad_loopcount < conjgrad_looplimit ? BPH_SOLVER_SUCCESS : BPH_SOLVER_NO_CONVERGENCE; result->iterations = conjgrad_loopcount; result->error = bnorm2 > 0.0f ? sqrtf(delta_new / bnorm2) : 0.0f; return conjgrad_loopcount < conjgrad_looplimit; // true means we reached desired accuracy in given time - ie stable } # if 0 // block diagonalizer DO_INLINE void BuildPPinv(fmatrix3x3 *lA, fmatrix3x3 *P, fmatrix3x3 *Pinv) { unsigned int i = 0; // Take only the diagonal blocks of A // #pragma omp parallel for private(i) if (lA[0].vcount > CLOTH_OPENMP_LIMIT) for (i = 0; i < lA[0].vcount; i++) { // block diagonalizer cp_fmatrix(P[i].m, lA[i].m); inverse_fmatrix(Pinv[i].m, P[i].m); } } # if 0 // version 1.3 static int cg_filtered_pre(lfVector *dv, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S, fmatrix3x3 *P, fmatrix3x3 *Pinv) { unsigned int numverts = lA[0].vcount, iterations = 0, conjgrad_looplimit = 100; float delta0 = 0, deltaNew = 0, deltaOld = 0, alpha = 0; float conjgrad_epsilon = 0.0001; // 0.2 is dt for steps=5 lfVector *r = create_lfvector(numverts); lfVector *p = create_lfvector(numverts); lfVector *s = create_lfvector(numverts); lfVector *h = create_lfvector(numverts); BuildPPinv(lA, P, Pinv); filter(dv, S); add_lfvector_lfvector(dv, dv, z, numverts); mul_bfmatrix_lfvector(r, lA, dv); sub_lfvector_lfvector(r, lB, r, numverts); filter(r, S); mul_prevfmatrix_lfvector(p, Pinv, r); filter(p, S); deltaNew = dot_lfvector(r, p, numverts); delta0 = deltaNew * sqrt(conjgrad_epsilon); # ifdef DEBUG_TIME double start = PIL_check_seconds_timer(); # endif while ((deltaNew > delta0) && (iterations < conjgrad_looplimit)) { iterations++; mul_bfmatrix_lfvector(s, lA, p); filter(s, S); alpha = deltaNew / dot_lfvector(p, s, numverts); add_lfvector_lfvectorS(dv, dv, p, alpha, numverts); add_lfvector_lfvectorS(r, r, s, -alpha, numverts); mul_prevfmatrix_lfvector(h, Pinv, r); filter(h, S); deltaOld = deltaNew; deltaNew = dot_lfvector(r, h, numverts); add_lfvector_lfvectorS(p, h, p, deltaNew / deltaOld, numverts); filter(p, S); } # ifdef DEBUG_TIME double end = PIL_check_seconds_timer(); printf("cg_filtered_pre time: %f\n", (float)(end - start)); # endif del_lfvector(h); del_lfvector(s); del_lfvector(p); del_lfvector(r); printf("iterations: %d\n", iterations); return iterations < conjgrad_looplimit; } # endif // version 1.4 static int cg_filtered_pre(lfVector *dv, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S, fmatrix3x3 *P, fmatrix3x3 *Pinv, fmatrix3x3 *bigI) { unsigned int numverts = lA[0].vcount, iterations = 0, conjgrad_looplimit = 100; float delta0 = 0, deltaNew = 0, deltaOld = 0, alpha = 0, tol = 0; lfVector *r = create_lfvector(numverts); lfVector *p = create_lfvector(numverts); lfVector *s = create_lfvector(numverts); lfVector *h = create_lfvector(numverts); lfVector *bhat = create_lfvector(numverts); lfVector *btemp = create_lfvector(numverts); BuildPPinv(lA, P, Pinv); initdiag_bfmatrix(bigI, I); sub_bfmatrix_Smatrix(bigI, bigI, S); // x = Sx_0+(I-S)z filter(dv, S); add_lfvector_lfvector(dv, dv, z, numverts); // b_hat = S(b-A(I-S)z) mul_bfmatrix_lfvector(r, lA, z); mul_bfmatrix_lfvector(bhat, bigI, r); sub_lfvector_lfvector(bhat, lB, bhat, numverts); // r = S(b-Ax) mul_bfmatrix_lfvector(r, lA, dv); sub_lfvector_lfvector(r, lB, r, numverts); filter(r, S); // p = SP^-1r mul_prevfmatrix_lfvector(p, Pinv, r); filter(p, S); // delta0 = bhat^TP^-1bhat mul_prevfmatrix_lfvector(btemp, Pinv, bhat); delta0 = dot_lfvector(bhat, btemp, numverts); // deltaNew = r^TP deltaNew = dot_lfvector(r, p, numverts); # if 0 filter(dv, S); add_lfvector_lfvector(dv, dv, z, numverts); mul_bfmatrix_lfvector(r, lA, dv); sub_lfvector_lfvector(r, lB, r, numverts); filter(r, S); mul_prevfmatrix_lfvector(p, Pinv, r); filter(p, S); deltaNew = dot_lfvector(r, p, numverts); delta0 = deltaNew * sqrt(conjgrad_epsilon); # endif # ifdef DEBUG_TIME double start = PIL_check_seconds_timer(); # endif tol = (0.01 * 0.2); while ((deltaNew > delta0 * tol * tol) && (iterations < conjgrad_looplimit)) { iterations++; mul_bfmatrix_lfvector(s, lA, p); filter(s, S); alpha = deltaNew / dot_lfvector(p, s, numverts); add_lfvector_lfvectorS(dv, dv, p, alpha, numverts); add_lfvector_lfvectorS(r, r, s, -alpha, numverts); mul_prevfmatrix_lfvector(h, Pinv, r); filter(h, S); deltaOld = deltaNew; deltaNew = dot_lfvector(r, h, numverts); add_lfvector_lfvectorS(p, h, p, deltaNew / deltaOld, numverts); filter(p, S); } # ifdef DEBUG_TIME double end = PIL_check_seconds_timer(); printf("cg_filtered_pre time: %f\n", (float)(end - start)); # endif del_lfvector(btemp); del_lfvector(bhat); del_lfvector(h); del_lfvector(s); del_lfvector(p); del_lfvector(r); // printf("iterations: %d\n", iterations); return iterations < conjgrad_looplimit; } # endif bool BPH_mass_spring_solve_velocities(Implicit_Data *data, float dt, ImplicitSolverResult *result) { unsigned int numverts = data->dFdV[0].vcount; lfVector *dFdXmV = create_lfvector(numverts); zero_lfvector(data->dV, numverts); cp_bfmatrix(data->A, data->M); subadd_bfmatrixS_bfmatrixS(data->A, data->dFdV, dt, data->dFdX, (dt * dt)); mul_bfmatrix_lfvector(dFdXmV, data->dFdX, data->V); add_lfvectorS_lfvectorS(data->B, data->F, dt, dFdXmV, (dt * dt), numverts); # ifdef DEBUG_TIME double start = PIL_check_seconds_timer(); # endif /* Conjugate gradient algorithm to solve Ax=b. */ cg_filtered(data->dV, data->A, data->B, data->z, data->S, result); // cg_filtered_pre(id->dV, id->A, id->B, id->z, id->S, id->P, id->Pinv, id->bigI); # ifdef DEBUG_TIME double end = PIL_check_seconds_timer(); printf("cg_filtered calc time: %f\n", (float)(end - start)); # endif // advance velocities add_lfvector_lfvector(data->Vnew, data->V, data->dV, numverts); del_lfvector(dFdXmV); return result->status == BPH_SOLVER_SUCCESS; } bool BPH_mass_spring_solve_positions(Implicit_Data *data, float dt) { int numverts = data->M[0].vcount; // advance positions add_lfvector_lfvectorS(data->Xnew, data->X, data->Vnew, dt, numverts); return true; } void BPH_mass_spring_apply_result(Implicit_Data *data) { int numverts = data->M[0].vcount; cp_lfvector(data->X, data->Xnew, numverts); cp_lfvector(data->V, data->Vnew, numverts); } void BPH_mass_spring_set_vertex_mass(Implicit_Data *data, int index, float mass) { unit_m3(data->M[index].m); mul_m3_fl(data->M[index].m, mass); } void BPH_mass_spring_set_rest_transform(Implicit_Data *data, int index, float tfm[3][3]) { # ifdef CLOTH_ROOT_FRAME copy_m3_m3(data->tfm[index].m, tfm); # else unit_m3(data->tfm[index].m); (void)tfm; # endif } void BPH_mass_spring_set_motion_state(Implicit_Data *data, int index, const float x[3], const float v[3]) { world_to_root_v3(data, index, data->X[index], x); world_to_root_v3(data, index, data->V[index], v); } void BPH_mass_spring_set_position(Implicit_Data *data, int index, const float x[3]) { world_to_root_v3(data, index, data->X[index], x); } void BPH_mass_spring_set_velocity(Implicit_Data *data, int index, const float v[3]) { world_to_root_v3(data, index, data->V[index], v); } void BPH_mass_spring_get_motion_state(struct Implicit_Data *data, int index, float x[3], float v[3]) { if (x) { root_to_world_v3(data, index, x, data->X[index]); } if (v) { root_to_world_v3(data, index, v, data->V[index]); } } void BPH_mass_spring_get_position(struct Implicit_Data *data, int index, float x[3]) { root_to_world_v3(data, index, x, data->X[index]); } void BPH_mass_spring_get_velocity(struct Implicit_Data *data, int index, float v[3]) { root_to_world_v3(data, index, v, data->V[index]); } void BPH_mass_spring_get_new_position(struct Implicit_Data *data, int index, float x[3]) { root_to_world_v3(data, index, x, data->Xnew[index]); } void BPH_mass_spring_set_new_position(struct Implicit_Data *data, int index, const float x[3]) { world_to_root_v3(data, index, data->Xnew[index], x); } void BPH_mass_spring_get_new_velocity(struct Implicit_Data *data, int index, float v[3]) { root_to_world_v3(data, index, v, data->Vnew[index]); } void BPH_mass_spring_set_new_velocity(struct Implicit_Data *data, int index, const float v[3]) { world_to_root_v3(data, index, data->Vnew[index], v); } /* -------------------------------- */ static int BPH_mass_spring_add_block(Implicit_Data *data, int v1, int v2) { int s = data->M[0].vcount + data->num_blocks; /* index from array start */ BLI_assert(s < data->M[0].vcount + data->M[0].scount); ++data->num_blocks; /* tfm and S don't have spring entries (diagonal blocks only) */ init_fmatrix(data->bigI + s, v1, v2); init_fmatrix(data->M + s, v1, v2); init_fmatrix(data->dFdX + s, v1, v2); init_fmatrix(data->dFdV + s, v1, v2); init_fmatrix(data->A + s, v1, v2); init_fmatrix(data->P + s, v1, v2); init_fmatrix(data->Pinv + s, v1, v2); return s; } void BPH_mass_spring_clear_constraints(Implicit_Data *data) { int i, numverts = data->S[0].vcount; for (i = 0; i < numverts; i++) { unit_m3(data->S[i].m); zero_v3(data->z[i]); } } void BPH_mass_spring_add_constraint_ndof0(Implicit_Data *data, int index, const float dV[3]) { zero_m3(data->S[index].m); world_to_root_v3(data, index, data->z[index], dV); } void BPH_mass_spring_add_constraint_ndof1( Implicit_Data *data, int index, const float c1[3], const float c2[3], const float dV[3]) { float m[3][3], p[3], q[3], u[3], cmat[3][3]; world_to_root_v3(data, index, p, c1); mul_fvectorT_fvector(cmat, p, p); sub_m3_m3m3(m, I, cmat); world_to_root_v3(data, index, q, c2); mul_fvectorT_fvector(cmat, q, q); sub_m3_m3m3(m, m, cmat); /* XXX not sure but multiplication should work here */ copy_m3_m3(data->S[index].m, m); // mul_m3_m3m3(data->S[index].m, data->S[index].m, m); world_to_root_v3(data, index, u, dV); add_v3_v3(data->z[index], u); } void BPH_mass_spring_add_constraint_ndof2(Implicit_Data *data, int index, const float c1[3], const float dV[3]) { float m[3][3], p[3], u[3], cmat[3][3]; world_to_root_v3(data, index, p, c1); mul_fvectorT_fvector(cmat, p, p); sub_m3_m3m3(m, I, cmat); copy_m3_m3(data->S[index].m, m); // mul_m3_m3m3(data->S[index].m, data->S[index].m, m); world_to_root_v3(data, index, u, dV); add_v3_v3(data->z[index], u); } void BPH_mass_spring_clear_forces(Implicit_Data *data) { int numverts = data->M[0].vcount; zero_lfvector(data->F, numverts); init_bfmatrix(data->dFdX, ZERO); init_bfmatrix(data->dFdV, ZERO); data->num_blocks = 0; } void BPH_mass_spring_force_reference_frame(Implicit_Data *data, int index, const float acceleration[3], const float omega[3], const float domega_dt[3], float mass) { # ifdef CLOTH_ROOT_FRAME float acc[3], w[3], dwdt[3]; float f[3], dfdx[3][3], dfdv[3][3]; float euler[3], coriolis[3], centrifugal[3], rotvel[3]; float deuler[3][3], dcoriolis[3][3], dcentrifugal[3][3], drotvel[3][3]; world_to_root_v3(data, index, acc, acceleration); world_to_root_v3(data, index, w, omega); world_to_root_v3(data, index, dwdt, domega_dt); cross_v3_v3v3(euler, dwdt, data->X[index]); cross_v3_v3v3(coriolis, w, data->V[index]); mul_v3_fl(coriolis, 2.0f); cross_v3_v3v3(rotvel, w, data->X[index]); cross_v3_v3v3(centrifugal, w, rotvel); sub_v3_v3v3(f, acc, euler); sub_v3_v3(f, coriolis); sub_v3_v3(f, centrifugal); mul_v3_fl(f, mass); /* F = m * a */ cross_v3_identity(deuler, dwdt); cross_v3_identity(dcoriolis, w); mul_m3_fl(dcoriolis, 2.0f); cross_v3_identity(drotvel, w); cross_m3_v3m3(dcentrifugal, w, drotvel); add_m3_m3m3(dfdx, deuler, dcentrifugal); negate_m3(dfdx); mul_m3_fl(dfdx, mass); copy_m3_m3(dfdv, dcoriolis); negate_m3(dfdv); mul_m3_fl(dfdv, mass); add_v3_v3(data->F[index], f); add_m3_m3m3(data->dFdX[index].m, data->dFdX[index].m, dfdx); add_m3_m3m3(data->dFdV[index].m, data->dFdV[index].m, dfdv); # else (void)data; (void)index; (void)acceleration; (void)omega; (void)domega_dt; # endif } void BPH_mass_spring_force_gravity(Implicit_Data *data, int index, float mass, const float g[3]) { /* force = mass * acceleration (in this case: gravity) */ float f[3]; world_to_root_v3(data, index, f, g); mul_v3_fl(f, mass); add_v3_v3(data->F[index], f); } void BPH_mass_spring_force_drag(Implicit_Data *data, float drag) { int i, numverts = data->M[0].vcount; for (i = 0; i < numverts; i++) { float tmp[3][3]; /* NB: uses root space velocity, no need to transform */ madd_v3_v3fl(data->F[i], data->V[i], -drag); copy_m3_m3(tmp, I); mul_m3_fl(tmp, -drag); add_m3_m3m3(data->dFdV[i].m, data->dFdV[i].m, tmp); } } void BPH_mass_spring_force_extern( struct Implicit_Data *data, int i, const float f[3], float dfdx[3][3], float dfdv[3][3]) { float tf[3], tdfdx[3][3], tdfdv[3][3]; world_to_root_v3(data, i, tf, f); world_to_root_m3(data, i, tdfdx, dfdx); world_to_root_m3(data, i, tdfdv, dfdv); add_v3_v3(data->F[i], tf); add_m3_m3m3(data->dFdX[i].m, data->dFdX[i].m, tdfdx); add_m3_m3m3(data->dFdV[i].m, data->dFdV[i].m, tdfdv); } static float calc_nor_area_tri(float nor[3], const float v1[3], const float v2[3], const float v3[3]) { float n1[3], n2[3]; sub_v3_v3v3(n1, v1, v2); sub_v3_v3v3(n2, v2, v3); cross_v3_v3v3(nor, n1, n2); return normalize_v3(nor) / 2.0f; } /* XXX does not support force jacobians yet, since the effector system does not provide them either */ void BPH_mass_spring_force_face_wind( Implicit_Data *data, int v1, int v2, int v3, const float (*winvec)[3]) { const float effector_scale = 0.02f; int vs[3] = {v1, v2, v3}; float win[3], nor[3], area; float factor, base_force; float force[3]; /* calculate face normal and area */ area = calc_nor_area_tri(nor, data->X[v1], data->X[v2], data->X[v3]); /* The force is calculated and split up evenly for each of the three face verts */ factor = effector_scale * area / 3.0f; /* Calculate wind pressure at each vertex by projecting the wind field on the normal. */ for (int i = 0; i < 3; i++) { world_to_root_v3(data, vs[i], win, winvec[vs[i]]); force[i] = dot_v3v3(win, nor); } /* Compute per-vertex force values from local pressures. * From integrating the pressure over the triangle and deriving * equivalent vertex forces, it follows that: * * force[idx] = (sum(pressure) + pressure[idx]) * area / 12 * * Effectively, 1/4 of the pressure acts just on its vertex, * while 3/4 is split evenly over all three. */ mul_v3_fl(force, factor / 4.0f); base_force = force[0] + force[1] + force[2]; /* add pressure to each of the face verts */ madd_v3_v3fl(data->F[v1], nor, base_force + force[0]); madd_v3_v3fl(data->F[v2], nor, base_force + force[1]); madd_v3_v3fl(data->F[v3], nor, base_force + force[2]); } void BPH_mass_spring_force_face_extern( Implicit_Data *data, int v1, int v2, int v3, const float (*forcevec)[3]) { const float effector_scale = 0.02f; int vs[3] = {v1, v2, v3}; float nor[3], area; float factor, base_force[3]; float force[3][3]; /* calculate face normal and area */ area = calc_nor_area_tri(nor, data->X[v1], data->X[v2], data->X[v3]); /* The force is calculated and split up evenly for each of the three face verts */ factor = effector_scale * area / 3.0f; /* Compute common and per-vertex force vectors from the original inputs. */ zero_v3(base_force); for (int i = 0; i < 3; i++) { world_to_root_v3(data, vs[i], force[i], forcevec[vs[i]]); mul_v3_fl(force[i], factor / 4.0f); add_v3_v3(base_force, force[i]); } /* Apply the common and vertex components to all vertices. */ for (int i = 0; i < 3; i++) { add_v3_v3(force[i], base_force); add_v3_v3(data->F[vs[i]], force[i]); } } float BPH_tri_tetra_volume_signed_6x(Implicit_Data *data, int v1, int v2, int v3) { /* The result will be 6x the volume */ return volume_tri_tetrahedron_signed_v3_6x(data->X[v1], data->X[v2], data->X[v3]); } float BPH_tri_area(struct Implicit_Data *data, int v1, int v2, int v3) { float nor[3]; return calc_nor_area_tri(nor, data->X[v1], data->X[v2], data->X[v3]); } void BPH_mass_spring_force_pressure(Implicit_Data *data, int v1, int v2, int v3, float common_pressure, const float *vertex_pressure, const float weights[3]) { float nor[3], area; float factor, base_force; float force[3]; /* calculate face normal and area */ area = calc_nor_area_tri(nor, data->X[v1], data->X[v2], data->X[v3]); /* The force is calculated and split up evenly for each of the three face verts */ factor = area / 3.0f; base_force = common_pressure * factor; /* Compute per-vertex force values from local pressures. * From integrating the pressure over the triangle and deriving * equivalent vertex forces, it follows that: * * force[idx] = (sum(pressure) + pressure[idx]) * area / 12 * * Effectively, 1/4 of the pressure acts just on its vertex, * while 3/4 is split evenly over all three. */ if (vertex_pressure) { copy_v3_fl3(force, vertex_pressure[v1], vertex_pressure[v2], vertex_pressure[v3]); mul_v3_fl(force, factor / 4.0f); base_force += force[0] + force[1] + force[2]; } else { zero_v3(force); } /* add pressure to each of the face verts */ madd_v3_v3fl(data->F[v1], nor, (base_force + force[0]) * weights[0]); madd_v3_v3fl(data->F[v2], nor, (base_force + force[1]) * weights[1]); madd_v3_v3fl(data->F[v3], nor, (base_force + force[2]) * weights[2]); } static void edge_wind_vertex(const float dir[3], float length, float radius, const float wind[3], float f[3], float UNUSED(dfdx[3][3]), float UNUSED(dfdv[3][3])) { const float density = 0.01f; /* XXX arbitrary value, corresponds to effect of air density */ float cos_alpha, sin_alpha, cross_section; float windlen = len_v3(wind); if (windlen == 0.0f) { zero_v3(f); return; } /* angle of wind direction to edge */ cos_alpha = dot_v3v3(wind, dir) / windlen; sin_alpha = sqrtf(1.0f - cos_alpha * cos_alpha); cross_section = radius * ((float)M_PI * radius * sin_alpha + length * cos_alpha); mul_v3_v3fl(f, wind, density * cross_section); } void BPH_mass_spring_force_edge_wind( Implicit_Data *data, int v1, int v2, float radius1, float radius2, const float (*winvec)[3]) { float win[3], dir[3], length; float f[3], dfdx[3][3], dfdv[3][3]; sub_v3_v3v3(dir, data->X[v1], data->X[v2]); length = normalize_v3(dir); world_to_root_v3(data, v1, win, winvec[v1]); edge_wind_vertex(dir, length, radius1, win, f, dfdx, dfdv); add_v3_v3(data->F[v1], f); world_to_root_v3(data, v2, win, winvec[v2]); edge_wind_vertex(dir, length, radius2, win, f, dfdx, dfdv); add_v3_v3(data->F[v2], f); } void BPH_mass_spring_force_vertex_wind(Implicit_Data *data, int v, float UNUSED(radius), const float (*winvec)[3]) { const float density = 0.01f; /* XXX arbitrary value, corresponds to effect of air density */ float wind[3]; float f[3]; world_to_root_v3(data, v, wind, winvec[v]); mul_v3_v3fl(f, wind, density); add_v3_v3(data->F[v], f); } BLI_INLINE void dfdx_spring(float to[3][3], const float dir[3], float length, float L, float k) { // dir is unit length direction, rest is spring's restlength, k is spring constant. // return ( (I-outerprod(dir, dir))*Min(1.0f, rest/length) - I) * -k; outerproduct(to, dir, dir); sub_m3_m3m3(to, I, to); mul_m3_fl(to, (L / length)); sub_m3_m3m3(to, to, I); mul_m3_fl(to, k); } /* unused */ # if 0 BLI_INLINE void dfdx_damp(float to[3][3], const float dir[3], float length, const float vel[3], float rest, float damping) { // inner spring damping vel is the relative velocity of the endpoints. // return (I-outerprod(dir, dir)) * (-damping * -(dot(dir, vel)/Max(length, rest))); mul_fvectorT_fvector(to, dir, dir); sub_fmatrix_fmatrix(to, I, to); mul_fmatrix_S(to, (-damping * -(dot_v3v3(dir, vel) / MAX2(length, rest)))); } # endif BLI_INLINE void dfdv_damp(float to[3][3], const float dir[3], float damping) { // derivative of force wrt velocity outerproduct(to, dir, dir); mul_m3_fl(to, -damping); } BLI_INLINE float fb(float length, float L) { float x = length / L; float xx = x * x; float xxx = xx * x; float xxxx = xxx * x; return (-11.541f * xxxx + 34.193f * xxx - 39.083f * xx + 23.116f * x - 9.713f); } BLI_INLINE float fbderiv(float length, float L) { float x = length / L; float xx = x * x; float xxx = xx * x; return (-46.164f * xxx + 102.579f * xx - 78.166f * x + 23.116f); } BLI_INLINE float fbstar(float length, float L, float kb, float cb) { float tempfb_fl = kb * fb(length, L); float fbstar_fl = cb * (length - L); if (tempfb_fl < fbstar_fl) { return fbstar_fl; } else { return tempfb_fl; } } // function to calculae bending spring force (taken from Choi & Co) BLI_INLINE float fbstar_jacobi(float length, float L, float kb, float cb) { float tempfb_fl = kb * fb(length, L); float fbstar_fl = cb * (length - L); if (tempfb_fl < fbstar_fl) { return -cb; } else { return -kb * fbderiv(length, L); } } /* calculate elonglation */ BLI_INLINE bool spring_length(Implicit_Data *data, int i, int j, float r_extent[3], float r_dir[3], float *r_length, float r_vel[3]) { sub_v3_v3v3(r_extent, data->X[j], data->X[i]); sub_v3_v3v3(r_vel, data->V[j], data->V[i]); *r_length = len_v3(r_extent); if (*r_length > ALMOST_ZERO) { # if 0 if (length > L) { if ((clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED) && (((length - L) * 100.0f / L) > clmd->sim_parms->maxspringlen)) { // cut spring! s->flags |= CSPRING_FLAG_DEACTIVATE; return false; } } # endif mul_v3_v3fl(r_dir, r_extent, 1.0f / (*r_length)); } else { zero_v3(r_dir); } return true; } BLI_INLINE void apply_spring( Implicit_Data *data, int i, int j, const float f[3], float dfdx[3][3], float dfdv[3][3]) { int block_ij = BPH_mass_spring_add_block(data, i, j); add_v3_v3(data->F[i], f); sub_v3_v3(data->F[j], f); add_m3_m3m3(data->dFdX[i].m, data->dFdX[i].m, dfdx); add_m3_m3m3(data->dFdX[j].m, data->dFdX[j].m, dfdx); sub_m3_m3m3(data->dFdX[block_ij].m, data->dFdX[block_ij].m, dfdx); add_m3_m3m3(data->dFdV[i].m, data->dFdV[i].m, dfdv); add_m3_m3m3(data->dFdV[j].m, data->dFdV[j].m, dfdv); sub_m3_m3m3(data->dFdV[block_ij].m, data->dFdV[block_ij].m, dfdv); } bool BPH_mass_spring_force_spring_linear(Implicit_Data *data, int i, int j, float restlen, float stiffness_tension, float damping_tension, float stiffness_compression, float damping_compression, bool resist_compress, bool new_compress, float clamp_force) { float extent[3], length, dir[3], vel[3]; float f[3], dfdx[3][3], dfdv[3][3]; float damping = 0; // calculate elonglation spring_length(data, i, j, extent, dir, &length, vel); /* This code computes not only the force, but also its derivative. * Zero derivative effectively disables the spring for the implicit solver. * Thus length > restlen makes cloth unconstrained at the start of simulation. */ if ((length >= restlen && length > 0) || resist_compress) { float stretch_force; damping = damping_tension; stretch_force = stiffness_tension * (length - restlen); if (clamp_force > 0.0f && stretch_force > clamp_force) { stretch_force = clamp_force; } mul_v3_v3fl(f, dir, stretch_force); dfdx_spring(dfdx, dir, length, restlen, stiffness_tension); } else if (new_compress) { /* This is based on the Choi and Ko bending model, * which works surprisingly well for compression. */ float kb = stiffness_compression; float cb = kb; /* cb equal to kb seems to work, but a factor can be added if necessary */ damping = damping_compression; mul_v3_v3fl(f, dir, fbstar(length, restlen, kb, cb)); outerproduct(dfdx, dir, dir); mul_m3_fl(dfdx, fbstar_jacobi(length, restlen, kb, cb)); } else { return false; } madd_v3_v3fl(f, dir, damping * dot_v3v3(vel, dir)); dfdv_damp(dfdv, dir, damping); apply_spring(data, i, j, f, dfdx, dfdv); return true; } /* See "Stable but Responsive Cloth" (Choi, Ko 2005) */ bool BPH_mass_spring_force_spring_bending( Implicit_Data *data, int i, int j, float restlen, float kb, float cb) { float extent[3], length, dir[3], vel[3]; // calculate elonglation spring_length(data, i, j, extent, dir, &length, vel); if (length < restlen) { float f[3], dfdx[3][3], dfdv[3][3]; mul_v3_v3fl(f, dir, fbstar(length, restlen, kb, cb)); outerproduct(dfdx, dir, dir); mul_m3_fl(dfdx, fbstar_jacobi(length, restlen, kb, cb)); /* XXX damping not supported */ zero_m3(dfdv); apply_spring(data, i, j, f, dfdx, dfdv); return true; } else { return false; } } BLI_INLINE void poly_avg(lfVector *data, int *inds, int len, float r_avg[3]) { float fact = 1.0f / (float)len; zero_v3(r_avg); for (int i = 0; i < len; i++) { madd_v3_v3fl(r_avg, data[inds[i]], fact); } } BLI_INLINE void poly_norm(lfVector *data, int i, int j, int *inds, int len, float r_dir[3]) { float mid[3]; poly_avg(data, inds, len, mid); normal_tri_v3(r_dir, data[i], data[j], mid); } BLI_INLINE void edge_avg(lfVector *data, int i, int j, float r_avg[3]) { r_avg[0] = (data[i][0] + data[j][0]) * 0.5f; r_avg[1] = (data[i][1] + data[j][1]) * 0.5f; r_avg[2] = (data[i][2] + data[j][2]) * 0.5f; } BLI_INLINE void edge_norm(lfVector *data, int i, int j, float r_dir[3]) { sub_v3_v3v3(r_dir, data[i], data[j]); normalize_v3(r_dir); } BLI_INLINE float bend_angle(float dir_a[3], float dir_b[3], float dir_e[3]) { float cos, sin; float tmp[3]; cos = dot_v3v3(dir_a, dir_b); cross_v3_v3v3(tmp, dir_a, dir_b); sin = dot_v3v3(tmp, dir_e); return atan2f(sin, cos); } BLI_INLINE void spring_angle(Implicit_Data *data, int i, int j, int *i_a, int *i_b, int len_a, int len_b, float r_dir_a[3], float r_dir_b[3], float *r_angle, float r_vel_a[3], float r_vel_b[3]) { float dir_e[3], vel_e[3]; poly_norm(data->X, j, i, i_a, len_a, r_dir_a); poly_norm(data->X, i, j, i_b, len_b, r_dir_b); edge_norm(data->X, i, j, dir_e); *r_angle = bend_angle(r_dir_a, r_dir_b, dir_e); poly_avg(data->V, i_a, len_a, r_vel_a); poly_avg(data->V, i_b, len_b, r_vel_b); edge_avg(data->V, i, j, vel_e); sub_v3_v3(r_vel_a, vel_e); sub_v3_v3(r_vel_b, vel_e); } /* Angular springs roughly based on the bending model proposed by Baraff and Witkin in "Large Steps * in Cloth Simulation". */ bool BPH_mass_spring_force_spring_angular(Implicit_Data *data, int i, int j, int *i_a, int *i_b, int len_a, int len_b, float restang, float stiffness, float damping) { float angle, dir_a[3], dir_b[3], vel_a[3], vel_b[3]; float f_a[3], f_b[3], f_e[3]; float force; int x; spring_angle(data, i, j, i_a, i_b, len_a, len_b, dir_a, dir_b, &angle, vel_a, vel_b); /* spring force */ force = stiffness * (angle - restang); /* damping force */ force += -damping * (dot_v3v3(vel_a, dir_a) + dot_v3v3(vel_b, dir_b)); mul_v3_v3fl(f_a, dir_a, force / len_a); mul_v3_v3fl(f_b, dir_b, force / len_b); for (x = 0; x < len_a; x++) { add_v3_v3(data->F[i_a[x]], f_a); } for (x = 0; x < len_b; x++) { add_v3_v3(data->F[i_b[x]], f_b); } mul_v3_v3fl(f_a, dir_a, force * 0.5f); mul_v3_v3fl(f_b, dir_b, force * 0.5f); add_v3_v3v3(f_e, f_a, f_b); sub_v3_v3(data->F[i], f_e); sub_v3_v3(data->F[j], f_e); return true; } /* Jacobian of a direction vector. * Basically the part of the differential orthogonal to the direction, * inversely proportional to the length of the edge. * * dD_ij/dx_i = -dD_ij/dx_j = (D_ij * D_ij^T - I) / len_ij */ BLI_INLINE void spring_grad_dir( Implicit_Data *data, int i, int j, float edge[3], float dir[3], float grad_dir[3][3]) { float length; sub_v3_v3v3(edge, data->X[j], data->X[i]); length = normalize_v3_v3(dir, edge); if (length > ALMOST_ZERO) { outerproduct(grad_dir, dir, dir); sub_m3_m3m3(grad_dir, I, grad_dir); mul_m3_fl(grad_dir, 1.0f / length); } else { zero_m3(grad_dir); } } BLI_INLINE void spring_hairbend_forces(Implicit_Data *data, int i, int j, int k, const float goal[3], float stiffness, float damping, int q, const float dx[3], const float dv[3], float r_f[3]) { float edge_ij[3], dir_ij[3]; float edge_jk[3], dir_jk[3]; float vel_ij[3], vel_jk[3], vel_ortho[3]; float f_bend[3], f_damp[3]; float fk[3]; float dist[3]; zero_v3(fk); sub_v3_v3v3(edge_ij, data->X[j], data->X[i]); if (q == i) { sub_v3_v3(edge_ij, dx); } if (q == j) { add_v3_v3(edge_ij, dx); } normalize_v3_v3(dir_ij, edge_ij); sub_v3_v3v3(edge_jk, data->X[k], data->X[j]); if (q == j) { sub_v3_v3(edge_jk, dx); } if (q == k) { add_v3_v3(edge_jk, dx); } normalize_v3_v3(dir_jk, edge_jk); sub_v3_v3v3(vel_ij, data->V[j], data->V[i]); if (q == i) { sub_v3_v3(vel_ij, dv); } if (q == j) { add_v3_v3(vel_ij, dv); } sub_v3_v3v3(vel_jk, data->V[k], data->V[j]); if (q == j) { sub_v3_v3(vel_jk, dv); } if (q == k) { add_v3_v3(vel_jk, dv); } /* bending force */ sub_v3_v3v3(dist, goal, edge_jk); mul_v3_v3fl(f_bend, dist, stiffness); add_v3_v3(fk, f_bend); /* damping force */ madd_v3_v3v3fl(vel_ortho, vel_jk, dir_jk, -dot_v3v3(vel_jk, dir_jk)); mul_v3_v3fl(f_damp, vel_ortho, damping); sub_v3_v3(fk, f_damp); copy_v3_v3(r_f, fk); } /* Finite Differences method for estimating the jacobian of the force */ BLI_INLINE void spring_hairbend_estimate_dfdx(Implicit_Data *data, int i, int j, int k, const float goal[3], float stiffness, float damping, int q, float dfdx[3][3]) { const float delta = 0.00001f; // TODO find a good heuristic for this float dvec_null[3][3], dvec_pos[3][3], dvec_neg[3][3]; float f[3]; int a, b; zero_m3(dvec_null); unit_m3(dvec_pos); mul_m3_fl(dvec_pos, delta * 0.5f); copy_m3_m3(dvec_neg, dvec_pos); negate_m3(dvec_neg); /* XXX TODO offset targets to account for position dependency */ for (a = 0; a < 3; a++) { spring_hairbend_forces( data, i, j, k, goal, stiffness, damping, q, dvec_pos[a], dvec_null[a], f); copy_v3_v3(dfdx[a], f); spring_hairbend_forces( data, i, j, k, goal, stiffness, damping, q, dvec_neg[a], dvec_null[a], f); sub_v3_v3(dfdx[a], f); for (b = 0; b < 3; b++) { dfdx[a][b] /= delta; } } } /* Finite Differences method for estimating the jacobian of the force */ BLI_INLINE void spring_hairbend_estimate_dfdv(Implicit_Data *data, int i, int j, int k, const float goal[3], float stiffness, float damping, int q, float dfdv[3][3]) { const float delta = 0.00001f; // TODO find a good heuristic for this float dvec_null[3][3], dvec_pos[3][3], dvec_neg[3][3]; float f[3]; int a, b; zero_m3(dvec_null); unit_m3(dvec_pos); mul_m3_fl(dvec_pos, delta * 0.5f); copy_m3_m3(dvec_neg, dvec_pos); negate_m3(dvec_neg); /* XXX TODO offset targets to account for position dependency */ for (a = 0; a < 3; a++) { spring_hairbend_forces( data, i, j, k, goal, stiffness, damping, q, dvec_null[a], dvec_pos[a], f); copy_v3_v3(dfdv[a], f); spring_hairbend_forces( data, i, j, k, goal, stiffness, damping, q, dvec_null[a], dvec_neg[a], f); sub_v3_v3(dfdv[a], f); for (b = 0; b < 3; b++) { dfdv[a][b] /= delta; } } } /* Angular spring that pulls the vertex toward the local target * See "Artistic Simulation of Curly Hair" (Pixar technical memo #12-03a) */ bool BPH_mass_spring_force_spring_bending_hair(Implicit_Data *data, int i, int j, int k, const float target[3], float stiffness, float damping) { float goal[3]; float fj[3], fk[3]; float dfj_dxi[3][3], dfj_dxj[3][3], dfk_dxi[3][3], dfk_dxj[3][3], dfk_dxk[3][3]; float dfj_dvi[3][3], dfj_dvj[3][3], dfk_dvi[3][3], dfk_dvj[3][3], dfk_dvk[3][3]; const float vecnull[3] = {0.0f, 0.0f, 0.0f}; int block_ij = BPH_mass_spring_add_block(data, i, j); int block_jk = BPH_mass_spring_add_block(data, j, k); int block_ik = BPH_mass_spring_add_block(data, i, k); world_to_root_v3(data, j, goal, target); spring_hairbend_forces(data, i, j, k, goal, stiffness, damping, k, vecnull, vecnull, fk); negate_v3_v3(fj, fk); /* counterforce */ spring_hairbend_estimate_dfdx(data, i, j, k, goal, stiffness, damping, i, dfk_dxi); spring_hairbend_estimate_dfdx(data, i, j, k, goal, stiffness, damping, j, dfk_dxj); spring_hairbend_estimate_dfdx(data, i, j, k, goal, stiffness, damping, k, dfk_dxk); copy_m3_m3(dfj_dxi, dfk_dxi); negate_m3(dfj_dxi); copy_m3_m3(dfj_dxj, dfk_dxj); negate_m3(dfj_dxj); spring_hairbend_estimate_dfdv(data, i, j, k, goal, stiffness, damping, i, dfk_dvi); spring_hairbend_estimate_dfdv(data, i, j, k, goal, stiffness, damping, j, dfk_dvj); spring_hairbend_estimate_dfdv(data, i, j, k, goal, stiffness, damping, k, dfk_dvk); copy_m3_m3(dfj_dvi, dfk_dvi); negate_m3(dfj_dvi); copy_m3_m3(dfj_dvj, dfk_dvj); negate_m3(dfj_dvj); /* add forces and jacobians to the solver data */ add_v3_v3(data->F[j], fj); add_v3_v3(data->F[k], fk); add_m3_m3m3(data->dFdX[j].m, data->dFdX[j].m, dfj_dxj); add_m3_m3m3(data->dFdX[k].m, data->dFdX[k].m, dfk_dxk); add_m3_m3m3(data->dFdX[block_ij].m, data->dFdX[block_ij].m, dfj_dxi); add_m3_m3m3(data->dFdX[block_jk].m, data->dFdX[block_jk].m, dfk_dxj); add_m3_m3m3(data->dFdX[block_ik].m, data->dFdX[block_ik].m, dfk_dxi); add_m3_m3m3(data->dFdV[j].m, data->dFdV[j].m, dfj_dvj); add_m3_m3m3(data->dFdV[k].m, data->dFdV[k].m, dfk_dvk); add_m3_m3m3(data->dFdV[block_ij].m, data->dFdV[block_ij].m, dfj_dvi); add_m3_m3m3(data->dFdV[block_jk].m, data->dFdV[block_jk].m, dfk_dvj); add_m3_m3m3(data->dFdV[block_ik].m, data->dFdV[block_ik].m, dfk_dvi); /* XXX analytical calculation of derivatives below is incorrect. * This proved to be difficult, but for now just using the finite difference method for * estimating the jacobians should be sufficient. */ # if 0 float edge_ij[3], dir_ij[3], grad_dir_ij[3][3]; float edge_jk[3], dir_jk[3], grad_dir_jk[3][3]; float dist[3], vel_jk[3], vel_jk_ortho[3], projvel[3]; float target[3]; float tmp[3][3]; float fi[3], fj[3], fk[3]; float dfi_dxi[3][3], dfj_dxi[3][3], dfj_dxj[3][3], dfk_dxi[3][3], dfk_dxj[3][3], dfk_dxk[3][3]; float dfdvi[3][3]; // TESTING damping = 0.0f; zero_v3(fi); zero_v3(fj); zero_v3(fk); zero_m3(dfi_dxi); zero_m3(dfj_dxi); zero_m3(dfk_dxi); zero_m3(dfk_dxj); zero_m3(dfk_dxk); /* jacobian of direction vectors */ spring_grad_dir(data, i, j, edge_ij, dir_ij, grad_dir_ij); spring_grad_dir(data, j, k, edge_jk, dir_jk, grad_dir_jk); sub_v3_v3v3(vel_jk, data->V[k], data->V[j]); /* bending force */ mul_v3_v3fl(target, dir_ij, restlen); sub_v3_v3v3(dist, target, edge_jk); mul_v3_v3fl(fk, dist, stiffness); /* damping force */ madd_v3_v3v3fl(vel_jk_ortho, vel_jk, dir_jk, -dot_v3v3(vel_jk, dir_jk)); madd_v3_v3fl(fk, vel_jk_ortho, damping); /* XXX this only holds true as long as we assume straight rest shape! * eventually will become a bit more involved since the opposite segment * gets its own target, under condition of having equal torque on both sides. */ copy_v3_v3(fi, fk); /* counterforce on the middle point */ sub_v3_v3(fj, fi); sub_v3_v3(fj, fk); /* === derivatives === */ madd_m3_m3fl(dfk_dxi, grad_dir_ij, stiffness * restlen); madd_m3_m3fl(dfk_dxj, grad_dir_ij, -stiffness * restlen); madd_m3_m3fl(dfk_dxj, I, stiffness); madd_m3_m3fl(dfk_dxk, I, -stiffness); copy_m3_m3(dfi_dxi, dfk_dxk); negate_m3(dfi_dxi); /* dfj_dfi == dfi_dfj due to symmetry, * dfi_dfj == dfk_dfj due to fi == fk * XXX see comment above on future bent rest shapes */ copy_m3_m3(dfj_dxi, dfk_dxj); /* dfj_dxj == -(dfi_dxj + dfk_dxj) due to fj == -(fi + fk) */ sub_m3_m3m3(dfj_dxj, dfj_dxj, dfj_dxi); sub_m3_m3m3(dfj_dxj, dfj_dxj, dfk_dxj); /* add forces and jacobians to the solver data */ add_v3_v3(data->F[i], fi); add_v3_v3(data->F[j], fj); add_v3_v3(data->F[k], fk); add_m3_m3m3(data->dFdX[i].m, data->dFdX[i].m, dfi_dxi); add_m3_m3m3(data->dFdX[j].m, data->dFdX[j].m, dfj_dxj); add_m3_m3m3(data->dFdX[k].m, data->dFdX[k].m, dfk_dxk); add_m3_m3m3(data->dFdX[block_ij].m, data->dFdX[block_ij].m, dfj_dxi); add_m3_m3m3(data->dFdX[block_jk].m, data->dFdX[block_jk].m, dfk_dxj); add_m3_m3m3(data->dFdX[block_ik].m, data->dFdX[block_ik].m, dfk_dxi); # endif return true; } bool BPH_mass_spring_force_spring_goal(Implicit_Data *data, int i, const float goal_x[3], const float goal_v[3], float stiffness, float damping) { float root_goal_x[3], root_goal_v[3], extent[3], length, dir[3], vel[3]; float f[3], dfdx[3][3], dfdv[3][3]; /* goal is in world space */ world_to_root_v3(data, i, root_goal_x, goal_x); world_to_root_v3(data, i, root_goal_v, goal_v); sub_v3_v3v3(extent, root_goal_x, data->X[i]); sub_v3_v3v3(vel, root_goal_v, data->V[i]); length = normalize_v3_v3(dir, extent); if (length > ALMOST_ZERO) { mul_v3_v3fl(f, dir, stiffness * length); // Ascher & Boxman, p.21: Damping only during elonglation // something wrong with it... madd_v3_v3fl(f, dir, damping * dot_v3v3(vel, dir)); dfdx_spring(dfdx, dir, length, 0.0f, stiffness); dfdv_damp(dfdv, dir, damping); add_v3_v3(data->F[i], f); add_m3_m3m3(data->dFdX[i].m, data->dFdX[i].m, dfdx); add_m3_m3m3(data->dFdV[i].m, data->dFdV[i].m, dfdv); return true; } else { return false; } } #endif /* IMPLICIT_SOLVER_BLENDER */
interpolate_op.h
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <algorithm> #include <string> #include <vector> #include "paddle/fluid/framework/op_registry.h" #include "paddle/phi/core/hostdevice.h" #include "paddle/phi/kernels/funcs/math_function.h" namespace paddle { namespace operators { template <typename T, size_t D, int MajorType = Eigen::RowMajor, typename IndexType = Eigen::DenseIndex> using EigenTensor = framework::EigenTensor<T, D, MajorType, IndexType>; using Tensor = framework::Tensor; using DataLayout = framework::DataLayout; inline std::vector<int> get_new_shape( const std::vector<const Tensor*>& list_new_shape_tensor) { // get tensor from std::vector<int> vec_new_shape; for (size_t i = 0; i < list_new_shape_tensor.size(); ++i) { auto tensor = list_new_shape_tensor[i]; PADDLE_ENFORCE_EQ(tensor->dims(), phi::make_ddim({1}), platform::errors::InvalidArgument( "The shape of dimension tensor should be [1]," "but received d%.", tensor->dims())); if (platform::is_gpu_place(tensor->place())) { framework::Tensor temp; paddle::framework::TensorCopySync(*tensor, platform::CPUPlace(), &temp); vec_new_shape.push_back(static_cast<int32_t>(*temp.data<int32_t>())); } else { vec_new_shape.push_back(static_cast<int32_t>(*tensor->data<int32_t>())); } } return vec_new_shape; } template <typename T> inline std::vector<T> get_new_data_from_tensor(const Tensor* new_data_tensor) { std::vector<T> vec_new_data; auto* new_data = new_data_tensor->data<T>(); framework::Tensor cpu_starts_tensor; if (platform::is_gpu_place(new_data_tensor->place())) { paddle::framework::TensorCopySync(*new_data_tensor, platform::CPUPlace(), &cpu_starts_tensor); new_data = cpu_starts_tensor.data<T>(); } vec_new_data = std::vector<T>(new_data, new_data + new_data_tensor->numel()); return vec_new_data; } inline void ExtractNCDWH(const framework::DDim& dims, const DataLayout& data_layout, int* N, int* C, int* D, int* H, int* W) { *N = dims[0]; if (dims.size() == 3) { *C = data_layout == DataLayout::kNCHW ? dims[1] : dims[2]; *D = 1; *H = 1; *W = data_layout == DataLayout::kNCHW ? dims[2] : dims[1]; } else if (dims.size() == 4) { *C = data_layout == DataLayout::kNCHW ? dims[1] : dims[3]; *D = 1; *H = data_layout == DataLayout::kNCHW ? dims[2] : dims[1]; *W = data_layout == DataLayout::kNCHW ? dims[3] : dims[2]; } else { *C = data_layout == DataLayout::kNCHW ? dims[1] : dims[4]; *D = data_layout == DataLayout::kNCHW ? dims[2] : dims[1]; *H = data_layout == DataLayout::kNCHW ? dims[3] : dims[2]; *W = data_layout == DataLayout::kNCHW ? dims[4] : dims[3]; } } template <typename T> static void NearestNeighborInterpolate(const Tensor& input, Tensor* output, const float ratio_h, const float ratio_w, const int n, const int c, const int out_h, const int out_w, const bool align_corners, const DataLayout& data_layout) { auto input_t = EigenTensor<T, 4>::From(input); auto output_t = EigenTensor<T, 4>::From(*output); for (int k = 0; k < out_h; k++) { // loop for images int in_k = (align_corners) ? static_cast<int>(ratio_h * k + 0.5) : static_cast<int>(ratio_h * k); for (int l = 0; l < out_w; l++) { int in_l = (align_corners) ? static_cast<int>(ratio_w * l + 0.5) : static_cast<int>(ratio_w * l); for (int i = 0; i < n; i++) { // loop for batches for (int j = 0; j < c; j++) { // loop for channels if (data_layout == DataLayout::kNCHW) { output_t(i, j, k, l) = input_t(i, j, in_k, in_l); } else { output_t(i, k, l, j) = input_t(i, in_k, in_l, j); } } } } } } template <typename T> static void LinearInterpolation(const Tensor& input, Tensor* output, const float ratio_w, const int in_w, const int n, const int c, const int out_w, const bool align_corners, const bool align_mode, const DataLayout data_layout) { auto input_t = EigenTensor<T, 3>::From(input); auto output_t = EigenTensor<T, 3>::From(*output); bool align_flag = (align_mode == 0 && !align_corners); std::vector<int> vx_w, vx_e; std::vector<float> vd_w, vd_e; vx_w.reserve(out_w); vx_e.reserve(out_w); vd_w.reserve(out_w); vd_e.reserve(out_w); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int l = 0; l < out_w; l++) { int x_w = align_flag ? static_cast<int>(ratio_w * (l + 0.5) - 0.5) : static_cast<int>(ratio_w * l); x_w = (x_w > 0) ? x_w : 0; // w int x_e = (x_w < (in_w - 1)) ? (x_w + 1) : x_w; // w_id float idx_src_x = ratio_w * (l + 0.5) - 0.5; idx_src_x = (idx_src_x > 0) ? idx_src_x : 0; float d_w = align_flag ? idx_src_x - x_w : ratio_w * l - x_w; // w1lambda float d_e = 1.f - d_w; // w2lambda { vx_w[l] = x_w; vx_e[l] = x_e; vd_w[l] = d_w; vd_e[l] = d_e; } } #ifdef PADDLE_WITH_MKLML #pragma omp parallel for collapse(3) #endif for (int i = 0; i < n; i++) { // loop for batches for (int j = 0; j < c; j++) { // loop for channels for (int l = 0; l < out_w; l++) { // linear interpolation T out_t; if (data_layout == DataLayout::kNCHW) { out_t = input_t(i, j, vx_w[l]) * vd_e[l] + input_t(i, j, vx_e[l]) * vd_w[l]; output_t(i, j, l) = out_t; } else { out_t = input_t(i, vx_w[l], j) * vd_e[l] + input_t(i, vx_e[l], j) * vd_w[l]; output_t(i, l, j) = out_t; } } } } } template <typename T> static void LinearInterpolationGrad(const Tensor& output_grad, Tensor* input_grad, const float ratio_w, const int in_w, const int n, const int c, const int out_w, const bool align_corners, const int align_mode, const DataLayout data_layout) { auto input_grad_t = EigenTensor<T, 3>::From(*input_grad); auto output_grad_t = EigenTensor<T, 3>::From(output_grad); bool align_flag = (align_mode == 0 && !align_corners); for (int l = 0; l < out_w; l++) { int x_w = align_flag ? static_cast<int>(ratio_w * (l + 0.5) - 0.5) : static_cast<int>(ratio_w * l); x_w = (x_w > 0) ? x_w : 0; // w int x_e = (x_w < (in_w - 1)) ? (x_w + 1) : x_w; // w_id float idx_src_x = ratio_w * (l + 0.5) - 0.5; idx_src_x = (idx_src_x > 0) ? idx_src_x : 0; float d_w = align_flag ? idx_src_x - x_w : ratio_w * l - x_w; // w1lambda float d_e = 1.f - d_w; // w2lambda for (int i = 0; i < n; i++) { // loop for batches for (int j = 0; j < c; j++) { // loop for channels // linear interpolation grad if (data_layout == DataLayout::kNCHW) { const T grad = output_grad_t(i, j, l); input_grad_t(i, j, x_w) += static_cast<T>(grad * d_e); input_grad_t(i, j, x_e) += static_cast<T>(grad * d_w); } else { const T grad = output_grad_t(i, l, j); input_grad_t(i, x_w, j) += static_cast<T>(grad * d_e); input_grad_t(i, x_e, j) += static_cast<T>(grad * d_w); } } } } } template <typename T> static void BilinearInterpolation(const Tensor& input, Tensor* output, const float ratio_h, const float ratio_w, const int in_h, const int in_w, const int n, const int c, const int out_h, const int out_w, const bool align_corners, const bool align_mode, const DataLayout data_layout) { auto input_t = EigenTensor<T, 4>::From(input); auto output_t = EigenTensor<T, 4>::From(*output); bool align_flag = (align_mode == 0 && !align_corners); std::vector<int> vy_n, vy_s; std::vector<float> vd_n, vd_s; vy_n.reserve(out_h); vy_s.reserve(out_h); vd_n.reserve(out_h); vd_s.reserve(out_h); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int k = 0; k < out_h; k++) { int y_n = align_flag ? static_cast<int>(ratio_h * (k + 0.5) - 0.5) : static_cast<int>(ratio_h * k); y_n = (y_n > 0) ? y_n : 0; int y_s = (y_n + 1) < (in_h - 1) ? (y_n + 1) : (in_h - 1); float idx_src_y = ratio_h * (k + 0.5) - 0.5; idx_src_y = (idx_src_y > 0) ? idx_src_y : 0; float d_n = align_flag ? idx_src_y - y_n : ratio_h * k - y_n; float d_s = 1.f - d_n; { vy_n[k] = y_n; vy_s[k] = y_s; vd_n[k] = d_n; vd_s[k] = d_s; } } std::vector<int> vx_w, vx_e; std::vector<float> vd_w, vd_e; vx_w.reserve(out_w); vx_e.reserve(out_w); vd_w.reserve(out_w); vd_e.reserve(out_w); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int l = 0; l < out_w; l++) { int x_w = (align_mode == 0 && !align_corners) ? static_cast<int>(ratio_w * (l + 0.5) - 0.5) : static_cast<int>(ratio_w * l); x_w = (x_w > 0) ? x_w : 0; int x_e = (x_w + 1) < (in_w - 1) ? (x_w + 1) : (in_w - 1); float idx_src_x = ratio_w * (l + 0.5) - 0.5; idx_src_x = (idx_src_x > 0) ? idx_src_x : 0; float d_w = align_flag ? idx_src_x - x_w : ratio_w * l - x_w; float d_e = 1.f - d_w; { vx_w[l] = x_w; vx_e[l] = x_e; vd_w[l] = d_w; vd_e[l] = d_e; } } #ifdef PADDLE_WITH_MKLML #pragma omp parallel for collapse(4) #endif for (int i = 0; i < n; i++) { // loop for batches for (int j = 0; j < c; j++) { // loop for channels for (int k = 0; k < out_h; k++) { // loop for images for (int l = 0; l < out_w; l++) { // bilinear interpolation T out_t; if (data_layout == DataLayout::kNCHW) { out_t = input_t(i, j, vy_n[k], vx_w[l]) * vd_s[k] * vd_e[l] + input_t(i, j, vy_s[k], vx_w[l]) * vd_n[k] * vd_e[l] + input_t(i, j, vy_n[k], vx_e[l]) * vd_s[k] * vd_w[l] + input_t(i, j, vy_s[k], vx_e[l]) * vd_n[k] * vd_w[l]; output_t(i, j, k, l) = out_t; } else { out_t = input_t(i, vy_n[k], vx_w[l], j) * vd_s[k] * vd_e[l] + input_t(i, vy_s[k], vx_w[l], j) * vd_n[k] * vd_e[l] + input_t(i, vy_n[k], vx_e[l], j) * vd_s[k] * vd_w[l] + input_t(i, vy_s[k], vx_e[l], j) * vd_n[k] * vd_w[l]; output_t(i, k, l, j) = out_t; } } } } } } template <typename T> static void TrilinearInterpolation( const Tensor& input, Tensor* output, const float ratio_d, const float ratio_h, const float ratio_w, const int in_d, const int in_h, const int in_w, const int n, const int c, const int out_d, const int out_h, const int out_w, const bool align_corners, const bool align_mode, const DataLayout& data_layout) { auto input_t = EigenTensor<T, 5>::From(input); auto output_t = EigenTensor<T, 5>::From(*output); bool align_flag = (align_mode == 0 && !align_corners); std::vector<int> vt_f, vt_b; std::vector<float> vd_f, vd_b; vt_f.reserve(out_d); vt_b.reserve(out_d); vd_f.reserve(out_d); vd_b.reserve(out_d); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int j = 0; j < out_d; j++) { int t_f = align_flag ? static_cast<int>(ratio_d * (j + 0.5) - 0.5) : static_cast<int>(ratio_d * j); t_f = (t_f > 0) ? t_f : 0; int t_b = (t_f + 1) < (in_d - 1) ? (t_f + 1) : (in_d - 1); float idx_src_t = ratio_d * (j + 0.5) - 0.5; idx_src_t = (idx_src_t > 0) ? idx_src_t : 0; float d_f = align_flag ? idx_src_t - t_f : ratio_d * j - t_f; float d_b = 1.f - d_f; { vt_f[j] = t_f; vt_b[j] = t_b; vd_f[j] = d_f; vd_b[j] = d_b; } } std::vector<int> vy_n, vy_s; std::vector<float> vd_n, vd_s; vy_n.reserve(out_h); vy_s.reserve(out_h); vd_n.reserve(out_h); vd_s.reserve(out_h); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int k = 0; k < out_h; k++) { int y_n = align_flag ? static_cast<int>(ratio_h * (k + 0.5) - 0.5) : static_cast<int>(ratio_h * k); y_n = (y_n > 0) ? y_n : 0; int y_s = (y_n + 1) < (in_h - 1) ? (y_n + 1) : (in_h - 1); float idx_src_y = ratio_h * (k + 0.5) - 0.5; idx_src_y = (idx_src_y > 0) ? idx_src_y : 0; float d_n = align_flag ? idx_src_y - y_n : ratio_h * k - y_n; float d_s = 1.f - d_n; { vy_n[k] = y_n; vy_s[k] = y_s; vd_n[k] = d_n; vd_s[k] = d_s; } } std::vector<int> vx_w, vx_e; std::vector<float> vd_w, vd_e; vx_w.reserve(out_w); vx_e.reserve(out_w); vd_w.reserve(out_w); vd_e.reserve(out_w); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int l = 0; l < out_w; l++) { int x_w = (align_mode == 0 && !align_corners) ? static_cast<int>(ratio_w * (l + 0.5) - 0.5) : static_cast<int>(ratio_w * l); x_w = (x_w > 0) ? x_w : 0; int x_e = (x_w + 1) < (in_w - 1) ? (x_w + 1) : (in_w - 1); float idx_src_x = ratio_w * (l + 0.5) - 0.5; idx_src_x = (idx_src_x > 0) ? idx_src_x : 0; float d_w = align_flag ? idx_src_x - x_w : ratio_w * l - x_w; float d_e = 1.f - d_w; { vx_w[l] = x_w; vx_e[l] = x_e; vd_w[l] = d_w; vd_e[l] = d_e; } } #ifdef PADDLE_WITH_MKLML #pragma omp parallel for collapse(5) #endif for (int b = 0; b < n; b++) { // loop for batches for (int i = 0; i < c; i++) { // loop for channels for (int j = 0; j < out_d; j++) { // loop for D, H, W for (int k = 0; k < out_h; k++) { for (int l = 0; l < out_w; l++) { // trilinear interpolation if (data_layout == DataLayout::kNCHW) { T out_t = input_t(b, i, vt_f[j], vy_n[k], vx_w[l]) * vd_b[j] * vd_s[k] * vd_e[l] + input_t(b, i, vt_f[j], vy_n[k], vx_e[l]) * vd_b[j] * vd_s[k] * vd_w[l] + input_t(b, i, vt_f[j], vy_s[k], vx_w[l]) * vd_b[j] * vd_n[k] * vd_e[l] + input_t(b, i, vt_f[j], vy_s[k], vx_e[l]) * vd_b[j] * vd_n[k] * vd_w[l] + input_t(b, i, vt_b[j], vy_n[k], vx_w[l]) * vd_f[j] * vd_s[k] * vd_e[l] + input_t(b, i, vt_b[j], vy_n[k], vx_e[l]) * vd_f[j] * vd_s[k] * vd_w[l] + input_t(b, i, vt_b[j], vy_s[k], vx_w[l]) * vd_f[j] * vd_n[k] * vd_e[l] + input_t(b, i, vt_b[j], vy_s[k], vx_e[l]) * vd_f[j] * vd_n[k] * vd_w[l]; output_t(b, i, j, k, l) = out_t; } else { T out_t = input_t(b, vt_f[j], vy_n[k], vx_w[l], i) * vd_b[j] * vd_s[k] * vd_e[l] + input_t(b, vt_f[j], vy_n[k], vx_e[l], i) * vd_b[j] * vd_s[k] * vd_w[l] + input_t(b, vt_f[j], vy_s[k], vx_w[l], i) * vd_b[j] * vd_n[k] * vd_e[l] + input_t(b, vt_f[j], vy_s[k], vx_e[l], i) * vd_b[j] * vd_n[k] * vd_w[l] + input_t(b, vt_b[j], vy_n[k], vx_w[l], i) * vd_f[j] * vd_s[k] * vd_e[l] + input_t(b, vt_b[j], vy_n[k], vx_e[l], i) * vd_f[j] * vd_s[k] * vd_w[l] + input_t(b, vt_b[j], vy_s[k], vx_w[l], i) * vd_f[j] * vd_n[k] * vd_e[l] + input_t(b, vt_b[j], vy_s[k], vx_e[l], i) * vd_f[j] * vd_n[k] * vd_w[l]; output_t(b, j, k, l, i) = out_t; } } } } } } } template <typename T> HOSTDEVICE inline T cubic_convolution1(T x, T A) { return ((A + 2) * x - (A + 3)) * x * x + 1; } template <typename T> HOSTDEVICE inline T cubic_convolution2(T x, T A) { return ((A * x - 5 * A) * x + 8 * A) * x - 4 * A; } template <typename T> HOSTDEVICE inline void get_cubic_upsample_coefficients(T coeffs[4], T t) { T A = -0.75; T x1 = t; coeffs[0] = cubic_convolution2<T>(x1 + 1.0, A); coeffs[1] = cubic_convolution1<T>(x1, A); // opposite coefficients T x2 = 1.0 - t; coeffs[2] = cubic_convolution1<T>(x2, A); coeffs[3] = cubic_convolution2<T>(x2 + 1.0, A); } template <typename T> static inline T cubic_interp(T x0, T x1, T x2, T x3, T t) { T coeffs[4]; get_cubic_upsample_coefficients<T>(coeffs, t); return x0 * coeffs[0] + x1 * coeffs[1] + x2 * coeffs[2] + x3 * coeffs[3]; } template <typename T> static void BicubicInterpolation(const Tensor& input, Tensor* output, const float ratio_h, const float ratio_w, const int in_h, const int in_w, const int n, const int c, const int out_h, const int out_w, const bool align_corners, const DataLayout data_layout) { auto input_t = EigenTensor<T, 4>::From(input); auto output_t = EigenTensor<T, 4>::From(*output); for (int k = 0; k < out_h; k++) { // loop for images T y_n = align_corners ? static_cast<T>(ratio_h * k) : static_cast<T>(ratio_h * (k + 0.5) - 0.5); int input_y = floorf(y_n); const T y_t = y_n - input_y; for (int l = 0; l < out_w; l++) { T x_n = align_corners ? static_cast<T>(ratio_w * l) : static_cast<T>(ratio_w * (l + 0.5) - 0.5); int input_x = floorf(x_n); const T x_t = x_n - input_x; for (int i = 0; i < n; i++) { // loop for batches for (int j = 0; j < c; j++) { // loop for channels T coefficients[4]; // interp 4 times in x direction for (int ii = 0; ii < 4; ii++) { int access_y = std::max(std::min(input_y - 1 + ii, in_h - 1), static_cast<int>(0)); int access_x_0 = std::max(std::min(input_x - 1, in_w - 1), static_cast<int>(0)); int access_x_1 = std::max(std::min(input_x + 0, in_w - 1), static_cast<int>(0)); int access_x_2 = std::max(std::min(input_x + 1, in_w - 1), static_cast<int>(0)); int access_x_3 = std::max(std::min(input_x + 2, in_w - 1), static_cast<int>(0)); if (data_layout == DataLayout::kNCHW) { coefficients[ii] = cubic_interp<T>(input_t(i, j, access_y, access_x_0), input_t(i, j, access_y, access_x_1), input_t(i, j, access_y, access_x_2), input_t(i, j, access_y, access_x_3), x_t); } else { coefficients[ii] = cubic_interp<T>(input_t(i, access_y, access_x_0, j), input_t(i, access_y, access_x_1, j), input_t(i, access_y, access_x_2, j), input_t(i, access_y, access_x_3, j), x_t); } } // interp y direction if (data_layout == DataLayout::kNCHW) { output_t(i, j, k, l) = cubic_interp<T>(coefficients[0], coefficients[1], coefficients[2], coefficients[3], y_t); } else { output_t(i, k, l, j) = cubic_interp<T>(coefficients[0], coefficients[1], coefficients[2], coefficients[3], y_t); } } } } } } template <typename T> static void NearestNeighborInterpolateGrad( const Tensor& output_grad, Tensor* input_grad, const float ratio_h, const float ratio_w, const int n, const int c, const int out_h, const int out_w, const bool align_corners, const DataLayout data_layout) { auto input_grad_t = EigenTensor<T, 4>::From(*input_grad); auto output_grad_t = EigenTensor<T, 4>::From(output_grad); for (int k = 0; k < out_h; k++) { // loop for images int in_k = (align_corners) ? static_cast<int>(ratio_h * k + 0.5) : static_cast<int>(ratio_h * k); for (int l = 0; l < out_w; l++) { int in_l = (align_corners) ? static_cast<int>(ratio_w * l + 0.5) : static_cast<int>(ratio_w * l); for (int i = 0; i < n; i++) { // loop for batches for (int j = 0; j < c; j++) { // loop for channels if (data_layout == DataLayout::kNCHW) { input_grad_t(i, j, in_k, in_l) += output_grad_t(i, j, k, l); } else { input_grad_t(i, in_k, in_l, j) += output_grad_t(i, k, l, j); } } } } } } template <typename T> static void BilinearInterpolationGrad( const Tensor& output_grad, Tensor* input_grad, const float ratio_h, const float ratio_w, const int in_h, const int in_w, const int n, const int c, const int out_h, const int out_w, const bool align_corners, const int align_mode, const DataLayout data_layout) { auto input_grad_t = EigenTensor<T, 4>::From(*input_grad); auto output_grad_t = EigenTensor<T, 4>::From(output_grad); bool align_flag = (align_mode == 0 && !align_corners); for (int k = 0; k < out_h; k++) { // loop for images int y_n = align_flag ? static_cast<int>(ratio_h * (k + 0.5) - 0.5) : static_cast<int>(ratio_h * k); y_n = (y_n > 0) ? y_n : 0; int y_s = (y_n + 1) < (in_h - 1) ? (y_n + 1) : (in_h - 1); float idx_src_y = ratio_h * (k + 0.5) - 0.5; idx_src_y = (idx_src_y > 0) ? idx_src_y : 0; float d_n = align_flag ? idx_src_y - y_n : ratio_h * k - y_n; float d_s = 1.f - d_n; for (int l = 0; l < out_w; l++) { int x_w = align_flag ? static_cast<int>(ratio_w * (l + 0.5) - 0.5) : static_cast<int>(ratio_w * l); x_w = (x_w > 0) ? x_w : 0; int x_e = (x_w + 1) < (in_w - 1) ? (x_w + 1) : (in_w - 1); float idx_src_x = ratio_w * (l + 0.5) - 0.5; idx_src_x = (idx_src_x > 0) ? idx_src_x : 0; float d_w = align_flag ? idx_src_x - x_w : ratio_w * l - x_w; float d_e = 1.f - d_w; for (int i = 0; i < n; i++) { // loop for batches for (int j = 0; j < c; j++) { // loop for channels // bilinear interpolation grad if (data_layout == DataLayout::kNCHW) { const T grad = output_grad_t(i, j, k, l); input_grad_t(i, j, y_n, x_w) += static_cast<T>(grad * d_s * d_e); input_grad_t(i, j, y_s, x_w) += static_cast<T>(grad * d_n * d_e); input_grad_t(i, j, y_n, x_e) += static_cast<T>(grad * d_s * d_w); input_grad_t(i, j, y_s, x_e) += static_cast<T>(grad * d_n * d_w); } else { const T grad = output_grad_t(i, k, l, j); input_grad_t(i, y_n, x_w, j) += static_cast<T>(grad * d_s * d_e); input_grad_t(i, y_s, x_w, j) += static_cast<T>(grad * d_n * d_e); input_grad_t(i, y_n, x_e, j) += static_cast<T>(grad * d_s * d_w); input_grad_t(i, y_s, x_e, j) += static_cast<T>(grad * d_n * d_w); } } } } } } template <typename T> static void TrilinearInterpolationGrad( const Tensor& output_grad, Tensor* input_grad, const float ratio_d, const float ratio_h, const float ratio_w, const int in_d, const int in_h, const int in_w, const int n, const int c, const int out_d, const int out_h, const int out_w, const bool align_corners, const int align_mode, const DataLayout data_layout) { auto input_grad_t = EigenTensor<T, 5>::From(*input_grad); auto output_grad_t = EigenTensor<T, 5>::From(output_grad); bool align_flag = (align_mode == 0 && !align_corners); for (int j = 0; j < out_d; j++) { // loop for D int t_f = align_flag ? static_cast<int>(ratio_d * (j + 0.5) - 0.5) : static_cast<int>(ratio_d * j); t_f = (t_f > 0) ? t_f : 0; int t_b = (t_f + 1) < (in_d - 1) ? (t_f + 1) : (in_d - 1); float idx_src_t = ratio_d * (j + 0.5) - 0.5; idx_src_t = (idx_src_t > 0) ? idx_src_t : 0; float d_f = align_flag ? idx_src_t - t_f : ratio_d * j - t_f; float d_b = 1.f - d_f; for (int k = 0; k < out_h; k++) { // loop for H int y_n = align_flag ? static_cast<int>(ratio_h * (k + 0.5) - 0.5) : static_cast<int>(ratio_h * k); y_n = (y_n > 0) ? y_n : 0; int y_s = (y_n + 1) < (in_h - 1) ? (y_n + 1) : (in_h - 1); float idx_src_y = ratio_h * (k + 0.5) - 0.5; idx_src_y = (idx_src_y > 0) ? idx_src_y : 0; float d_n = align_flag ? idx_src_y - y_n : ratio_h * k - y_n; float d_s = 1.f - d_n; for (int l = 0; l < out_w; l++) { // loop for W int x_w = align_flag ? static_cast<int>(ratio_w * (l + 0.5) - 0.5) : static_cast<int>(ratio_w * l); x_w = (x_w > 0) ? x_w : 0; int x_e = (x_w + 1) < (in_w - 1) ? (x_w + 1) : (in_w - 1); float idx_src_x = ratio_w * (l + 0.5) - 0.5; idx_src_x = (idx_src_x > 0) ? idx_src_x : 0; float d_w = align_flag ? idx_src_x - x_w : ratio_w * l - x_w; float d_e = 1.f - d_w; for (int b = 0; b < n; b++) { // loop for batches for (int i = 0; i < c; i++) { // loop for channels // trilinear interpolation grad if (data_layout == DataLayout::kNCHW) { const T grad = output_grad_t(b, i, j, k, l); input_grad_t(b, i, t_f, y_n, x_w) += static_cast<T>(grad * d_b * d_s * d_e); input_grad_t(b, i, t_f, y_n, x_e) += static_cast<T>(grad * d_b * d_s * d_w); input_grad_t(b, i, t_f, y_s, x_w) += static_cast<T>(grad * d_b * d_n * d_e); input_grad_t(b, i, t_f, y_s, x_e) += static_cast<T>(grad * d_b * d_n * d_w); input_grad_t(b, i, t_b, y_n, x_w) += static_cast<T>(grad * d_f * d_s * d_e); input_grad_t(b, i, t_b, y_n, x_e) += static_cast<T>(grad * d_f * d_s * d_w); input_grad_t(b, i, t_b, y_s, x_w) += static_cast<T>(grad * d_f * d_n * d_e); input_grad_t(b, i, t_b, y_s, x_e) += static_cast<T>(grad * d_f * d_n * d_w); } else { const T grad = output_grad_t(b, j, k, l, i); input_grad_t(b, t_f, y_n, x_w, i) += static_cast<T>(grad * d_b * d_s * d_e); input_grad_t(b, t_f, y_n, x_e, i) += static_cast<T>(grad * d_b * d_s * d_w); input_grad_t(b, t_f, y_s, x_w, i) += static_cast<T>(grad * d_b * d_n * d_e); input_grad_t(b, t_f, y_s, x_e, i) += static_cast<T>(grad * d_b * d_n * d_w); input_grad_t(b, t_b, y_n, x_w, i) += static_cast<T>(grad * d_f * d_s * d_e); input_grad_t(b, t_b, y_n, x_e, i) += static_cast<T>(grad * d_f * d_s * d_w); input_grad_t(b, t_b, y_s, x_w, i) += static_cast<T>(grad * d_f * d_n * d_e); input_grad_t(b, t_b, y_s, x_e, i) += static_cast<T>(grad * d_f * d_n * d_w); } } } } } } } template <typename T> static void BicubicInterpolationGrad(const Tensor& output_grad, Tensor* input_grad, const float ratio_h, const float ratio_w, const int in_h, const int in_w, const int n, const int c, const int out_h, const int out_w, const bool align_corners, const DataLayout data_layout) { auto input_grad_t = EigenTensor<T, 4>::From(*input_grad); auto output_grad_t = EigenTensor<T, 4>::From(output_grad); for (int k = 0; k < out_h; k++) { // loop for images T y_n = align_corners ? static_cast<T>(ratio_h * k) : static_cast<T>(ratio_h * (k + 0.5) - 0.5); int input_y = floorf(y_n); T y_t = y_n - input_y; for (int l = 0; l < out_w; l++) { T x_n = align_corners ? static_cast<T>(ratio_w * l) : static_cast<T>(ratio_w * (l + 0.5) - 0.5); int input_x = floorf(x_n); T x_t = x_n - input_x; T x_coeffs[4]; T y_coeffs[4]; get_cubic_upsample_coefficients<T>(x_coeffs, x_t); get_cubic_upsample_coefficients<T>(y_coeffs, y_t); for (int i = 0; i < n; i++) { // loop for batches for (int j = 0; j < c; j++) { // loop for channels // bicubic interpolation grad for (int ii = 0; ii < 4; ii++) { for (int jj = 0; jj < 4; jj++) { int access_x = std::max(std::min(input_x - 1 + ii, in_w - 1), static_cast<int>(0)); int access_y = std::max(std::min(input_y - 1 + jj, in_h - 1), static_cast<int>(0)); if (data_layout == DataLayout::kNCHW) { T grad = output_grad_t(i, j, k, l); input_grad_t(i, j, access_y, access_x) += grad * y_coeffs[jj] * x_coeffs[ii]; } else { T grad = output_grad_t(i, k, l, j); input_grad_t(i, access_y, access_x, j) += grad * y_coeffs[jj] * x_coeffs[ii]; } } } } } } } } template <typename T> static void Interpolate1DCPUFwd(const framework::ExecutionContext& ctx, const Tensor& input, Tensor* output) { const std::string data_layout_str = ctx.Attr<std::string>("data_layout"); const DataLayout data_layout = framework::StringToDataLayout(data_layout_str); int n, c, in_d, in_h, in_w; ExtractNCDWH(input.dims(), data_layout, &n, &c, &in_d, &in_h, &in_w); auto interp_method = ctx.Attr<std::string>("interp_method"); bool align_corners = ctx.Attr<bool>("align_corners"); int align_mode = ctx.Attr<int>("align_mode"); int out_w = ctx.Attr<int>("out_w"); auto list_new_size_tensor = ctx.MultiInput<framework::Tensor>("SizeTensor"); if (list_new_size_tensor.size() > 0) { // have size tensor auto new_size = get_new_shape(list_new_size_tensor); out_w = new_size[0]; } else { float scale; auto scale_tensor = ctx.Input<Tensor>("Scale"); if (scale_tensor != nullptr) { auto scale_data = get_new_data_from_tensor<float>(scale_tensor); scale = scale_data[0]; } else { scale = ctx.Attr<float>("scale"); } if (scale > 0) { out_w = static_cast<int>(in_w * scale); } auto out_size = ctx.Input<Tensor>("OutSize"); if (out_size != nullptr) { auto out_size_data = get_new_data_from_tensor<int>(out_size); out_w = out_size_data[0]; } } PADDLE_ENFORCE_GT(out_w, 0, platform::errors::InvalidArgument( "out_w in Attr(out_shape) of Op(interpolate) " "should be greater than 0.")); framework::DDim dim_out; if (data_layout == DataLayout::kNCHW) { dim_out = {n, c, out_w}; } else { dim_out = {n, out_w, c}; } output->mutable_data<T>(dim_out, ctx.GetPlace()); if (in_w == out_w) { framework::TensorCopy(input, ctx.GetPlace(), output); return; } float ratio_w = 0.f; if (out_w > 1) { ratio_w = (align_corners) ? static_cast<float>(in_w - 1) / (out_w - 1) : static_cast<float>(in_w) / out_w; } if ("linear" == interp_method) { LinearInterpolation<T>(input, output, ratio_w, in_w, n, c, out_w, align_corners, align_mode, data_layout); } } template <typename T> static void Interpolate2DCPUFwd(const framework::ExecutionContext& ctx, const Tensor& input, Tensor* output) { const std::string data_layout_str = ctx.Attr<std::string>("data_layout"); const DataLayout data_layout = framework::StringToDataLayout(data_layout_str); int n, c, in_d, in_h, in_w; ExtractNCDWH(input.dims(), data_layout, &n, &c, &in_d, &in_h, &in_w); auto interp_method = ctx.Attr<std::string>("interp_method"); bool align_corners = ctx.Attr<bool>("align_corners"); int align_mode = ctx.Attr<int>("align_mode"); int out_h = ctx.Attr<int>("out_h"); int out_w = ctx.Attr<int>("out_w"); auto list_new_size_tensor = ctx.MultiInput<framework::Tensor>("SizeTensor"); if (list_new_size_tensor.size() > 0) { // have size tensor auto new_size = get_new_shape(list_new_size_tensor); out_h = new_size[0]; out_w = new_size[1]; } else { float scale; auto scale_tensor = ctx.Input<Tensor>("Scale"); if (scale_tensor != nullptr) { auto scale_data = get_new_data_from_tensor<float>(scale_tensor); scale = scale_data[0]; } else { scale = ctx.Attr<float>("scale"); } if (scale > 0) { out_h = static_cast<int>(in_h * scale); out_w = static_cast<int>(in_w * scale); } auto out_size = ctx.Input<Tensor>("OutSize"); if (out_size != nullptr) { auto out_size_data = get_new_data_from_tensor<int>(out_size); out_h = out_size_data[0]; out_w = out_size_data[1]; } } PADDLE_ENFORCE_GT(out_h, 0, platform::errors::InvalidArgument( "out_h in Attr(out_shape) of Op(interpolate) " "should be greater than 0.")); PADDLE_ENFORCE_GT(out_w, 0, platform::errors::InvalidArgument( "out_w in Attr(out_shape) of Op(interpolate) " "should be greater than 0.")); framework::DDim dim_out; if (data_layout == DataLayout::kNCHW) { dim_out = {n, c, out_h, out_w}; } else { dim_out = {n, out_h, out_w, c}; } output->mutable_data<T>(dim_out, ctx.GetPlace()); if (in_h == out_h && in_w == out_w) { framework::TensorCopy(input, ctx.GetPlace(), output); return; } float ratio_h = 0.f; float ratio_w = 0.f; if (out_h > 1) { ratio_h = (align_corners) ? static_cast<float>(in_h - 1) / (out_h - 1) : static_cast<float>(in_h) / out_h; } if (out_w > 1) { ratio_w = (align_corners) ? static_cast<float>(in_w - 1) / (out_w - 1) : static_cast<float>(in_w) / out_w; } if ("bilinear" == interp_method) { BilinearInterpolation<T>(input, output, ratio_h, ratio_w, in_h, in_w, n, c, out_h, out_w, align_corners, align_mode, data_layout); } else if ("nearest" == interp_method) { NearestNeighborInterpolate<T>(input, output, ratio_h, ratio_w, n, c, out_h, out_w, align_corners, data_layout); } else if ("bicubic" == interp_method) { BicubicInterpolation<T>(input, output, ratio_h, ratio_w, in_h, in_w, n, c, out_h, out_w, align_corners, data_layout); } } template <typename T> static void Interpolate3DCPUFwd(const framework::ExecutionContext& ctx, const Tensor& input, Tensor* output) { const std::string data_layout_str = ctx.Attr<std::string>("data_layout"); const DataLayout data_layout = framework::StringToDataLayout(data_layout_str); int n, c, in_d, in_h, in_w; ExtractNCDWH(input.dims(), data_layout, &n, &c, &in_d, &in_h, &in_w); auto interp_method = ctx.Attr<std::string>("interp_method"); bool align_corners = ctx.Attr<bool>("align_corners"); int align_mode = ctx.Attr<int>("align_mode"); int out_d = ctx.Attr<int>("out_d"); int out_h = ctx.Attr<int>("out_h"); int out_w = ctx.Attr<int>("out_w"); auto list_new_size_tensor = ctx.MultiInput<framework::Tensor>("SizeTensor"); if (list_new_size_tensor.size() > 0) { // have size tensor auto new_size = get_new_shape(list_new_size_tensor); out_d = new_size[0]; out_h = new_size[1]; out_w = new_size[2]; } else { float scale; auto scale_tensor = ctx.Input<Tensor>("Scale"); if (scale_tensor != nullptr) { auto scale_data = get_new_data_from_tensor<float>(scale_tensor); scale = scale_data[0]; } else { scale = ctx.Attr<float>("scale"); } if (scale > 0) { out_d = static_cast<int>(in_d * scale); out_h = static_cast<int>(in_h * scale); out_w = static_cast<int>(in_w * scale); } auto out_size = ctx.Input<Tensor>("OutSize"); if (out_size != nullptr) { auto out_size_data = get_new_data_from_tensor<int>(out_size); out_d = out_size_data[0]; out_h = out_size_data[1]; out_w = out_size_data[2]; } } PADDLE_ENFORCE_GT(out_d, 0, platform::errors::InvalidArgument( "out_d in Attr(out_shape) of Op(interpolate) " "should be greater than 0.")); PADDLE_ENFORCE_GT(out_h, 0, platform::errors::InvalidArgument( "out_h in Attr(out_shape) of Op(interpolate) " "should be greater than 0.")); PADDLE_ENFORCE_GT(out_w, 0, platform::errors::InvalidArgument( "out_w in Attr(out_shape) of Op(interpolate) " "should be greater than 0.")); framework::DDim dim_out; if (data_layout == DataLayout::kNCHW) { dim_out = {n, c, out_d, out_h, out_w}; } else { dim_out = {n, out_d, out_h, out_w, c}; } output->mutable_data<T>(dim_out, ctx.GetPlace()); if (in_d == out_d && in_h == out_h && in_w == out_w) { framework::TensorCopy(input, ctx.GetPlace(), output); return; } float ratio_d = 0.f; float ratio_h = 0.f; float ratio_w = 0.f; if (out_d > 1) { ratio_d = (align_corners) ? static_cast<float>(in_d - 1) / (out_d - 1) : static_cast<float>(in_d) / out_d; } if (out_h > 1) { ratio_h = (align_corners) ? static_cast<float>(in_h - 1) / (out_h - 1) : static_cast<float>(in_h) / out_h; } if (out_w > 1) { ratio_w = (align_corners) ? static_cast<float>(in_w - 1) / (out_w - 1) : static_cast<float>(in_w) / out_w; } if ("trilinear" == interp_method) { TrilinearInterpolation<T>(input, output, ratio_d, ratio_h, ratio_w, in_d, in_h, in_w, n, c, out_d, out_h, out_w, align_corners, align_mode, data_layout); } } template <typename T> static void Interpolate1DCPUBwd(const framework::ExecutionContext& ctx, Tensor* input_grad, const Tensor& output_grad) { auto* input = ctx.Input<Tensor>("X"); const std::string data_layout_str = ctx.Attr<std::string>("data_layout"); const DataLayout data_layout = framework::StringToDataLayout(data_layout_str); int n, c, in_d, in_h, in_w; ExtractNCDWH(input->dims(), data_layout, &n, &c, &in_d, &in_h, &in_w); auto interp_method = ctx.Attr<std::string>("interp_method"); bool align_corners = ctx.Attr<bool>("align_corners"); int align_mode = ctx.Attr<int>("align_mode"); int out_w = ctx.Attr<int>("out_w"); float scale; auto scale_tensor = ctx.Input<Tensor>("Scale"); if (scale_tensor != nullptr) { auto scale_data = get_new_data_from_tensor<float>(scale_tensor); scale = scale_data[0]; } else { scale = ctx.Attr<float>("scale"); } if (scale > 0) { out_w = static_cast<int>(in_w * scale); } auto out_size = ctx.Input<Tensor>("OutSize"); if (out_size != nullptr) { auto out_size_data = get_new_data_from_tensor<int>(out_size); out_w = out_size_data[0]; } auto list_new_size_tensor = ctx.MultiInput<framework::Tensor>("SizeTensor"); if (list_new_size_tensor.size() > 0) { // have size tensor auto new_size = get_new_shape(list_new_size_tensor); out_w = new_size[0]; } framework::DDim dim_grad; if (data_layout == DataLayout::kNCHW) { dim_grad = {n, c, in_w}; } else { dim_grad = {n, in_w, c}; } input_grad->mutable_data<T>(dim_grad, ctx.GetPlace()); auto& device_ctx = ctx.template device_context<platform::CPUDeviceContext>(); phi::funcs::SetConstant<platform::CPUDeviceContext, T> zero; zero(device_ctx, input_grad, static_cast<T>(0.0)); if (in_w == out_w) { framework::TensorCopy(output_grad, ctx.GetPlace(), input_grad); return; } float ratio_w = 0.f; if (out_w > 1) { ratio_w = (align_corners) ? static_cast<float>(in_w - 1) / (out_w - 1) : static_cast<float>(in_w) / out_w; } if ("linear" == interp_method) { LinearInterpolationGrad<T>(output_grad, input_grad, ratio_w, in_w, n, c, out_w, align_corners, align_mode, data_layout); } } template <typename T> static void Interpolate2DCPUBwd(const framework::ExecutionContext& ctx, Tensor* input_grad, const Tensor& output_grad) { auto* input = ctx.Input<Tensor>("X"); const std::string data_layout_str = ctx.Attr<std::string>("data_layout"); const DataLayout data_layout = framework::StringToDataLayout(data_layout_str); int n, c, in_d, in_h, in_w; ExtractNCDWH(input->dims(), data_layout, &n, &c, &in_d, &in_h, &in_w); auto interp_method = ctx.Attr<std::string>("interp_method"); bool align_corners = ctx.Attr<bool>("align_corners"); int align_mode = ctx.Attr<int>("align_mode"); int out_h = ctx.Attr<int>("out_h"); int out_w = ctx.Attr<int>("out_w"); float scale; auto scale_tensor = ctx.Input<Tensor>("Scale"); if (scale_tensor != nullptr) { auto scale_data = get_new_data_from_tensor<float>(scale_tensor); scale = scale_data[0]; } else { scale = ctx.Attr<float>("scale"); } if (scale > 0) { out_h = static_cast<int>(in_h * scale); out_w = static_cast<int>(in_w * scale); } auto out_size = ctx.Input<Tensor>("OutSize"); if (out_size != nullptr) { auto out_size_data = get_new_data_from_tensor<int>(out_size); out_h = out_size_data[0]; out_w = out_size_data[1]; } auto list_new_size_tensor = ctx.MultiInput<framework::Tensor>("SizeTensor"); if (list_new_size_tensor.size() > 0) { // have size tensor auto new_size = get_new_shape(list_new_size_tensor); out_h = new_size[0]; out_w = new_size[1]; } framework::DDim dim_grad; if (data_layout == DataLayout::kNCHW) { dim_grad = {n, c, in_h, in_w}; } else { dim_grad = {n, in_h, in_w, c}; } input_grad->mutable_data<T>(dim_grad, ctx.GetPlace()); auto& device_ctx = ctx.template device_context<platform::CPUDeviceContext>(); phi::funcs::SetConstant<platform::CPUDeviceContext, T> zero; zero(device_ctx, input_grad, static_cast<T>(0.0)); if (in_h == out_h && in_w == out_w) { framework::TensorCopy(output_grad, ctx.GetPlace(), input_grad); return; } float ratio_h = 0.f; float ratio_w = 0.f; if (out_h > 1) { ratio_h = (align_corners) ? static_cast<float>(in_h - 1) / (out_h - 1) : static_cast<float>(in_h) / out_h; } if (out_w > 1) { ratio_w = (align_corners) ? static_cast<float>(in_w - 1) / (out_w - 1) : static_cast<float>(in_w) / out_w; } if ("bilinear" == interp_method) { BilinearInterpolationGrad<T>(output_grad, input_grad, ratio_h, ratio_w, in_h, in_w, n, c, out_h, out_w, align_corners, align_mode, data_layout); } else if ("nearest" == interp_method) { NearestNeighborInterpolateGrad<T>(output_grad, input_grad, ratio_h, ratio_w, n, c, out_h, out_w, align_corners, data_layout); } else if ("bicubic" == interp_method) { BicubicInterpolationGrad<T>(output_grad, input_grad, ratio_h, ratio_w, in_h, in_w, n, c, out_h, out_w, align_corners, data_layout); } } template <typename T> static void Interpolate3DCPUBwd(const framework::ExecutionContext& ctx, Tensor* input_grad, const Tensor output_grad) { auto* input = ctx.Input<Tensor>("X"); const std::string data_layout_str = ctx.Attr<std::string>("data_layout"); const DataLayout data_layout = framework::StringToDataLayout(data_layout_str); int n, c, in_d, in_h, in_w; ExtractNCDWH(input->dims(), data_layout, &n, &c, &in_d, &in_h, &in_w); auto interp_method = ctx.Attr<std::string>("interp_method"); bool align_corners = ctx.Attr<bool>("align_corners"); int align_mode = ctx.Attr<int>("align_mode"); int out_d = ctx.Attr<int>("out_d"); int out_h = ctx.Attr<int>("out_h"); int out_w = ctx.Attr<int>("out_w"); float scale; auto scale_tensor = ctx.Input<Tensor>("Scale"); if (scale_tensor != nullptr) { auto scale_data = get_new_data_from_tensor<float>(scale_tensor); scale = scale_data[0]; } else { scale = ctx.Attr<float>("scale"); } if (scale > 0) { out_d = static_cast<int>(in_d * scale); out_h = static_cast<int>(in_h * scale); out_w = static_cast<int>(in_w * scale); } auto out_size = ctx.Input<Tensor>("OutSize"); if (out_size != nullptr) { auto out_size_data = get_new_data_from_tensor<int>(out_size); out_d = out_size_data[0]; out_h = out_size_data[1]; out_w = out_size_data[2]; } auto list_new_size_tensor = ctx.MultiInput<framework::Tensor>("SizeTensor"); if (list_new_size_tensor.size() > 0) { // have size tensor auto new_size = get_new_shape(list_new_size_tensor); out_d = new_size[0]; out_h = new_size[1]; out_w = new_size[2]; } framework::DDim dim_grad; if (data_layout == DataLayout::kNCHW) { dim_grad = {n, c, in_d, in_h, in_w}; } else { dim_grad = {n, in_d, in_h, in_w, c}; } input_grad->mutable_data<T>(dim_grad, ctx.GetPlace()); auto& device_ctx = ctx.template device_context<platform::CPUDeviceContext>(); phi::funcs::SetConstant<platform::CPUDeviceContext, T> zero; zero(device_ctx, input_grad, static_cast<T>(0.0)); if (in_d == out_d && in_h == out_h && in_w == out_w) { framework::TensorCopy(output_grad, ctx.GetPlace(), input_grad); return; } float ratio_d = 0.f; float ratio_h = 0.f; float ratio_w = 0.f; if (out_d > 1) { ratio_d = (align_corners) ? static_cast<float>(in_d - 1) / (out_d - 1) : static_cast<float>(in_d) / out_d; } if (out_h > 1) { ratio_h = (align_corners) ? static_cast<float>(in_h - 1) / (out_h - 1) : static_cast<float>(in_h) / out_h; } if (out_w > 1) { ratio_w = (align_corners) ? static_cast<float>(in_w - 1) / (out_w - 1) : static_cast<float>(in_w) / out_w; } if ("trilinear" == interp_method) { TrilinearInterpolationGrad<T>( output_grad, input_grad, ratio_d, ratio_h, ratio_w, in_d, in_h, in_w, n, c, out_d, out_h, out_w, align_corners, align_mode, data_layout); } } template <typename T> class InterpolateKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* input = ctx.Input<Tensor>("X"); auto* output = ctx.Output<Tensor>("Out"); auto input_dims = input->dims(); if (input_dims.size() == 3) { // 1D interpolation Interpolate1DCPUFwd<T>(ctx, *input, output); } else if (input_dims.size() == 4) { // 2D interpolation Interpolate2DCPUFwd<T>(ctx, *input, output); } else if (input_dims.size() == 5) { // 3D interpolation Interpolate3DCPUFwd<T>(ctx, *input, output); } } }; template <typename T> class InterpolateGradKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* input_grad = ctx.Output<Tensor>(framework::GradVarName("X")); auto* output_grad = ctx.Input<Tensor>(framework::GradVarName("Out")); auto output_grad_dims = output_grad->dims(); if (output_grad_dims.size() == 3) { // 1D interpolation grad Interpolate1DCPUBwd<T>(ctx, input_grad, *output_grad); } else if (output_grad_dims.size() == 4) { // 2D interpolation grad Interpolate2DCPUBwd<T>(ctx, input_grad, *output_grad); } else if (output_grad_dims.size() == 5) { // 3D interpolation grad Interpolate3DCPUBwd<T>(ctx, input_grad, *output_grad); } } }; } // namespace operators } // namespace paddle
vsll.c
#include<Python.h> #include<numpy/arrayobject.h> #include<math.h> #include<omp.h> #define IND(a,i) *((double *)(a->data+i*a->strides[0])) static PyObject *vsll(PyObject *self, PyObject *args, PyObject *keywds); static PyObject *vsll(PyObject *self, PyObject *args, PyObject *keywds) { PyObject *etc, *seq, *temp_seq; PyArrayObject *t,*y,*rampparams; double x0,a,b,c,x1; int i; npy_intp dims[1]; // etc = PyList_New(0); static char *kwlist[] = {"rampparams","temp_seq","etc",NULL}; if(!PyArg_ParseTupleAndKeywords(args,keywds,"OO|O",kwlist,&rampparams,&temp_seq,&etc)) { return NULL; } t = (PyArrayObject *) PyList_GetItem(temp_seq,0); x0 = IND(rampparams,0); a = IND(rampparams,1); b = IND(rampparams,2); c = IND(rampparams,3); x1 = IND(rampparams,4); dims[0] = t->dimensions[0]; y = (PyArrayObject *) PyArray_SimpleNew(1,dims,PyArray_DOUBLE); #pragma omp parallel for for(i=0;i<dims[0];i++) { if(IND(t,i)>x0) IND(y,i) = a*log(IND(t,i)-x0)+b*(IND(t,i)-x1)+c; else IND(y,i) = 0; } //Py_XDECREF(t); return PyArray_Return(y); } static char module_docstring[]="\ This function creates a model that fits a ramp using a log + linear ploynomial.\n\ \n\ Parameters\n\ ----------\n\ x0: phase offset for log term\n\ a: log(x) constant\n\ b: x constant\n\ c: x=0 offset\n\ x1: phase offset for polynomial\n\ x: Array of time/phase points\n\ \n\ Returns\n\ -------\n\ This function returns the flux values for the ramp models\n\ \n\ Revisions\n\ ---------\n\ 2008-08-31 Kevin Stevenson, UCF \n\ kevin218@knights.ucf.edu\n\ Original version\n\ 2010-07-07 Kevin Stevenson\n\ New code for when x < x0\n\ 2010-12-26 Nate Lust, UCF\n\ natelust at linux dot com\n\ Updated to C extension\n\ 2018-11-22 Jonathan Fraine, SSI\n\ jfraine at spacescience.org\n\ Updated c extensions to python3, with support for python2.7\n\ "; static PyMethodDef module_methods[] = { {"vsll",(PyCFunction)vsll,METH_VARARGS|METH_KEYWORDS,module_docstring},{NULL}}; PyMODINIT_FUNC #if PY_MAJOR_VERSION >= 3 PyInit_vsll(void) #else initvsll(void) #endif { #if PY_MAJOR_VERSION >= 3 PyObject *module; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "vsll", /* m_name */ module_docstring, /* m_doc */ -1, /* m_size */ module_methods, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; #endif #if PY_MAJOR_VERSION >= 3 module = PyModule_Create(&moduledef); if (!module) return NULL; /* Load `numpy` functionality. */ import_array(); return module; #else PyObject *m = Py_InitModule3("vsll", module_methods, module_docstring); if (m == NULL) return; /* Load `numpy` functionality. */ import_array(); #endif }
ep.c
//-------------------------------------------------------------------------// // // // This benchmark is an OpenMP C version of the NPB EP code. This OpenMP // // C version is developed by the Center for Manycore Programming at Seoul // // National University and derived from the OpenMP Fortran versions in // // "NPB3.3-OMP" developed by NAS. // // // // Permission to use, copy, distribute and modify this software for any // // purpose with or without fee is hereby granted. This software is // // provided "as is" without express or implied warranty. // // // // Information on NPB 3.3, including the technical report, the original // // specifications, source code, results and information on how to submit // // new results, is available at: // // // // http://www.nas.nasa.gov/Software/NPB/ // // // // Send comments or suggestions for this OpenMP C version to // // cmp@aces.snu.ac.kr // // // // Center for Manycore Programming // // School of Computer Science and Engineering // // Seoul National University // // Seoul 151-744, Korea // // // // E-mail: cmp@aces.snu.ac.kr // // // //-------------------------------------------------------------------------// //-------------------------------------------------------------------------// // Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, // // and Jaejin Lee // //-------------------------------------------------------------------------// //--------------------------------------------------------------------- // program EMBAR //--------------------------------------------------------------------- // M is the Log_2 of the number of complex pairs of uniform (0, 1) random // numbers. MK is the Log_2 of the size of each batch of uniform random // numbers. MK can be set for convenience on a given system, since it does // not affect the results. //--------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <math.h> #ifdef _OPENMP #include <omp.h> #endif #include "type.h" #include "npbparams.h" #include "randdp.h" #include "timers.h" #include "print_results.h" #include "../my_include/my_include.h" #define MAX(X,Y) (((X) > (Y)) ? (X) : (Y)) #define MK 16 #define MM (M - MK) #define NN (1 << MM) #define NK (1 << MK) #define NQ 10 #define EPSILON 1.0e-8 #define A 1220703125.0 #define S 271828183.0 static double x[2*NK]; static double qq[NQ]; #pragma omp threadprivate(x,qq) static double q[NQ]; int i1=0, i2=0, i3=0, k_temp = 0; double ssx,ssy; void vranlc_temp( int n, double *x, double a, double y[] ) { //-------------------------------------------------------------------- // // This routine generates N uniform pseudorandom double precision numbers in // the range (0, 1) by using the linear congruential generator // // x_{k+1} = a x_k (mod 2^46) // // where 0 < x_k < 2^46 and 0 < a < 2^46. This scheme generates 2^44 numbers // before repeating. The argument A is the same as 'a' in the above formula, // and X is the same as x_0. A and X must be odd double precision integers // in the range (1, 2^46). The N results are placed in Y and are normalized // to be between 0 and 1. X is updated to contain the new seed, so that // subsequent calls to VRANLC using the same arguments will generate a // continuous sequence. If N is zero, only initialization is performed, and // the variables X, A and Y are ignored. // // This routine is the standard version designed for scalar or RISC systems. // However, it should produce the same results on any single processor // computer with at least 48 mantissa bits in double precision floating point // data. On 64 bit systems, double precision should be disabled. // //-------------------------------------------------------------------- // r23 = pow(0.5, 23.0); //// pow(0.5, 23.0) = 1.1920928955078125e-07 // r46 = r23 * r23; // t23 = pow(2.0, 23.0); //// pow(2.0, 23.0) = 8.388608e+06 // t46 = t23 * t23; const double r23 = 1.1920928955078125e-07; const double r46 = r23 * r23; const double t23 = 8.388608e+06; const double t46 = t23 * t23; double t1, t2, t3, t4, a1, a2, x1, x2, z; int i; //-------------------------------------------------------------------- // Break A into two parts such that A = 2^23 * A1 + A2. //-------------------------------------------------------------------- t1 = r23 * a; a1 = (int) t1; a2 = a - t23 * a1; //-------------------------------------------------------------------- // Generate N results. This loop is not vectorizable. //-------------------------------------------------------------------- for ( i = 0; i < n; i++ ) { //-------------------------------------------------------------------- // Break X into two parts such that X = 2^23 * X1 + X2, compute // Z = A1 * X2 + A2 * X1 (mod 2^23), and then // X = 2^23 * Z + A2 * X2 (mod 2^46). //-------------------------------------------------------------------- t1 = r23 * (*x); x1 = (int) t1; x2 = *x - t23 * x1; t1 = a1 * x2 + a2 * x1; t2 = (int) (r23 * t1); z = t1 - t23 * t2; t3 = t23 * z + a2 * x2; t4 = (int) (r46 * t3) ; *x = t3 - t46 * t4; y[i] = r46 * (*x); i3 = i; } return; } int main(int argc, char *argv[]) { crucial_data(x,"double",2*NK); crucial_data(qq,"double",NQ); crucial_data(q,"double",NQ); crucial_data(&ssx,"double",1); crucial_data(&ssy,"double",1); //printf("the addr of x at beginning is %p\n",x); double Mops, t1, t2, t3, t4, x1, x2; double sx, sy, tm, an, tt, gc; double sx_verify_value, sy_verify_value, sx_err, sy_err; int np; int i, ik, kk, l, k, nit; int k_offset, j; logical verified, timers_enabled; consistent_data(&k_temp,"int",1); consistent_data(&i1,"int",1); consistent_data(&i2,"int",1); //consistent_data(&i3,"int",1); double dum[3] = {1.0, 1.0, 1.0}; char size[16]; FILE *fp; if ((fp = fopen("timer.flag", "r")) == NULL) { timers_enabled = false; } else { timers_enabled = true; fclose(fp); } //-------------------------------------------------------------------- // Because the size of the problem is too large to store in a 32-bit // integer for some classes, we put it into a string (for printing). // Have to strip off the decimal point put in there by the floating // point print statement (internal file) //-------------------------------------------------------------------- sprintf(size, "%15.0lf", pow(2.0, M+1)); j = 14; if (size[j] == '.') j--; size[j+1] = '\0'; printf("\n\n NAS Parallel Benchmarks (NPB3.3-OMP-C) - EP Benchmark\n"); printf("\n Number of random numbers generated: %15s\n", size); printf("\n Number of available threads: %13d\n", omp_get_max_threads()); verified = false; //-------------------------------------------------------------------- // Compute the number of "batches" of random number pairs generated // per processor. Adjust if the number of processors does not evenly // divide the total number //-------------------------------------------------------------------- np = NN; //-------------------------------------------------------------------- // Call the random number generator functions and initialize // the x-array to reduce the effects of paging on the timings. // Also, call all mathematical functions that are used. Make // sure these initializations cannot be eliminated as dead code. //-------------------------------------------------------------------- vranlc(0, &dum[0], dum[1], &dum[2]); dum[0] = randlc(&dum[1], dum[2]); #pragma omp parallel default(shared) private(i) { for (i = 0; i < 2 * NK; i++) { x[i] = -1.0e99; } } Mops = log(sqrt(fabs(MAX(1.0, 1.0)))); #pragma omp parallel { timer_clear(0); if (timers_enabled) timer_clear(1); if (timers_enabled) timer_clear(2); } timer_start(0); t1 = A; vranlc(0, &t1, A, x); //-------------------------------------------------------------------- // Compute AN = A ^ (2 * NK) (mod 2^46). //-------------------------------------------------------------------- t1 = A; for (i = 0; i < MK + 1; i++) { t2 = randlc(&t1, t1); } an = t1; tt = S; gc = 0.0; sx = 0.0; sy = 0.0; for (i = 0; i < NQ; i++) { q[i] = 0.0; } //-------------------------------------------------------------------- // Each instance of this loop may be performed independently. We compute // the k offsets separately to take into account the fact that some nodes // have more numbers to generate than others //-------------------------------------------------------------------- int calculate_counter = 0; int uncalculate_counter = 0; k_offset = -1; //FILE *testfile; //testfile = fopen("resultfile1443.out","w"); //printf("the addr of x at middle is %p\n",x); #pragma omp parallel default(shared) private(k,kk,t1,t2,t3,t4,i,ik,x1,x2,l) { for (i = 0; i < NQ; i++) { qq[i] = 0.0; } flush_whole_cache(); start_crash(); #pragma omp for reduction(+:sx,sy) nowait for (k = 1; k <= np; k++) {//main conputation loop kk = k_offset + k; t1 = S; t2 = an; for (i = 1; i <= 100; i++) { ik = kk / 2; if ((2 * ik) != kk) t3 = randlc(&t1, t2); if (ik == 0) break; t3 = randlc(&t2, t2); kk = ik; i1 = i; } //printf("k=%d, i1 = %d\n",k,i1); //-------------------------------------------------------------------- // Compute uniform pseudorandom numbers. //-------------------------------------------------------------------- if (timers_enabled) timer_start(2); vranlc_temp(2 * NK, &t1, A, x); if (timers_enabled) timer_stop(2); /*if(k==2981){ fprintf(testfile,"after vranlc, t1 = %lf, A = %lf\n",t1, A); for(ijk = 0; ijk<2*NK; ijk++) { fprintf(testfile,"%lf\n",x[ijk]); }}*/ //-------------------------------------------------------------------- // Compute Gaussian deviates by acceptance-rejection method and // tally counts in concentri//square annuli. This loop is not // vectorizable. //-------------------------------------------------------------------- if (timers_enabled) timer_start(1); for (i = 0; i < NK; i++) { x1 = 2.0 * x[2*i] - 1.0; x2 = 2.0 * x[2*i+1] - 1.0; t1 = x1 * x1 + x2 * x2; if (t1 <= 1.0) { t2 = sqrt(-2.0 * log(t1) / t1); t3 = (x1 * t2); t4 = (x2 * t2); l = MAX(fabs(t3), fabs(t4)); qq[l] = qq[l] + 1.0; sx = sx + t3; sy = sy + t4; } i2=i; } if (timers_enabled) timer_stop(1); k_temp=k; ssx = sx; ssy = sy; /*sx_err = fabs((sx - sx_verify_value) / sx_verify_value); sy_err = fabs((sy - sy_verify_value) / sy_verify_value); verified = ((sx_err <= EPSILON) && (sy_err <= EPSILON)); printf("sx_err = %25.15lE, sy_err =%25.15lE\n",sx_err, sy_err);*/ } end_crash(); printf("%d %d\n",calculate_counter,uncalculate_counter); for (i = 0; i < NQ; i++) { #pragma omp atomic q[i] += qq[i]; } } //fclose(testfile); for (i = 0; i < NQ; i++) { gc = gc + q[i]; } timer_stop(0); tm = timer_read(0); nit = 0; verified = true; if (M == 24) { sx_verify_value = -3.247834652034740e+3; sy_verify_value = -6.958407078382297e+3; } else if (M == 25) { sx_verify_value = -2.863319731645753e+3; sy_verify_value = -6.320053679109499e+3; } else if (M == 28) { sx_verify_value = -4.295875165629892e+3; sy_verify_value = -1.580732573678431e+4; } else if (M == 30) { sx_verify_value = 4.033815542441498e+4; sy_verify_value = -2.660669192809235e+4; } else if (M == 32) { sx_verify_value = 4.764367927995374e+4; sy_verify_value = -8.084072988043731e+4; } else if (M == 36) { sx_verify_value = 1.982481200946593e+5; sy_verify_value = -1.020596636361769e+5; } else if (M == 40) { sx_verify_value = -5.319717441530e+05; sy_verify_value = -3.688834557731e+05; } else { verified = false; } if (verified) { sx_err = fabs((sx - sx_verify_value) / sx_verify_value); sy_err = fabs((sy - sy_verify_value) / sy_verify_value); verified = ((sx_err <= EPSILON) && (sy_err <= EPSILON)); } Mops = pow(2.0, M+1) / tm / 1000000.0; printf("\nEP Benchmark Results:\n\n"); printf("CPU Time =%10.4lf\n", tm); printf("N = 2^%5d\n", M); printf("No. Gaussian Pairs = %15.0lf\n", gc); printf("Sums = %25.15lE %25.15lE\n", sx, sy); printf("Counts: \n"); for (i = 0; i < NQ; i++) { printf("%3d%15.0lf\n", i, q[i]); } print_results("EP", CLASS, M+1, 0, 0, nit, tm, Mops, "Random numbers generated", verified, NPBVERSION, COMPILETIME, CS1, CS2, CS3, CS4, CS5, CS6, CS7); if (timers_enabled) { if (tm <= 0.0) tm = 1.0; tt = timer_read(0); printf("\nTotal time: %9.3lf (%6.2lf)\n", tt, tt*100.0/tm); tt = timer_read(1); printf("Gaussian pairs: %9.3lf (%6.2lf)\n", tt, tt*100.0/tm); tt = timer_read(2); printf("Random numbers: %9.3lf (%6.2lf)\n", tt, tt*100.0/tm); } return 0; }
iftODISF.c
/*****************************************************************************\ * iftODISF.c * * AUTHOR : Felipe Belem * DATE : 2021-06-15 * LICENSE : MIT License * EMAIL : felipe.belem@ic.unicamp.br \*****************************************************************************/ #include "iftODISF.h" /*****************************************************************************\ * * PRIVATE STRUCTS * \*****************************************************************************/ /* Contains all IFT's auxiliary data */ typedef struct _ift_iftdata { int num_spels; // Number of spels within the image/video int *id_map; // Seed id map (a.k.a. root map) int *pred_map; // Predecessor map double *cost_map; // Accumulated pathcost map } _iftIFTData; /* Contains the forest's data through its trees (and their relation) */ typedef struct _ift_foreststats { int num_trees, num_feats; // Number of trees and the number of its features int *tree_size; // Size of each tree (in spels) float *tree_sal; // Mean saliency value of each tree float **tree_feats; // Mean feature vector of each tree iftBMap **tree_adj; // Tree adjacency relation } _iftForestStats; /*****************************************************************************\ * * PUBLIC STRUCTS * \*****************************************************************************/ struct ift_odisf_alg { bool use_diag_adj; // Use diagonal adjacents (i.e., 8-adjacency)? int n0, nf; // Initial number of seeds and final quantity of superspels float *saliency; // Normalized object saliency values (if they are provided) iftMImage *mimg; // Multiband image/video iftBMap *mask; // Mask indicating the ROI (if it exists) iftODISFSampl sampl_opt; // Seed sampling option }; /*****************************************************************************\ * * PRIVATE FUNCTIONS * \*****************************************************************************/ //===========================================================================// // GENERAL //===========================================================================// /* Computes the L2-norm (a.k.a. Euclidean distance) between two feature vectors in the same space (i.e., have the same number of features) */ inline double _iftEuclDist (const float *feat_a, const float *feat_b, const int num_feats) { #if IFT_DEBUG //-----------------------------------------------------------// assert(feat_a != NULL); assert(feat_b != NULL); assert(num_feats > 0); #endif //------------------------------------------------------------------// double dist; dist = 0; for(int j = 0; j < num_feats; ++j) // L2-norm dist += (feat_a[j] - feat_b[j]) * (feat_a[j] - feat_b[j]); dist = sqrtf(dist); return dist; } /* Creates a label image given an IFT id map generated during segmentation. */ iftImage *_iftCreateLabelImageFromIdMap (const iftODISF *odisf, const iftIntArray *seeds, const _iftIFTData *iftdata) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); assert(seeds != NULL); assert(iftdata != NULL); #endif //------------------------------------------------------------------// int label; iftImage *label_img; label_img = iftCreateImage(odisf->mimg->xsize, odisf->mimg->ysize, odisf->mimg->zsize); label = 1; // 0 is for the background for(long i = 0; i < seeds->n; ++i) label_img->val[seeds->val[i]] = label++; // Assign unique label #if IFT_OMP //-------------------------------------------------------------// #pragma omp parallel for #endif //------------------------------------------------------------------// for(int p = 0; p < label_img->n; ++p) // For each spel { int seed_id; seed_id = iftdata->id_map[p]; if(seed_id != IFT_NIL) // If it is not in the background label_img->val[p] = label_img->val[seeds->val[seed_id]];// Copy root label } return label_img; } //===========================================================================// // IFT DATA //===========================================================================// /* Creates a new empty IFT data container whose mappings' sizes are defined by the number of spels given */ _iftIFTData *_iftCreateIFTData (const int num_spels) { #if IFT_DEBUG //-----------------------------------------------------------// assert(num_spels > 0); #endif //------------------------------------------------------------------// _iftIFTData *iftdata; iftdata = malloc(sizeof(_iftIFTData)); assert(iftdata != NULL); iftdata->num_spels = num_spels; iftdata->id_map = calloc(num_spels, sizeof(int)); assert(iftdata->id_map != NULL); iftdata->pred_map = calloc(num_spels, sizeof(int)); assert(iftdata->pred_map != NULL); iftdata->cost_map = calloc(num_spels, sizeof(double)); assert(iftdata->cost_map != NULL); return iftdata; } /* Deallocates the memory of the given object and sets it to NULL */ void _iftDestroyIFTData (_iftIFTData **iftdata) { #if IFT_DEBUG //-----------------------------------------------------------// assert(iftdata != NULL); assert(*iftdata != NULL); #endif //------------------------------------------------------------------// free((*iftdata)->id_map); free((*iftdata)->pred_map); free((*iftdata)->cost_map); free(*iftdata); (*iftdata) = NULL; } /* Resets the IFT mappings to their initial (pre-IFT) values */ void _iftResetIFTData (const iftODISF *odisf, _iftIFTData **iftdata) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); assert(iftdata != NULL); assert(*iftdata != NULL); #endif //------------------------------------------------------------------// #if IFT_OMP //-------------------------------------------------------------// #pragma omp parallel for #endif //------------------------------------------------------------------// for(int p = 0; p < odisf->mimg->n; ++p) // For each spel { (*iftdata)->id_map[p] = IFT_NIL; // If p is not in the background, such (*iftdata)->pred_map[p] = IFT_NIL; // values will surely be changed // If a mask was not provided OR it is not a forbidden spel if(odisf->mask == NULL || iftBMapValue(odisf->mask, p) == true) (*iftdata)->cost_map[p] = IFT_INFINITY_DBL; // Exposed to conquering else // Then, it is forbidden (*iftdata)->cost_map[p] = IFT_INFINITY_DBL_NEG; // Safe from conquering } } //===========================================================================// // FOREST STATISTICS //===========================================================================// /* Creates an empty IFT forest statistics object based on the IFT data generated in the segmentation and its inputs. */ _iftForestStats *_iftCreateForestStats (const iftODISF *odisf, const _iftIFTData *iftdata, const iftIntArray *seeds) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); assert(iftdata != NULL); assert(seeds != NULL); #endif //------------------------------------------------------------------// _iftForestStats *forstats; forstats = malloc(sizeof(_iftForestStats)); assert(forstats != NULL); forstats->num_trees = (int)seeds->n; forstats->num_feats = odisf->mimg->m; forstats->tree_size = calloc(forstats->num_trees, sizeof(int)); assert(forstats->tree_size != NULL); forstats->tree_sal = calloc(forstats->num_trees, sizeof(float)); assert(forstats->tree_sal != NULL); forstats->tree_feats = calloc(forstats->num_trees, sizeof(float*)); assert(forstats->tree_feats != NULL); forstats->tree_adj = calloc(forstats->num_trees, sizeof(iftBMap*)); assert(forstats->tree_adj != NULL); #if IFT_OMP //-------------------------------------------------------------// #pragma omp parallel for #endif //------------------------------------------------------------------// for(long i = 0; i < seeds->n; ++i) // For each seed/tree { forstats->tree_feats[i] = calloc(forstats->num_feats, sizeof(float)); assert(forstats->tree_feats[i] != NULL); forstats->tree_adj[i] = iftCreateBMap(forstats->num_trees); assert(forstats->tree_adj[i] != NULL); } return forstats; } /* Deallocates the memory of the given object and sets it to NULL */ void _iftDestroyForestStats (_iftForestStats **forstats) { #if IFT_DEBUG //-----------------------------------------------------------// assert(forstats != NULL); assert(*forstats != NULL); #endif //------------------------------------------------------------------// free((*forstats)->tree_size); free((*forstats)->tree_sal); for(int i = 0; i < (*forstats)->num_trees; ++i) // For each tree { if((*forstats)->tree_feats[i] != NULL) free((*forstats)->tree_feats[i]); if((*forstats)->tree_adj[i] != NULL) iftDestroyBMap(&((*forstats)->tree_adj[i])); } free((*forstats)->tree_feats); free((*forstats)->tree_adj); free(*forstats); (*forstats) = NULL; } /* Calculates the forest statistics object based on the IFT data generated in the segmentation and its inputs. */ _iftForestStats *_iftCalcForestStats (const iftODISF *odisf, const _iftIFTData *iftdata, const iftIntArray *seeds) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); assert(iftdata != NULL); assert(seeds != NULL); #endif //------------------------------------------------------------------// _iftForestStats *forstats; iftAdjRel *A; forstats = _iftCreateForestStats(odisf, iftdata, seeds); // Use the same adjacency as the one used in segmentation if(odisf->use_diag_adj == true) A = iftCircular(sqrtf(2.0)); else A = iftCircular(1.0); for(int p = 0; p < odisf->mimg->n; ++p) // For each spel { int seed_id; seed_id = iftdata->id_map[p]; if(seed_id != IFT_NIL) // If it is not in the background { iftVoxel p_vxl; p_vxl = iftMGetVoxelCoord(odisf->mimg, p); forstats->tree_size[seed_id]++; if(odisf->saliency != NULL) // If a saliency map was provided forstats->tree_sal[seed_id] += odisf->saliency[p]; for(int j = 0; j < odisf->mimg->m; ++j) // For each feature forstats->tree_feats[seed_id][j] += odisf->mimg->val[p][j]; for(int i = 1; i < A->n; ++i) // For each adjacent { iftVoxel adj_vxl; adj_vxl = iftGetAdjacentVoxel(A, p_vxl, i); // If it is within the image domain if(iftMValidVoxel(odisf->mimg, adj_vxl) == true) { int adj_idx, adj_seed_id; adj_idx = iftMGetVoxelIndex(odisf->mimg, adj_vxl); adj_seed_id = iftdata->id_map[adj_idx]; // If the adjacent is not in the background AND their labels differ // AND their trees were not already marked as adjacents if(adj_seed_id != IFT_NIL && seed_id != adj_seed_id && iftBMapValue(forstats->tree_adj[seed_id], adj_seed_id) == false) // They are adjacents iftBMapSet1(forstats->tree_adj[seed_id], adj_seed_id); } } } } for(long i = 0; i < seeds->n; ++i) // For each seed/tree { if(odisf->saliency != NULL) // If a saliency map was provided // Compute mean saliency forstats->tree_sal[i] /= (float)forstats->tree_size[i]; else forstats->tree_sal[i] = 1.0; // Then, all trees are relevant for(int j = 0; j < odisf->mimg->m; ++j) // For each feature // Compute mean feature forstats->tree_feats[i][j] /= (float)forstats->tree_size[i]; } iftDestroyAdjRel(&A); return forstats; } //===========================================================================// // SEED SAMPLING //===========================================================================// /* Samples the desired initial number of seeds by a grid scheme selection. If a candidate is within a forbidden location, it is not resampled. */ iftIntArray *_iftRunGridSampl (const iftODISF *odisf) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); #endif //------------------------------------------------------------------// int x0, xf, y0, yf; float xstride, ystride; iftSet *tmp_seeds; iftIntArray *seeds; // Calculate each axis' stride for equal distribution of seeds xstride = ystride = sqrtf(odisf->mimg->n/(float)odisf->n0); if(xstride < 1.0 || ystride < 1.0) // If jump size may fall in the same spel iftError("Excessive number of seeds!", "_iftRunGridSampl"); x0 = (int)(xstride/2.0); xf = odisf->mimg->xsize - 1; y0 = (int)(ystride/2.0); yf = odisf->mimg->ysize - 1; tmp_seeds = NULL; // Temporary storage for agglomerating the seed indexes for(int y = y0; y <= yf; y = (int)(y + ystride)) // For each y-index { for(int x = x0; x <= xf; x = (int)(x + xstride)) // For each x-index { int curr_idx; iftVoxel curr_vxl; curr_vxl.x = x; curr_vxl.y = y; curr_vxl.z = 0; // Create the seed voxel curr_idx = iftMGetVoxelIndex(odisf->mimg, curr_vxl); // Get its index // If a mask was not provided OR it is not a forbidden spel if(odisf->mask == NULL || iftBMapValue(odisf->mask, curr_idx) == true) iftInsertSet(&tmp_seeds, curr_idx); // Add it as a seed } } seeds = iftSetToArray(tmp_seeds); // Convert to an array for simplicity iftDestroySet(&tmp_seeds); return seeds; } /* Samples the desired initial number of seeds by random selection. If a candidate is within a forbidden location, it is resampled. */ iftIntArray *_iftRunRndSampl (const iftODISF *odisf) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); #endif //------------------------------------------------------------------// int num_sampled; iftBMap *marked; iftIntArray *seeds; seeds = iftCreateIntArray(odisf->n0); // Assured N0 seeds to be sampled marked = iftCreateBMap(odisf->mimg->n); // Marked indexes num_sampled = 0; while(num_sampled < odisf->n0) // Until the desired quantity is reached { int idx; idx = iftRandomInteger(0, odisf->mimg->n - 1); // If (a mask was not provided OR it is not a forbidden spel) AND // it was not selected as seed in a previous iteration if((odisf->mask == NULL || iftBMapValue(odisf->mask, idx) == true) && iftBMapValue(marked, idx) == false) { seeds->val[num_sampled] = idx; iftBMapSet1(marked, idx); num_sampled++; } // Then, such seed must be resampled to another position } iftDestroyBMap(&marked); return seeds; } /* Samples the initial seed set in accordance to the configuration given in parameter. */ iftIntArray* _iftSampleSeeds (const iftODISF *odisf) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); #endif //------------------------------------------------------------------// iftIntArray *seeds; seeds = NULL; // Sample the initial seed set if(odisf->sampl_opt == IFT_ODISF_SAMPL_GRID) seeds = _iftRunGridSampl(odisf); else if(odisf->sampl_opt == IFT_ODISF_SAMPL_RND) seeds = _iftRunRndSampl(odisf); else iftError("Unknown seed sampling option", "_iftSampleSeeds"); return seeds; } //===========================================================================// // IMAGE FORESTING TRANSFORM //===========================================================================// /* Runs the seed-restricted IFT considering the options defined in the parameter. Note that the IFT data is updated inplace. */ void _iftRunIFT (const iftODISF *odisf, const iftIntArray *seeds, _iftIFTData **iftdata) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); assert(seeds != NULL); assert(iftdata != NULL); assert(*iftdata != NULL); #endif //------------------------------------------------------------------// int *tree_size; float **seed_feats; iftAdjRel *A; iftDHeap *heap; // If it is permitted to consider the diagonal neighbors if(odisf->use_diag_adj == true) A = iftCircular(sqrtf(2.0)); else A = iftCircular(1.0); tree_size = calloc(seeds->n, sizeof(int)); assert(tree_size != NULL); // Get the seed features based on the user's selection of arc estimation seed_feats = calloc(seeds->n, sizeof(float*)); assert(seed_feats != NULL); for(long i = 0; i < seeds->n; ++i) // For each seed/tree { seed_feats[i] = calloc(odisf->mimg->m, sizeof(float)); assert(seed_feats[i] != NULL); } _iftResetIFTData(odisf, iftdata); // Clear the IFT data for a new iteration heap = iftCreateDHeap(odisf->mimg->n, (*iftdata)->cost_map); iftSetRemovalPolicyDHeap(heap, MINVALUE); // Place the avaliable seeds in the mappings for(long i = 0; i < seeds->n; ++i) // For each seed { int idx; idx = seeds->val[i]; (*iftdata)->cost_map[idx] = 0; // Assuring that seeds are 1st in line (*iftdata)->id_map[idx] = i; // A seed maps to its own id iftInsertDHeap(heap, idx); } while(iftEmptyDHeap(heap) == false) // While exists a spel to be evaluated { int p_idx, seed_id; float *feats; iftVoxel p_vxl; p_idx = iftRemoveDHeap(heap); p_vxl = iftMGetVoxelCoord(odisf->mimg, p_idx); seed_id = (*iftdata)->id_map[p_idx]; // Update the seed features for(int j = 0; j < odisf->mimg->m; ++j) // For each feature { seed_feats[seed_id][j] *= tree_size[seed_id]; // Get accumulated value seed_feats[seed_id][j] += odisf->mimg->val[p_idx][j]; // Add features seed_feats[seed_id][j] /= (float)(tree_size[seed_id] + 1); // Get mean } tree_size[seed_id]++; // Increase tree's size feats = seed_feats[seed_id]; // For readability for(int i = 1; i < A->n; ++i) // For each adjacent spel { iftVoxel adj_vxl; adj_vxl = iftGetAdjacentVoxel(A, p_vxl, i); // If it is within the image domain if(iftMValidVoxel(odisf->mimg, adj_vxl) == true) { int adj_idx; adj_idx = iftMGetVoxelIndex(odisf->mimg, adj_vxl); if(heap->color[adj_idx] != IFT_BLACK) // If it wasn't ordely removed { double arccost, pathcost; float *adj_feats; adj_feats = odisf->mimg->val[adj_idx]; arccost = _iftEuclDist(feats, adj_feats, odisf->mimg->m); // L2-Norm pathcost = iftMax((*iftdata)->cost_map[p_idx], arccost); // Fmax // Does the new path offer a lesser accumulated cost? if(pathcost < (*iftdata)->cost_map[adj_idx]) { if (heap->color[adj_idx] == IFT_GRAY) // If it is within the heap iftRemoveDHeapElem(heap, adj_idx); // Remove for updating (*iftdata)->id_map[adj_idx] = seed_id; // Mark as conquered by (*iftdata)->pred_map[adj_idx] = p_idx; // the current spel (*iftdata)->cost_map[adj_idx] = pathcost; // evaluated // Insert to be evaluated in the future iftInsertDHeap(heap, adj_idx); } } } } } for(long i = 0; i < seeds->n; ++i) // For each seed free(seed_feats[i]); free(seed_feats); free(tree_size); iftDestroyDHeap(&heap); iftDestroyAdjRel(&A); } //===========================================================================// // SEED REMOVAL //===========================================================================// /* Assigns a priority value to each seed based on its properties and based on its contrast to its adjacents (considering either saliency or color). If a saliency map is provided, then it becomes object-based. */ double *_iftCalcSeedPrio (const iftODISF *odisf, const _iftIFTData *iftdata, const iftIntArray *seeds) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); assert(seeds != NULL); assert(iftdata != NULL); #endif //------------------------------------------------------------------// double *prio; _iftForestStats *forstats; prio = calloc(seeds->n, sizeof(double)); // Calculate the statistics of the generated forest forstats = _iftCalcForestStats(odisf, iftdata, seeds); #if IFT_OMP //-------------------------------------------------------------// #pragma omp parallel for #endif //------------------------------------------------------------------// for(long i = 0; i < seeds->n; ++i) { double size_perc, min_color_grad, max_sal_grad; // Size percentage with respect to the image's size (in spels) size_perc = forstats->tree_size[i]/(float)odisf->mimg->n; max_sal_grad = 0.0; min_color_grad = IFT_INFINITY_DBL; for(int j = 0; j < forstats->num_trees; ++j) // For each seed/tree { double sal_grad, grad; if(iftBMapValue(forstats->tree_adj[i], j) == true)//If they are adjacents { // L2-Norm grad = _iftEuclDist(forstats->tree_feats[i], forstats->tree_feats[j], forstats->num_feats); // L1-Norm sal_grad = fabs(forstats->tree_sal[i] - forstats->tree_sal[j]); // Update values if(grad < min_color_grad) min_color_grad = grad; if(sal_grad > max_sal_grad) max_sal_grad = sal_grad; } // Then, do not consider in the computation } prio[i] = size_perc * min_color_grad; prio[i] *= iftMax(forstats->tree_sal[i], max_sal_grad); } _iftDestroyForestStats(&forstats); return prio; } /* Selects the desired quantity of seeds with highest relevance and returns them. */ iftIntArray *_iftRemSeeds (const iftODISF *odisf, const int ni, const _iftIFTData *iftdata, const iftIntArray *seeds) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); assert(seeds != NULL); assert(ni > 1 && ni <= seeds->n); #endif //------------------------------------------------------------------// double *prio; iftDHeap *heap; iftIntArray *new_seeds; // Compute the seed priority prio = _iftCalcSeedPrio(odisf, iftdata, seeds); heap = iftCreateDHeap(seeds->n, prio); iftSetRemovalPolicyDHeap(heap, MAXVALUE); // Select the most relevants for(long i = 0; i < seeds->n; ++i) // For each seed iftInsertDHeap(heap, i); // Insert with its respective priority new_seeds = iftCreateIntArray(ni); // Assured to select ni seeds for(long i = 0; i < ni; ++i) // For each seed selected { int seed_id; seed_id = iftRemoveDHeap(heap); // Remove the one with highest priority new_seeds->val[i] = seeds->val[seed_id]; // Add its index to the array } // The rest are discarted free(prio); iftDestroyDHeap(&heap); return new_seeds; } /*****************************************************************************\ * * PUBLIC FUNCTIONS * \*****************************************************************************/ //===========================================================================// // CONSTRUCTOR & DESTRUCTOR //===========================================================================// iftODISF *iftCreateODISF (const iftImage *img, const iftImage *mask, const iftImage *objsm) { #if IFT_DEBUG //-----------------------------------------------------------// assert(img != NULL); if(mask != NULL) iftVerifyImageDomains(img, mask, "iftCreateODISF"); if(objsm != NULL) iftVerifyImageDomains(img, objsm, "iftCreateODISF"); #endif //------------------------------------------------------------------// iftODISF *odisf; odisf = malloc(sizeof(*odisf)); assert(odisf != NULL); if(iftIsColorImage(img) == true) // If it is a colored image or video odisf->mimg = iftImageToMImage(img, LAB_CSPACE); // Set to CIELAB else // Then, deal with the luminosity values odisf->mimg = iftImageToMImage(img, GRAY_CSPACE); if(mask != NULL) // If a mask was provided odisf->mask = iftBinImageToBMap(mask); // Saves a lot of memory else odisf->mask = NULL; // Then, all spels are to be conquered if(objsm != NULL) // If a saliency map was provided { int max_sal, min_sal; iftMinMaxValues(objsm, &min_sal, &max_sal); // For normalizing the values odisf->saliency = calloc(objsm->n, sizeof(float)); assert(odisf->saliency != NULL); #if IFT_OMP //-----------------------------------------------------------// #pragma omp parallel for #endif //----------------------------------------------------------------// for(int p = 0; p < objsm->n; ++p) // For each spel { odisf->saliency[p] = (objsm->val[p] - min_sal); // Normalize saliency odisf->saliency[p] /= (float)(max_sal - min_sal); // to [0,1] } } else odisf->saliency = NULL; // Then, no object information is considered // Default values odisf->n0 = 8000; odisf->nf = 200; odisf->use_diag_adj = true; // Default configuration odisf->sampl_opt = IFT_ODISF_SAMPL_GRID; return odisf; } void iftDestroyODISF (iftODISF **odisf) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); assert(*odisf != NULL); #endif //------------------------------------------------------------------// iftDestroyMImage(&((*odisf)->mimg)); if((*odisf)->mask != NULL) iftDestroyBMap(&((*odisf)->mask)); if((*odisf)->saliency != NULL) free((*odisf)->mask); free(*odisf); (*odisf) = NULL; } //===========================================================================// // GETTERS //===========================================================================// inline int iftODISFGetN0 (const iftODISF *odisf) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); #endif //------------------------------------------------------------------// return odisf->n0; } inline int iftODISFGetNf (const iftODISF *odisf) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); #endif //------------------------------------------------------------------// return odisf->nf; } //===========================================================================// // SETTERS //===========================================================================// inline void iftODISFSetN0 (iftODISF **odisf, const int n0) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); assert(*odisf != NULL); assert(n0 >= 2 && n0 >= (*odisf)->nf); #endif //------------------------------------------------------------------// (*odisf)->n0 = n0; } inline void iftODISFSetNf (iftODISF **odisf, const int nf) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); assert(*odisf != NULL); assert(nf >= 2 && nf <= (*odisf)->n0); #endif //------------------------------------------------------------------// (*odisf)->nf = nf; } inline void iftODISFUseDiagAdj (iftODISF **odisf, const bool use) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); assert(*odisf != NULL); #endif //------------------------------------------------------------------// (*odisf)->use_diag_adj = use; } //===========================================================================// // SEED SAMPLING //===========================================================================// inline iftODISFSampl iftODISFGetSamplOpt (const iftODISF *odisf) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); #endif //------------------------------------------------------------------// return odisf->sampl_opt; } inline void iftODISFSetSamplOpt (iftODISF **odisf, const iftODISFSampl sampl_opt) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); assert(*odisf != NULL); #endif //------------------------------------------------------------------// (*odisf)->sampl_opt = sampl_opt; } //===========================================================================// // VERIFIERS //===========================================================================// inline bool iftODISFUsingDiagAdj (const iftODISF *odisf) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); #endif //------------------------------------------------------------------// return odisf->use_diag_adj; } //===========================================================================// // RUNNER //===========================================================================// iftImage *iftRunODISF (const iftODISF *odisf) { #if IFT_DEBUG //-----------------------------------------------------------// assert(odisf != NULL); #endif //------------------------------------------------------------------// int iter, real_n0, ni, ni_prev; iftIntArray *seeds, *old_seeds; iftImage *label_img; _iftIFTData *iftdata; old_seeds = NULL; seeds = _iftSampleSeeds(odisf); // Sample the initial seed set // Since the latter may not guarantee N0, we need to consider the REAL N0 // over the one desired by the user real_n0 = ni = (int)seeds->n; #if IFT_DEBUG //---------------------------------------------------------// fprintf(stderr, "iftRunODISF: Number of seeds = %ld\n", seeds->n); #endif //----------------------------------------------------------------// iftdata = _iftCreateIFTData(odisf->mimg->n); // Create an empty IFT data iter = 1; do { #if IFT_DEBUG //---------------------------------------------------------// fprintf(stderr, "iftRunODISF: Iteration %d\n", iter); #endif //----------------------------------------------------------------// // Segment image using the IFT _iftRunIFT(odisf, seeds, &iftdata); // Calculate the number of seeds to be selected (for the next iteration) ni_prev = ni; ni = iftMax(iftRound(real_n0 * exp(-iter)), odisf->nf); if(ni < ni_prev) // If it is not the last iteration { #if IFT_DEBUG //-------------------------------------------------------// fprintf(stderr, "iftRunODISF: Ni = %d\n", ni); #endif //--------------------------------------------------------------// // Select the Ni relevant seeds (and remove the others) if(old_seeds != NULL) iftDestroyIntArray(&old_seeds); old_seeds = seeds; seeds = _iftRemSeeds(odisf, ni, iftdata, old_seeds); iter++; } } while(ni < ni_prev); // Creates a label image based on the seed id's in the IFT's id map label_img = _iftCreateLabelImageFromIdMap(odisf, seeds, iftdata); _iftDestroyIFTData(&iftdata); iftDestroyIntArray(&seeds); return label_img; }
mesh.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> #include "utils.h" void set_num_threads(int num_threads) { if (num_threads>0) omp_set_num_threads(num_threads); } int get_num_threads() { //Calculate number of threads int num_threads=0; #pragma omp parallel { #pragma omp atomic num_threads++; } return num_threads; } int assign_cic(FLOAT* mesh, const int* nmesh, const FLOAT* positions, const FLOAT* weights, size_t npositions) { // Assign positions (weights) to mesh // Asumes periodic boundaries // Positions must be in [0,nmesh-1] const size_t nmeshz = nmesh[2]; const size_t nmeshyz = nmesh[2]*nmesh[1]; for (size_t ii=0; ii<npositions; ii++) { const FLOAT weight = weights[ii]; const FLOAT *pos = &(positions[ii*NDIM]); int ix0 = (int) pos[0]; int iy0 = (int) pos[1]; int iz0 = (int) pos[2]; if (ix0<0 || ix0>=nmesh[0] || iy0<0 || iy0>=nmesh[1] || iz0<0 || iz0>=nmesh[2]) { printf("Index out of range: (ix,iy,iz) = (%d,%d,%d) for (%.3f,%.3f,%.3f)\n",ix0,iy0,iz0,pos[0],pos[1],pos[2]); return -1; } FLOAT dx = pos[0] - ix0; FLOAT dy = pos[1] - iy0; FLOAT dz = pos[2] - iz0; size_t ixp = nmeshyz*((ix0+1) % nmesh[0]); size_t iyp = nmeshz*((iy0+1) % nmesh[1]); size_t izp = (iz0+1) % nmesh[2]; ix0 *= nmeshyz; iy0 *= nmeshz; mesh[ix0+iy0+iz0] += (1-dx)*(1-dy)*(1-dz)*weight; mesh[ix0+iy0+izp] += (1-dx)*(1-dy)*dz*weight; mesh[ix0+iyp+iz0] += (1-dx)*dy*(1-dz)*weight; mesh[ix0+iyp+izp] += (1-dx)*dy*dz*weight; mesh[ixp+iy0+iz0] += dx*(1-dy)*(1-dz)*weight; mesh[ixp+iy0+izp] += dx*(1-dy)*dz*weight; mesh[ixp+iyp+iz0] += dx*dy*(1-dz)*weight; mesh[ixp+iyp+izp] += dx*dy*dz*weight; } return 0; } int convolve(FLOAT* mesh, const int* nmesh, const FLOAT* kernel, const int* nkernel) { // Performs a Gaussian smoothing using brute-force convolution. // Asumes periodic boundaries FLOAT sumw = 0; size_t size = nkernel[0]*nkernel[1]*nkernel[2]; const size_t nkernelz = nkernel[2]; const size_t nkernelyz = nkernel[2]*nkernel[1]; for (size_t ii=0; ii<size; ii++) sumw += kernel[ii]; // Take a copy of the data we're smoothing. size = nmesh[0]*nmesh[1]*nmesh[2]; const size_t nmeshz = nmesh[2]; const size_t nmeshyz = nmesh[2]*nmesh[1]; FLOAT *ss = (FLOAT *) malloc(size*sizeof(FLOAT)); for (size_t ii=0; ii<size; ii++) ss[ii] = mesh[ii]; FLOAT rad[NDIM]; for (int idim=0; idim<NDIM; idim++) { rad[idim] = nkernel[idim] / 2; if (nkernel[idim] % 2 == 0) { printf("Kernel size must be odd"); free(ss); return -1; } } #pragma omp parallel for shared(mesh,ss,kernel) for (int ix=0; ix<nmesh[0]; ix++) { for (int iy=0; iy<nmesh[1]; iy++) { for (int iz=0; iz<nmesh[2]; iz++) { FLOAT sumd = 0; for (int dx=-rad[0]; dx<=rad[0]; dx++) { size_t iix = nmeshyz*((ix+dx+nmesh[0]) % nmesh[0]); size_t jjx = nkernelyz*(rad[0]+dx); for (int dy=-rad[1]; dy<=rad[1]; dy++) { size_t iiy = nmeshz*((iy+dy+nmesh[1]) % nmesh[1]); size_t jjy = nkernelz*(rad[1]+dy); for (int dz=-rad[2]; dz<=rad[2]; dz++) { int iiz = (iz+dz+nmesh[2]) % nmesh[2]; size_t ii = iix+iiy+iiz; size_t jj = jjx+jjy+rad[2]+dz; sumd += kernel[jj]*ss[ii]; } } } mesh[nmeshyz*ix+nmeshz*iy+iz] = sumd/sumw; } } } free(ss); return 0; } int smooth_gaussian(FLOAT* mesh, const int* nmesh, const FLOAT* smoothing_radius, const FLOAT nsigmas) { // Performs a Gaussian smoothing using brute-force convolution. // Now set up the smoothing stencil. // The number of grid points to search: >= nsigmas * smoothing_radius. int rad[NDIM], nkernel[NDIM]; FLOAT fact[NDIM]; for (int idim=0; idim<NDIM; idim++) { rad[idim] = (size_t) (nsigmas*smoothing_radius[idim]*nmesh[idim] + 1.0); nkernel[idim] = 2*rad[idim] + 1; fact[idim] = 1.0/(nmesh[idim]*smoothing_radius[idim])/(nmesh[idim]*smoothing_radius[idim]); } FLOAT *kernel = (FLOAT *) malloc(nkernel[0]*nkernel[1]*nkernel[2]*sizeof(FLOAT)); #pragma omp parallel for shared(kernel) for (int dx=-rad[0]; dx<=rad[0]; dx++) { for (int dy=-rad[1]; dy<=rad[1]; dy++) { for (int dz=-rad[2]; dz<=rad[2]; dz++) { size_t ii = nkernel[1]*nkernel[2]*(rad[0]+dx)+nkernel[0]*(dy+rad[1])+(dz+rad[2]); FLOAT r2 = fact[0]*dx*dx+fact[1]*dy*dy+fact[2]*dz*dz; if (r2 < nsigmas*nsigmas) kernel[ii] = exp(-r2/2); else kernel[ii] = 0; } } } convolve(mesh,nmesh,kernel,nkernel); free(kernel); return 0; } /* void smooth_fft_gaussian(FLOAT *mesh, const int* nmesh, const FLOAT* smoothing_radius) { // Performs a Gaussian smoothing using the FFTW library (v3), assumed to be // installed already. Rf is assumed to be in box units. // Make temporary vectors. FFTW uses double precision. size_t size = nmesh[0]*nmesh[1]*nmesh[2]; fftw_complex * meshk = (fftw_complex *) malloc(nmesh[0]*nmesh[1]*(nmesh[2]/2+1)*sizeof(fftw_complex)); // Generate the FFTW plan files. fftw_init_threads(); fftw_plan_with_nthreads(omp_get_max_threads()); fftw_plan fplan = fftw_plan_dft_r2c_3d(nmesh[0],nmesh[1],nmesh[2],mesh,meshk,FFTW_ESTIMATE); fftw_plan iplan = fftw_plan_dft_c2r_3d(nmesh[0],nmesh[1],nmesh[2],meshk,mesh,FFTW_ESTIMATE); fftw_execute(fplan); // Now multiply by the smoothing filter. FLOAT fact[NDIM]; for (int idim=0; idim<NDIM; idim++) fact[idim] = 0.5*smoothing_radius[idim]*smoothing_radius[idim]*(2*M_PI)*(2*M_PI); #pragma omp parallel for shared(meshk) for (int ix=0; ix<nmesh[0]; ix++) { int iix = (ix<=nmesh[0]/2) ? ix : ix-nmesh[0]; for (int iy=0; iy<nmesh[1]; iy++) { int iiy = (iy<=nmesh[1]/2) ? iy : iy-nmesh[1]; for (int iz=0; iz<nmesh[2]/2+1; iz++) { int iiz = iz; size_t ip = nmesh[1]*(nmesh[2]/2+1)*ix+(nmesh[2]/2+1)*iy+iz; FLOAT smth = exp(-fact[0]*iix*iix+fact[1]*iiy*iiy+fact[2]*iiz*iiz)); meshk[ip][0] *= smth; meshk[ip][1] *= smth; } } } meshk[0][0] = meshk[0][1] = 0; // Set the mean to zero. fftw_execute(iplan); #pragma omp parallel for shared(mesh) for (size_t ii=0; ii<size; ii++) mesh[ii] /= size; fftw_destroy_plan(fplan); fftw_destroy_plan(iplan); fftw_cleanup_threads(); free(meshk); } */ int read_finite_difference_cic(const FLOAT* mesh, const int* nmesh, const FLOAT* boxsize, const FLOAT* positions, FLOAT* shifts, size_t npositions) { // Computes the displacement field from mesh using second-order accurate // finite difference and shifts the data and randoms. // The displacements are pulled from the grid onto the positions of the // particles using CIC. // Positions must be in [0,nmesh-1] // Output is in boxsize unit const size_t nmeshz = nmesh[2]; const size_t nmeshyz = nmesh[2]*nmesh[1]; FLOAT cell[NDIM]; for (int idim=0; idim<NDIM; idim++) cell[idim] = 2.0*boxsize[idim]/nmesh[idim]; int flag = 0; #pragma omp parallel for shared(mesh,positions,shifts) for (size_t ii=0; ii<npositions; ii++) { if (flag) continue; // This is written out in gory detail both to make it easier to // see what's going on and to encourage the compiler to optimize // and vectorize the code as much as possible. const FLOAT *pos = &(positions[ii*NDIM]); int ix0 = (int) pos[0]; int iy0 = (int) pos[1]; int iz0 = (int) pos[2]; if (ix0<0 || ix0>=nmesh[0] || iy0<0 || iy0>=nmesh[1] || iz0<0 || iz0>=nmesh[2]) { printf("Index out of range: (ix,iy,iz) = (%d,%d,%d) for (%.3f,%.3f,%.3f)\n",ix0,iy0,iz0,pos[0],pos[1],pos[2]); flag = 1; continue; } FLOAT dx = pos[0] - ix0; FLOAT dy = pos[1] - iy0; FLOAT dz = pos[2] - iz0; size_t ixp = nmeshyz*((ix0+1) % nmesh[0]); size_t ixpp = nmeshyz*((ix0+2) % nmesh[0]); size_t ixm = nmeshyz*((ix0-1+nmesh[0]) % nmesh[0]); size_t iyp = nmeshz*((iy0+1) % nmesh[1]); size_t iypp = nmeshz*((iy0+2) % nmesh[1]); size_t iym = nmeshz*((iy0-1+nmesh[1]) % nmesh[1]); size_t izp = (iz0+1) % nmesh[2]; size_t izpp = (iz0+2) % nmesh[2]; size_t izm = (iz0-1+nmesh[2]) % nmesh[2]; ix0 *= nmeshyz; iy0 *= nmeshz; FLOAT px,py,pz,wt; wt = (1-dx)*(1-dy)*(1-dz); px = (mesh[ixp+iy0+iz0]-mesh[ixm+iy0+iz0])*wt; py = (mesh[ix0+iyp+iz0]-mesh[ix0+iym+iz0])*wt; pz = (mesh[ix0+iy0+izp]-mesh[ix0+iy0+izm])*wt; wt = dx*(1-dy)*(1-dz); px += (mesh[ixpp+iy0+iz0]-mesh[ix0+iy0+iz0])*wt; py += (mesh[ixp+iyp+iz0]-mesh[ixp+iym+iz0])*wt; pz += (mesh[ixp+iy0+izp]-mesh[ixp+iy0+izm])*wt; wt = (1-dx)*dy*(1-dz); px += (mesh[ixp+iyp+iz0]-mesh[ixm+iyp+iz0])*wt; py += (mesh[ix0+iypp+iz0]-mesh[ix0+iy0+iz0])*wt; pz += (mesh[ix0+iyp+izp]-mesh[ix0+iyp+izm])*wt; wt = (1-dx)*(1-dy)*dz; px += (mesh[ixp+iy0+izp]-mesh[ixm+iy0+izp])*wt; py += (mesh[ix0+iyp+izp]-mesh[ix0+iym+izp])*wt; pz += (mesh[ix0+iy0+izpp]-mesh[ix0+iy0+iz0])*wt; wt = dx*dy*(1-dz); px += (mesh[ixpp+iyp+iz0]-mesh[ix0+iyp+iz0])*wt; py += (mesh[ixp+iypp+iz0]-mesh[ixp+iy0+iz0])*wt; pz += (mesh[ixp+iyp+izp]-mesh[ixp+iyp+izm])*wt; wt = dx*(1-dy)*dz; px += (mesh[ixpp+iy0+izp]-mesh[ix0+iy0+izp])*wt; py += (mesh[ixp+iyp+izp]-mesh[ixp+iym+izp])*wt; pz += (mesh[ixp+iy0+izpp]-mesh[ixp+iy0+iz0])*wt; wt = (1-dx)*dy*dz; px += (mesh[ixp+iyp+izp]-mesh[ixm+iyp+izp])*wt; py += (mesh[ix0+iypp+izp]-mesh[ix0+iy0+izp])*wt; pz += (mesh[ix0+iyp+izpp]-mesh[ix0+iyp+iz0])*wt; wt = dx*dy*dz; px += (mesh[ixpp+iyp+izp]-mesh[ix0+iyp+izp])*wt; py += (mesh[ixp+iypp+izp]-mesh[ixp+iy0+izp])*wt; pz += (mesh[ixp+iyp+izpp]-mesh[ixp+iyp+iz0])*wt; FLOAT *sh = &(shifts[ii*NDIM]); //px *= boxsize[0]*boxsize[0]; //py *= boxsize[0]*boxsize[0]; //pz *= boxsize[0]*boxsize[0]; sh[0] = px/cell[0]; sh[1] = py/cell[1]; sh[2] = pz/cell[2]; } if (flag) return -1; return 0; } int read_cic(const FLOAT* mesh, const int* nmesh, const FLOAT* positions, FLOAT* shifts, size_t npositions) { // Positions must be in [0,nmesh-1] const size_t nmeshz = nmesh[2]; const size_t nmeshyz = nmesh[2]*nmesh[1]; int flag = 0; #pragma omp parallel for shared(mesh,positions,shifts,flag) for (size_t ii=0; ii<npositions; ii++) { if (flag) continue; const FLOAT *pos = &(positions[ii*NDIM]); int ix0 = (int) pos[0]; int iy0 = (int) pos[1]; int iz0 = (int) pos[2]; if (ix0<0 || ix0>=nmesh[0] || iy0<0 || iy0>=nmesh[1] || iz0<0 || iz0>=nmesh[2]) { printf("Index out of range: (ix,iy,iz) = (%d,%d,%d) for (%.3f,%.3f,%.3f)\n",ix0,iy0,iz0,pos[0],pos[1],pos[2]); flag = 1; continue; } FLOAT dx = pos[0] - ix0; FLOAT dy = pos[1] - iy0; FLOAT dz = pos[2] - iz0; size_t ixp = nmeshyz*((ix0+1) % nmesh[0]); size_t iyp = nmeshz*((iy0+1) % nmesh[1]); size_t izp = (iz0+1) % nmesh[2]; ix0 *= nmeshyz; iy0 *= nmeshz; FLOAT px; px = mesh[ix0+iy0+iz0]*(1-dx)*(1-dy)*(1-dz); px += mesh[ix0+iy0+izp]*(1-dx)*(1-dy)*dz; px += mesh[ix0+iyp+iz0]*(1-dx)*dy*(1-dz); px += mesh[ix0+iyp+izp]*(1-dx)*dy*dz; px += mesh[ixp+iy0+iz0]*dx*(1-dy)*(1-dz); px += mesh[ixp+iy0+izp]*dx*(1-dy)*dz; px += mesh[ixp+iyp+iz0]*dx*dy*(1-dz); px += mesh[ixp+iyp+izp]*dx*dy*dz; shifts[ii] = px; } if (flag) return -1; return 0; } /* int copy(FLOAT* input_array, FLOAT* output_array, const size_t size) { #pragma omp parallel for schedule(dynamic) shared(input_array, output_array) for (size_t ii=0; ii<size; ii++) output_array[ii] = input_array[ii]; return 0; } */ int copy(FLOAT* input_array, FLOAT* output_array, const size_t size) { int chunksize = 100000; #pragma omp parallel for schedule(static, chunksize) shared(input_array, output_array) for (size_t ii=0; ii<size; ii++) output_array[ii] = input_array[ii]; return 0; } int prod_sum(FLOAT* mesh, const int* nmesh, const FLOAT* coords, const int exp) { // We expand everything to help compiler // Slightly faster than a numpy code // NOTE: coords should list arrays to apply along z, y and x, in this order const size_t nmeshz = nmesh[2]; const size_t nmeshypz = nmesh[1] + nmesh[2]; const size_t nmeshyz = nmesh[2]*nmesh[1]; if (exp == -1) { #pragma omp parallel for shared(mesh) for (int ix=0; ix<nmesh[0]; ix++) { for (int iy=0; iy<nmesh[1]; iy++) { FLOAT xy = coords[nmeshz + iy] + coords[nmeshypz + ix]; size_t ixy = nmeshyz*ix + nmeshz*iy; for (int iz=0; iz<nmesh[2]; iz++) mesh[ixy + iz] /= (xy + coords[iz]); } } } else if (exp == 1) { #pragma omp parallel for shared(mesh) for (int ix=0; ix<nmesh[0]; ix++) { for (int iy=0; iy<nmesh[1]; iy++) { FLOAT xy = coords[nmeshz + iy] + coords[nmeshypz + ix]; size_t ixy = nmeshyz*ix + nmeshz*iy; for (int iz=0; iz<nmesh[2]; iz++) mesh[ixy + iz] *= (xy + coords[iz]); } } } else { #pragma omp parallel for shared(mesh) for (int ix=0; ix<nmesh[0]; ix++) { for (int iy=0; iy<nmesh[1]; iy++) { FLOAT xy = coords[nmeshz + iy] + coords[nmeshypz + ix]; size_t ixy = nmeshyz*ix + nmeshz*iy; for (int iz=0; iz<nmesh[2]; iz++) mesh[ixy + iz] *= POW((xy + coords[iz]), exp); } } } return 0.; }
hermv_c_csc_u_hi.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include <memory.h> #include "alphasparse/opt.h" #ifdef _OPENMP #include <omp.h> #endif static alphasparse_status_t hermv_csc_u_hi_unroll(const ALPHA_Number alpha, const ALPHA_SPMAT_CSC *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { const ALPHA_INT m = A->rows; const ALPHA_INT n = A->cols; const ALPHA_INT num_threads = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT i = 0; i < m; ++i) { ALPHA_Number tmp1, tmp2; alpha_mul(tmp1, beta, y[i]); alpha_mul(tmp2, alpha, x[i]); alpha_add(y[i], tmp1, tmp2); } // each thread has a y_local ALPHA_Number **y_local = alpha_memalign(num_threads * sizeof(ALPHA_Number *), DEFAULT_ALIGNMENT); #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT i = 0; i < num_threads; i++) { y_local[i] = alpha_memalign(m * sizeof(ALPHA_Number), DEFAULT_ALIGNMENT); memset(y_local[i], '\0', sizeof(ALPHA_Number) * m); } #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT i = 0; i < m; ++i) { ALPHA_INT tid = alpha_get_thread_id(); ALPHA_INT ais = A->cols_start[i]; ALPHA_INT aie = A->cols_end[i]; ALPHA_INT start = ais; ALPHA_INT end = alpha_lower_bound(&A->row_indx[ais], &A->row_indx[aie], i) - A->row_indx; if(end > ais && A->row_indx[end-1] == i){ end -= 1; } const ALPHA_INT* A_row = &A->row_indx[ais]; const ALPHA_Number* A_val = &A->values[ais]; ALPHA_INT ai = 0; ALPHA_INT ail = end - start; ALPHA_Number alpha_xi, tmp; alpha_mul(alpha_xi, alpha, x[i]); for(; ai < ail-3; ai+=4) { ALPHA_Number av0 = A_val[ai]; ALPHA_Number av1 = A_val[ai + 1]; ALPHA_Number av2 = A_val[ai + 2]; ALPHA_Number av3 = A_val[ai + 3]; ALPHA_INT ar0 = A_row[ai]; ALPHA_INT ar1 = A_row[ai + 1]; ALPHA_INT ar2 = A_row[ai + 2]; ALPHA_INT ar3 = A_row[ai + 3]; alpha_madde(y_local[tid][ar0], av0, alpha_xi); alpha_madde(y_local[tid][ar1], av1, alpha_xi); alpha_madde(y_local[tid][ar2], av2, alpha_xi); alpha_madde(y_local[tid][ar3], av3, alpha_xi); alpha_mul_3c(tmp, alpha, av0); alpha_madde(y_local[tid][i], tmp, x[ar0]); alpha_mul_3c(tmp, alpha, av1); alpha_madde(y_local[tid][i], tmp, x[ar1]); alpha_mul_3c(tmp, alpha, av2); alpha_madde(y_local[tid][i], tmp, x[ar2]); alpha_mul_3c(tmp, alpha, av3); alpha_madde(y_local[tid][i], tmp, x[ar3]); } for(; ai < ail; ai++) { ALPHA_Number av = A_val[ai]; ALPHA_INT ar = A_row[ai]; alpha_madde(y_local[tid][ar], av, alpha_xi); alpha_mul_3c(tmp, alpha, av); alpha_madde(y_local[tid][i], tmp, x[ar]); } } #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT col = 0; col < m; col++) for(ALPHA_INT i = 0; i < num_threads; i++) { alpha_add(y[col], y[col], y_local[i][col]); } for(ALPHA_INT i = 0; i < num_threads; i++) { alpha_free(y_local[i]); } alpha_free(y_local); return ALPHA_SPARSE_STATUS_SUCCESS; } alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_CSC *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { return hermv_csc_u_hi_unroll(alpha, A, x, beta, y); }
draw.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD RRRR AAA W W % % D D R R A A W W % % D D RRRR AAAAA W W W % % D D R RN A A WW WW % % DDDD R R A A W W % % % % % % MagickCore Image Drawing Methods % % % % % % Software Design % % Cristy % % July 1998 % % % % % % Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Bill Radcliffe of Corbis (www.corbis.com) contributed the polygon % rendering code based on Paul Heckbert's "Concave Polygon Scan Conversion", % Graphics Gems, 1990. Leonard Rosenthal and David Harr of Appligent % (www.appligent.com) contributed the dash pattern, linecap stroking % algorithm, and minor rendering improvements. % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/annotate.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/draw-private.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resource_.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/token.h" #include "MagickCore/transform-private.h" #include "MagickCore/utility.h" /* Define declarations. */ #define BezierQuantum 200 #define PrimitiveExtentPad 2053.0 #define MaxBezierCoordinates 67108864 #define ThrowPointExpectedException(token,exception) \ { \ (void) ThrowMagickException(exception,GetMagickModule(),DrawError, \ "NonconformingDrawingPrimitiveDefinition","`%s'",token); \ status=MagickFalse; \ break; \ } /* Typedef declarations. */ typedef struct _EdgeInfo { SegmentInfo bounds; double scanline; PointInfo *points; size_t number_points; ssize_t direction; MagickBooleanType ghostline; size_t highwater; } EdgeInfo; typedef struct _ElementInfo { double cx, cy, major, minor, angle; } ElementInfo; typedef struct _MVGInfo { PrimitiveInfo **primitive_info; size_t *extent; ssize_t offset; PointInfo point; ExceptionInfo *exception; } MVGInfo; typedef struct _PolygonInfo { EdgeInfo *edges; size_t number_edges; } PolygonInfo; typedef enum { MoveToCode, OpenCode, GhostlineCode, LineToCode, EndCode } PathInfoCode; typedef struct _PathInfo { PointInfo point; PathInfoCode code; } PathInfo; /* Forward declarations. */ static Image *DrawClippingMask(Image *,const DrawInfo *,const char *,const char *, ExceptionInfo *); static MagickBooleanType DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *, ExceptionInfo *), RenderMVGContent(Image *,const DrawInfo *,const size_t,ExceptionInfo *), TraceArc(MVGInfo *,const PointInfo,const PointInfo,const PointInfo), TraceArcPath(MVGInfo *,const PointInfo,const PointInfo,const PointInfo, const double,const MagickBooleanType,const MagickBooleanType), TraceBezier(MVGInfo *,const size_t), TraceCircle(MVGInfo *,const PointInfo,const PointInfo), TraceEllipse(MVGInfo *,const PointInfo,const PointInfo,const PointInfo), TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo), TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo), TraceRoundRectangle(MVGInfo *,const PointInfo,const PointInfo,PointInfo), TraceSquareLinecap(PrimitiveInfo *,const size_t,const double); static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *,const PrimitiveInfo *,ExceptionInfo *); static ssize_t TracePath(MVGInfo *,const char *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireDrawInfo() returns a DrawInfo structure properly initialized. % % The format of the AcquireDrawInfo method is: % % DrawInfo *AcquireDrawInfo(void) % */ MagickExport DrawInfo *AcquireDrawInfo(void) { DrawInfo *draw_info; draw_info=(DrawInfo *) AcquireCriticalMemory(sizeof(*draw_info)); GetDrawInfo((ImageInfo *) NULL,draw_info); return(draw_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneDrawInfo() makes a copy of the given draw_info structure. If NULL % is specified, a new DrawInfo structure is created initialized to default % values. % % The format of the CloneDrawInfo method is: % % DrawInfo *CloneDrawInfo(const ImageInfo *image_info, % const DrawInfo *draw_info) % % A description of each parameter follows: % % o image_info: the image info. % % o draw_info: the draw info. % */ MagickExport DrawInfo *CloneDrawInfo(const ImageInfo *image_info, const DrawInfo *draw_info) { DrawInfo *clone_info; ExceptionInfo *exception; clone_info=(DrawInfo *) AcquireCriticalMemory(sizeof(*clone_info)); GetDrawInfo(image_info,clone_info); if (draw_info == (DrawInfo *) NULL) return(clone_info); exception=AcquireExceptionInfo(); if (draw_info->id != (char *) NULL) (void) CloneString(&clone_info->id,draw_info->id); if (draw_info->primitive != (char *) NULL) (void) CloneString(&clone_info->primitive,draw_info->primitive); if (draw_info->geometry != (char *) NULL) (void) CloneString(&clone_info->geometry,draw_info->geometry); clone_info->compliance=draw_info->compliance; clone_info->viewbox=draw_info->viewbox; clone_info->affine=draw_info->affine; clone_info->gravity=draw_info->gravity; clone_info->fill=draw_info->fill; clone_info->stroke=draw_info->stroke; clone_info->stroke_width=draw_info->stroke_width; if (draw_info->fill_pattern != (Image *) NULL) clone_info->fill_pattern=CloneImage(draw_info->fill_pattern,0,0,MagickTrue, exception); if (draw_info->stroke_pattern != (Image *) NULL) clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0, MagickTrue,exception); clone_info->stroke_antialias=draw_info->stroke_antialias; clone_info->text_antialias=draw_info->text_antialias; clone_info->fill_rule=draw_info->fill_rule; clone_info->linecap=draw_info->linecap; clone_info->linejoin=draw_info->linejoin; clone_info->miterlimit=draw_info->miterlimit; clone_info->dash_offset=draw_info->dash_offset; clone_info->decorate=draw_info->decorate; clone_info->compose=draw_info->compose; if (draw_info->text != (char *) NULL) (void) CloneString(&clone_info->text,draw_info->text); if (draw_info->font != (char *) NULL) (void) CloneString(&clone_info->font,draw_info->font); if (draw_info->metrics != (char *) NULL) (void) CloneString(&clone_info->metrics,draw_info->metrics); if (draw_info->family != (char *) NULL) (void) CloneString(&clone_info->family,draw_info->family); clone_info->style=draw_info->style; clone_info->stretch=draw_info->stretch; clone_info->weight=draw_info->weight; if (draw_info->encoding != (char *) NULL) (void) CloneString(&clone_info->encoding,draw_info->encoding); clone_info->pointsize=draw_info->pointsize; clone_info->kerning=draw_info->kerning; clone_info->interline_spacing=draw_info->interline_spacing; clone_info->interword_spacing=draw_info->interword_spacing; clone_info->direction=draw_info->direction; if (draw_info->density != (char *) NULL) (void) CloneString(&clone_info->density,draw_info->density); clone_info->align=draw_info->align; clone_info->undercolor=draw_info->undercolor; clone_info->border_color=draw_info->border_color; if (draw_info->server_name != (char *) NULL) (void) CloneString(&clone_info->server_name,draw_info->server_name); if (draw_info->dash_pattern != (double *) NULL) { ssize_t x; for (x=0; fabs(draw_info->dash_pattern[x]) >= MagickEpsilon; x++) ; clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2*x+2), sizeof(*clone_info->dash_pattern)); if (clone_info->dash_pattern == (double *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) memset(clone_info->dash_pattern,0,(size_t) (2*x+2)* sizeof(*clone_info->dash_pattern)); (void) memcpy(clone_info->dash_pattern,draw_info->dash_pattern,(size_t) (x+1)*sizeof(*clone_info->dash_pattern)); } clone_info->gradient=draw_info->gradient; if (draw_info->gradient.stops != (StopInfo *) NULL) { size_t number_stops; number_stops=clone_info->gradient.number_stops; clone_info->gradient.stops=(StopInfo *) AcquireQuantumMemory((size_t) number_stops,sizeof(*clone_info->gradient.stops)); if (clone_info->gradient.stops == (StopInfo *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) memcpy(clone_info->gradient.stops,draw_info->gradient.stops, (size_t) number_stops*sizeof(*clone_info->gradient.stops)); } clone_info->bounds=draw_info->bounds; clone_info->fill_alpha=draw_info->fill_alpha; clone_info->stroke_alpha=draw_info->stroke_alpha; clone_info->element_reference=draw_info->element_reference; clone_info->clip_path=draw_info->clip_path; clone_info->clip_units=draw_info->clip_units; if (draw_info->clip_mask != (char *) NULL) (void) CloneString(&clone_info->clip_mask,draw_info->clip_mask); if (draw_info->clipping_mask != (Image *) NULL) clone_info->clipping_mask=CloneImage(draw_info->clipping_mask,0,0, MagickTrue,exception); if (draw_info->composite_mask != (Image *) NULL) clone_info->composite_mask=CloneImage(draw_info->composite_mask,0,0, MagickTrue,exception); clone_info->render=draw_info->render; clone_info->debug=IsEventLogging(); exception=DestroyExceptionInfo(exception); return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n v e r t P a t h T o P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConvertPathToPolygon() converts a path to the more efficient sorted % rendering form. % % The format of the ConvertPathToPolygon method is: % % PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info, % ExceptionInfo *excetion) % % A description of each parameter follows: % % o ConvertPathToPolygon() returns the path in a more efficient sorted % rendering form of type PolygonInfo. % % o draw_info: Specifies a pointer to an DrawInfo structure. % % o path_info: Specifies a pointer to an PathInfo structure. % % */ static PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info) { ssize_t i; if (polygon_info->edges != (EdgeInfo *) NULL) { for (i=0; i < (ssize_t) polygon_info->number_edges; i++) if (polygon_info->edges[i].points != (PointInfo *) NULL) polygon_info->edges[i].points=(PointInfo *) RelinquishMagickMemory(polygon_info->edges[i].points); polygon_info->edges=(EdgeInfo *) RelinquishMagickMemory( polygon_info->edges); } return((PolygonInfo *) RelinquishMagickMemory(polygon_info)); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int DrawCompareEdges(const void *p_edge,const void *q_edge) { #define DrawCompareEdge(p,q) \ { \ if (((p)-(q)) < 0.0) \ return(-1); \ if (((p)-(q)) > 0.0) \ return(1); \ } const PointInfo *p, *q; /* Edge sorting for right-handed coordinate system. */ p=((const EdgeInfo *) p_edge)->points; q=((const EdgeInfo *) q_edge)->points; DrawCompareEdge(p[0].y,q[0].y); DrawCompareEdge(p[0].x,q[0].x); DrawCompareEdge((p[1].x-p[0].x)*(q[1].y-q[0].y),(p[1].y-p[0].y)* (q[1].x-q[0].x)); DrawCompareEdge(p[1].y,q[1].y); DrawCompareEdge(p[1].x,q[1].x); return(0); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static void LogPolygonInfo(const PolygonInfo *polygon_info) { EdgeInfo *p; ssize_t i, j; (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin active-edge"); p=polygon_info->edges; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) { (void) LogMagickEvent(DrawEvent,GetMagickModule()," edge %.20g:", (double) i); (void) LogMagickEvent(DrawEvent,GetMagickModule()," direction: %s", p->direction != MagickFalse ? "down" : "up"); (void) LogMagickEvent(DrawEvent,GetMagickModule()," ghostline: %s", p->ghostline != MagickFalse ? "transparent" : "opaque"); (void) LogMagickEvent(DrawEvent,GetMagickModule(), " bounds: %g,%g - %g,%g",p->bounds.x1,p->bounds.y1, p->bounds.x2,p->bounds.y2); for (j=0; j < (ssize_t) p->number_points; j++) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %g,%g", p->points[j].x,p->points[j].y); p++; } (void) LogMagickEvent(DrawEvent,GetMagickModule()," end active-edge"); } static void ReversePoints(PointInfo *points,const size_t number_points) { PointInfo point; ssize_t i; for (i=0; i < (ssize_t) (number_points >> 1); i++) { point=points[i]; points[i]=points[number_points-(i+1)]; points[number_points-(i+1)]=point; } } static PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info, ExceptionInfo *exception) { long direction, next_direction; PointInfo point, *points; PolygonInfo *polygon_info; SegmentInfo bounds; ssize_t i, n; MagickBooleanType ghostline; size_t edge, number_edges, number_points; /* Convert a path to the more efficient sorted rendering form. */ polygon_info=(PolygonInfo *) AcquireMagickMemory(sizeof(*polygon_info)); if (polygon_info == (PolygonInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return((PolygonInfo *) NULL); } number_edges=16; polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory(number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } (void) memset(polygon_info->edges,0,number_edges* sizeof(*polygon_info->edges)); direction=0; edge=0; ghostline=MagickFalse; n=0; number_points=0; points=(PointInfo *) NULL; (void) memset(&point,0,sizeof(point)); (void) memset(&bounds,0,sizeof(bounds)); polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=0.0; polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) direction; polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->number_edges=0; for (i=0; path_info[i].code != EndCode; i++) { if ((path_info[i].code == MoveToCode) || (path_info[i].code == OpenCode) || (path_info[i].code == GhostlineCode)) { /* Move to. */ if ((points != (PointInfo *) NULL) && (n >= 2)) { if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); points=(PointInfo *) RelinquishMagickMemory(points); return(DestroyPolygonInfo(polygon_info)); } } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; points=(PointInfo *) NULL; ghostline=MagickFalse; edge++; polygon_info->number_edges=edge; } if (points == (PointInfo *) NULL) { number_points=16; points=(PointInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } } ghostline=path_info[i].code == GhostlineCode ? MagickTrue : MagickFalse; point=path_info[i].point; points[0]=point; bounds.x1=point.x; bounds.x2=point.x; direction=0; n=1; continue; } /* Line to. */ next_direction=((path_info[i].point.y > point.y) || ((fabs(path_info[i].point.y-point.y) < MagickEpsilon) && (path_info[i].point.x > point.x))) ? 1 : -1; if ((points != (PointInfo *) NULL) && (direction != 0) && (direction != next_direction)) { /* New edge. */ point=points[n-1]; if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); points=(PointInfo *) RelinquishMagickMemory(points); return(DestroyPolygonInfo(polygon_info)); } } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; polygon_info->number_edges=edge+1; points=(PointInfo *) NULL; number_points=16; points=(PointInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } n=1; ghostline=MagickFalse; points[0]=point; bounds.x1=point.x; bounds.x2=point.x; edge++; } direction=next_direction; if (points == (PointInfo *) NULL) continue; if (n == (ssize_t) number_points) { number_points<<=1; points=(PointInfo *) ResizeQuantumMemory(points,(size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } } point=path_info[i].point; points[n]=point; if (point.x < bounds.x1) bounds.x1=point.x; if (point.x > bounds.x2) bounds.x2=point.x; n++; } if (points != (PointInfo *) NULL) { if (n < 2) points=(PointInfo *) RelinquishMagickMemory(points); else { if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; points=(PointInfo *) NULL; ghostline=MagickFalse; edge++; polygon_info->number_edges=edge; } } polygon_info->number_edges=edge; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(polygon_info->edges, polygon_info->number_edges,sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } for (i=0; i < (ssize_t) polygon_info->number_edges; i++) { EdgeInfo *edge_info; edge_info=polygon_info->edges+i; edge_info->points=(PointInfo *) ResizeQuantumMemory(edge_info->points, edge_info->number_points,sizeof(*edge_info->points)); if (edge_info->points == (PointInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonInfo(polygon_info)); } } qsort(polygon_info->edges,(size_t) polygon_info->number_edges, sizeof(*polygon_info->edges),DrawCompareEdges); if (IsEventLogging() != MagickFalse) LogPolygonInfo(polygon_info); return(polygon_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n v e r t P r i m i t i v e T o P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConvertPrimitiveToPath() converts a PrimitiveInfo structure into a vector % path structure. % % The format of the ConvertPrimitiveToPath method is: % % PathInfo *ConvertPrimitiveToPath(const DrawInfo *draw_info, % const PrimitiveInfo *primitive_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o ConvertPrimitiveToPath() returns a vector path structure of type % PathInfo. % % o draw_info: a structure of type DrawInfo. % % o primitive_info: Specifies a pointer to an PrimitiveInfo structure. % */ static void LogPathInfo(const PathInfo *path_info) { const PathInfo *p; (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin vector-path"); for (p=path_info; p->code != EndCode; p++) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %g,%g %s",p->point.x,p->point.y,p->code == GhostlineCode ? "moveto ghostline" : p->code == OpenCode ? "moveto open" : p->code == MoveToCode ? "moveto" : p->code == LineToCode ? "lineto" : "?"); (void) LogMagickEvent(DrawEvent,GetMagickModule()," end vector-path"); } static PathInfo *ConvertPrimitiveToPath(const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { MagickBooleanType closed_subpath; PathInfo *path_info; PathInfoCode code; PointInfo p, q; ssize_t i, n; ssize_t coordinates, start; /* Converts a PrimitiveInfo structure into a vector path structure. */ switch (primitive_info->primitive) { case AlphaPrimitive: case ColorPrimitive: case ImagePrimitive: case PointPrimitive: case TextPrimitive: return((PathInfo *) NULL); default: break; } for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; path_info=(PathInfo *) AcquireQuantumMemory((size_t) (3UL*i+1UL), sizeof(*path_info)); if (path_info == (PathInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return((PathInfo *) NULL); } coordinates=0; closed_subpath=MagickFalse; n=0; p.x=(-1.0); p.y=(-1.0); q.x=(-1.0); q.y=(-1.0); start=0; for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { code=LineToCode; if (coordinates <= 0) { /* New subpath. */ coordinates=(ssize_t) primitive_info[i].coordinates; p=primitive_info[i].point; start=n; code=MoveToCode; closed_subpath=primitive_info[i].closed_subpath; } coordinates--; if ((code == MoveToCode) || (coordinates <= 0) || (fabs(q.x-primitive_info[i].point.x) >= MagickEpsilon) || (fabs(q.y-primitive_info[i].point.y) >= MagickEpsilon)) { /* Eliminate duplicate points. */ path_info[n].code=code; path_info[n].point=primitive_info[i].point; q=primitive_info[i].point; n++; } if (coordinates > 0) continue; /* next point in current subpath */ if (closed_subpath != MagickFalse) { closed_subpath=MagickFalse; continue; } /* Mark the p point as open if the subpath is not closed. */ path_info[start].code=OpenCode; path_info[n].code=GhostlineCode; path_info[n].point=primitive_info[i].point; n++; path_info[n].code=LineToCode; path_info[n].point=p; n++; } path_info[n].code=EndCode; path_info[n].point.x=0.0; path_info[n].point.y=0.0; if (IsEventLogging() != MagickFalse) LogPathInfo(path_info); path_info=(PathInfo *) ResizeQuantumMemory(path_info,(size_t) (n+1), sizeof(*path_info)); return(path_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyDrawInfo() deallocates memory associated with an DrawInfo structure. % % The format of the DestroyDrawInfo method is: % % DrawInfo *DestroyDrawInfo(DrawInfo *draw_info) % % A description of each parameter follows: % % o draw_info: the draw info. % */ MagickExport DrawInfo *DestroyDrawInfo(DrawInfo *draw_info) { assert(draw_info != (DrawInfo *) NULL); if (draw_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info->signature == MagickCoreSignature); if (draw_info->id != (char *) NULL) draw_info->id=DestroyString(draw_info->id); if (draw_info->primitive != (char *) NULL) draw_info->primitive=DestroyString(draw_info->primitive); if (draw_info->text != (char *) NULL) draw_info->text=DestroyString(draw_info->text); if (draw_info->geometry != (char *) NULL) draw_info->geometry=DestroyString(draw_info->geometry); if (draw_info->fill_pattern != (Image *) NULL) draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern); if (draw_info->stroke_pattern != (Image *) NULL) draw_info->stroke_pattern=DestroyImage(draw_info->stroke_pattern); if (draw_info->font != (char *) NULL) draw_info->font=DestroyString(draw_info->font); if (draw_info->metrics != (char *) NULL) draw_info->metrics=DestroyString(draw_info->metrics); if (draw_info->family != (char *) NULL) draw_info->family=DestroyString(draw_info->family); if (draw_info->encoding != (char *) NULL) draw_info->encoding=DestroyString(draw_info->encoding); if (draw_info->density != (char *) NULL) draw_info->density=DestroyString(draw_info->density); if (draw_info->server_name != (char *) NULL) draw_info->server_name=(char *) RelinquishMagickMemory(draw_info->server_name); if (draw_info->dash_pattern != (double *) NULL) draw_info->dash_pattern=(double *) RelinquishMagickMemory( draw_info->dash_pattern); if (draw_info->gradient.stops != (StopInfo *) NULL) draw_info->gradient.stops=(StopInfo *) RelinquishMagickMemory( draw_info->gradient.stops); if (draw_info->clip_mask != (char *) NULL) draw_info->clip_mask=DestroyString(draw_info->clip_mask); if (draw_info->clipping_mask != (Image *) NULL) draw_info->clipping_mask=DestroyImage(draw_info->clipping_mask); if (draw_info->composite_mask != (Image *) NULL) draw_info->composite_mask=DestroyImage(draw_info->composite_mask); draw_info->signature=(~MagickCoreSignature); draw_info=(DrawInfo *) RelinquishMagickMemory(draw_info); return(draw_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w A f f i n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawAffineImage() composites the source over the destination image as % dictated by the affine transform. % % The format of the DrawAffineImage method is: % % MagickBooleanType DrawAffineImage(Image *image,const Image *source, % const AffineMatrix *affine,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o source: the source image. % % o affine: the affine transform. % % o exception: return any errors or warnings in this structure. % */ static SegmentInfo AffineEdge(const Image *image,const AffineMatrix *affine, const double y,const SegmentInfo *edge) { double intercept, z; double x; SegmentInfo inverse_edge; /* Determine left and right edges. */ inverse_edge.x1=edge->x1; inverse_edge.y1=edge->y1; inverse_edge.x2=edge->x2; inverse_edge.y2=edge->y2; z=affine->ry*y+affine->tx; if (affine->sx >= MagickEpsilon) { intercept=(-z/affine->sx); x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z+(double) image->columns)/affine->sx; x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if (affine->sx < -MagickEpsilon) { intercept=(-z+(double) image->columns)/affine->sx; x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z/affine->sx); x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->columns)) { inverse_edge.x2=edge->x1; return(inverse_edge); } /* Determine top and bottom edges. */ z=affine->sy*y+affine->ty; if (affine->rx >= MagickEpsilon) { intercept=(-z/affine->rx); x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z+(double) image->rows)/affine->rx; x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if (affine->rx < -MagickEpsilon) { intercept=(-z+(double) image->rows)/affine->rx; x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z/affine->rx); x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->rows)) { inverse_edge.x2=edge->x2; return(inverse_edge); } return(inverse_edge); } static AffineMatrix InverseAffineMatrix(const AffineMatrix *affine) { AffineMatrix inverse_affine; double determinant; determinant=PerceptibleReciprocal(affine->sx*affine->sy-affine->rx* affine->ry); inverse_affine.sx=determinant*affine->sy; inverse_affine.rx=determinant*(-affine->rx); inverse_affine.ry=determinant*(-affine->ry); inverse_affine.sy=determinant*affine->sx; inverse_affine.tx=(-affine->tx)*inverse_affine.sx-affine->ty* inverse_affine.ry; inverse_affine.ty=(-affine->tx)*inverse_affine.rx-affine->ty* inverse_affine.sy; return(inverse_affine); } MagickExport MagickBooleanType DrawAffineImage(Image *image, const Image *source,const AffineMatrix *affine,ExceptionInfo *exception) { AffineMatrix inverse_affine; CacheView *image_view, *source_view; MagickBooleanType status; PixelInfo zero; PointInfo extent[4], min, max; ssize_t i; SegmentInfo edge; ssize_t start, stop, y; /* Determine bounding box. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(source != (const Image *) NULL); assert(source->signature == MagickCoreSignature); assert(affine != (AffineMatrix *) NULL); extent[0].x=0.0; extent[0].y=0.0; extent[1].x=(double) source->columns-1.0; extent[1].y=0.0; extent[2].x=(double) source->columns-1.0; extent[2].y=(double) source->rows-1.0; extent[3].x=0.0; extent[3].y=(double) source->rows-1.0; for (i=0; i < 4; i++) { PointInfo point; point=extent[i]; extent[i].x=point.x*affine->sx+point.y*affine->ry+affine->tx; extent[i].y=point.x*affine->rx+point.y*affine->sy+affine->ty; } min=extent[0]; max=extent[0]; for (i=1; i < 4; i++) { if (min.x > extent[i].x) min.x=extent[i].x; if (min.y > extent[i].y) min.y=extent[i].y; if (max.x < extent[i].x) max.x=extent[i].x; if (max.y < extent[i].y) max.y=extent[i].y; } /* Affine transform image. */ if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; edge.x1=MagickMax(min.x,0.0); edge.y1=MagickMax(min.y,0.0); edge.x2=MagickMin(max.x,(double) image->columns-1.0); edge.y2=MagickMin(max.y,(double) image->rows-1.0); inverse_affine=InverseAffineMatrix(affine); GetPixelInfo(image,&zero); start=CastDoubleToLong(ceil(edge.y1-0.5)); stop=CastDoubleToLong(floor(edge.y2+0.5)); source_view=AcquireVirtualCacheView(source,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(source,image,stop-start,1) #endif for (y=start; y <= stop; y++) { PixelInfo composite, pixel; PointInfo point; ssize_t x; Quantum *magick_restrict q; SegmentInfo inverse_edge; ssize_t x_offset; if (status == MagickFalse) continue; inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge); if (inverse_edge.x2 < inverse_edge.x1) continue; q=GetCacheViewAuthenticPixels(image_view,CastDoubleToLong( ceil(inverse_edge.x1-0.5)),y,(size_t) CastDoubleToLong(floor( inverse_edge.x2+0.5)-ceil(inverse_edge.x1-0.5)+1),1,exception); if (q == (Quantum *) NULL) continue; pixel=zero; composite=zero; x_offset=0; for (x=CastDoubleToLong(ceil(inverse_edge.x1-0.5)); x <= CastDoubleToLong(floor(inverse_edge.x2+0.5)); x++) { point.x=(double) x*inverse_affine.sx+y*inverse_affine.ry+ inverse_affine.tx; point.y=(double) x*inverse_affine.rx+y*inverse_affine.sy+ inverse_affine.ty; status=InterpolatePixelInfo(source,source_view,UndefinedInterpolatePixel, point.x,point.y,&pixel,exception); if (status == MagickFalse) break; GetPixelInfoPixel(image,q,&composite); CompositePixelInfoOver(&pixel,pixel.alpha,&composite,composite.alpha, &composite); SetPixelViaPixelInfo(image,&composite,q); x_offset++; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w B o u n d i n g R e c t a n g l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawBoundingRectangles() draws the bounding rectangles on the image. This % is only useful for developers debugging the rendering algorithm. % % The format of the DrawBoundingRectangles method is: % % MagickBooleanType DrawBoundingRectangles(Image *image, % const DrawInfo *draw_info,PolygonInfo *polygon_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o polygon_info: Specifies a pointer to a PolygonInfo structure. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType DrawBoundingRectangles(Image *image, const DrawInfo *draw_info,const PolygonInfo *polygon_info, ExceptionInfo *exception) { double mid; DrawInfo *clone_info; MagickStatusType status; PointInfo end, resolution, start; PrimitiveInfo primitive_info[6]; ssize_t i; SegmentInfo bounds; ssize_t coordinates; (void) memset(primitive_info,0,sizeof(primitive_info)); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); status=QueryColorCompliance("#000F",AllCompliance,&clone_info->fill, exception); if (status == MagickFalse) { clone_info=DestroyDrawInfo(clone_info); return(MagickFalse); } resolution.x=96.0; resolution.y=96.0; if (clone_info->density != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(clone_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == MagickFalse) resolution.y=resolution.x; } mid=(resolution.x/96.0)*ExpandAffine(&clone_info->affine)* clone_info->stroke_width/2.0; bounds.x1=0.0; bounds.y1=0.0; bounds.x2=0.0; bounds.y2=0.0; if (polygon_info != (PolygonInfo *) NULL) { bounds=polygon_info->edges[0].bounds; for (i=1; i < (ssize_t) polygon_info->number_edges; i++) { if (polygon_info->edges[i].bounds.x1 < (double) bounds.x1) bounds.x1=polygon_info->edges[i].bounds.x1; if (polygon_info->edges[i].bounds.y1 < (double) bounds.y1) bounds.y1=polygon_info->edges[i].bounds.y1; if (polygon_info->edges[i].bounds.x2 > (double) bounds.x2) bounds.x2=polygon_info->edges[i].bounds.x2; if (polygon_info->edges[i].bounds.y2 > (double) bounds.y2) bounds.y2=polygon_info->edges[i].bounds.y2; } bounds.x1-=mid; bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double) image->columns ? (double) image->columns-1 : bounds.x1; bounds.y1-=mid; bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double) image->rows ? (double) image->rows-1 : bounds.y1; bounds.x2+=mid; bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double) image->columns ? (double) image->columns-1 : bounds.x2; bounds.y2+=mid; bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double) image->rows ? (double) image->rows-1 : bounds.y2; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) { if (polygon_info->edges[i].direction != 0) status=QueryColorCompliance("#f00",AllCompliance,&clone_info->stroke, exception); else status=QueryColorCompliance("#0f0",AllCompliance,&clone_info->stroke, exception); if (status == MagickFalse) break; start.x=(double) (polygon_info->edges[i].bounds.x1-mid); start.y=(double) (polygon_info->edges[i].bounds.y1-mid); end.x=(double) (polygon_info->edges[i].bounds.x2+mid); end.y=(double) (polygon_info->edges[i].bounds.y2+mid); primitive_info[0].primitive=RectanglePrimitive; status&=TraceRectangle(primitive_info,start,end); primitive_info[0].method=ReplaceMethod; coordinates=(ssize_t) primitive_info[0].coordinates; primitive_info[coordinates].primitive=UndefinedPrimitive; status=DrawPrimitive(image,clone_info,primitive_info,exception); if (status == MagickFalse) break; } if (i < (ssize_t) polygon_info->number_edges) { clone_info=DestroyDrawInfo(clone_info); return(status == 0 ? MagickFalse : MagickTrue); } } status=QueryColorCompliance("#00f",AllCompliance,&clone_info->stroke, exception); if (status == MagickFalse) { clone_info=DestroyDrawInfo(clone_info); return(MagickFalse); } start.x=(double) (bounds.x1-mid); start.y=(double) (bounds.y1-mid); end.x=(double) (bounds.x2+mid); end.y=(double) (bounds.y2+mid); primitive_info[0].primitive=RectanglePrimitive; status&=TraceRectangle(primitive_info,start,end); primitive_info[0].method=ReplaceMethod; coordinates=(ssize_t) primitive_info[0].coordinates; primitive_info[coordinates].primitive=UndefinedPrimitive; status=DrawPrimitive(image,clone_info,primitive_info,exception); clone_info=DestroyDrawInfo(clone_info); return(status == 0 ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w C l i p P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawClipPath() draws the clip path on the image mask. % % The format of the DrawClipPath method is: % % MagickBooleanType DrawClipPath(Image *image,const DrawInfo *draw_info, % const char *id,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o id: the clip path id. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType DrawClipPath(Image *image, const DrawInfo *draw_info,const char *id,ExceptionInfo *exception) { const char *clip_path; Image *clipping_mask; MagickBooleanType status; clip_path=GetImageArtifact(image,id); if (clip_path == (const char *) NULL) return(MagickFalse); clipping_mask=DrawClippingMask(image,draw_info,draw_info->clip_mask,clip_path, exception); if (clipping_mask == (Image *) NULL) return(MagickFalse); status=SetImageMask(image,WritePixelMask,clipping_mask,exception); clipping_mask=DestroyImage(clipping_mask); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w C l i p p i n g M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawClippingMask() draws the clip path and returns it as an image clipping % mask. % % The format of the DrawClippingMask method is: % % Image *DrawClippingMask(Image *image,const DrawInfo *draw_info, % const char *id,const char *clip_path,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o id: the clip path id. % % o clip_path: the clip path. % % o exception: return any errors or warnings in this structure. % */ static Image *DrawClippingMask(Image *image,const DrawInfo *draw_info, const char *id,const char *clip_path,ExceptionInfo *exception) { DrawInfo *clone_info; Image *clip_mask, *separate_mask; MagickStatusType status; /* Draw a clip path. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); clip_mask=AcquireImage((const ImageInfo *) NULL,exception); status=SetImageExtent(clip_mask,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImage(clip_mask)); status=SetImageMask(clip_mask,WritePixelMask,(Image *) NULL,exception); status=QueryColorCompliance("#0000",AllCompliance, &clip_mask->background_color,exception); clip_mask->background_color.alpha=(MagickRealType) TransparentAlpha; clip_mask->background_color.alpha_trait=BlendPixelTrait; status=SetImageBackgroundColor(clip_mask,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s", id); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,clip_path); status=QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill, exception); if (clone_info->clip_mask != (char *) NULL) clone_info->clip_mask=DestroyString(clone_info->clip_mask); status=QueryColorCompliance("#00000000",AllCompliance,&clone_info->stroke, exception); clone_info->stroke_width=0.0; clone_info->alpha=OpaqueAlpha; clone_info->clip_path=MagickTrue; status=RenderMVGContent(clip_mask,clone_info,0,exception); clone_info=DestroyDrawInfo(clone_info); separate_mask=SeparateImage(clip_mask,AlphaChannel,exception); if (separate_mask != (Image *) NULL) { clip_mask=DestroyImage(clip_mask); clip_mask=separate_mask; status=NegateImage(clip_mask,MagickFalse,exception); if (status == MagickFalse) clip_mask=DestroyImage(clip_mask); } if (status == MagickFalse) clip_mask=DestroyImage(clip_mask); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path"); return(clip_mask); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w C o m p o s i t e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawCompositeMask() draws the mask path and returns it as an image mask. % % The format of the DrawCompositeMask method is: % % Image *DrawCompositeMask(Image *image,const DrawInfo *draw_info, % const char *id,const char *mask_path,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o id: the mask path id. % % o mask_path: the mask path. % % o exception: return any errors or warnings in this structure. % */ static Image *DrawCompositeMask(Image *image,const DrawInfo *draw_info, const char *id,const char *mask_path,ExceptionInfo *exception) { Image *composite_mask, *separate_mask; DrawInfo *clone_info; MagickStatusType status; /* Draw a mask path. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); composite_mask=AcquireImage((const ImageInfo *) NULL,exception); status=SetImageExtent(composite_mask,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImage(composite_mask)); status=SetImageMask(composite_mask,CompositePixelMask,(Image *) NULL, exception); status=QueryColorCompliance("#0000",AllCompliance, &composite_mask->background_color,exception); composite_mask->background_color.alpha=(MagickRealType) TransparentAlpha; composite_mask->background_color.alpha_trait=BlendPixelTrait; (void) SetImageBackgroundColor(composite_mask,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin mask-path %s", id); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,mask_path); status=QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill, exception); status=QueryColorCompliance("#00000000",AllCompliance,&clone_info->stroke, exception); clone_info->stroke_width=0.0; clone_info->alpha=OpaqueAlpha; status=RenderMVGContent(composite_mask,clone_info,0,exception); clone_info=DestroyDrawInfo(clone_info); separate_mask=SeparateImage(composite_mask,AlphaChannel,exception); if (separate_mask != (Image *) NULL) { composite_mask=DestroyImage(composite_mask); composite_mask=separate_mask; status=NegateImage(composite_mask,MagickFalse,exception); if (status == MagickFalse) composite_mask=DestroyImage(composite_mask); } if (status == MagickFalse) composite_mask=DestroyImage(composite_mask); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end mask-path"); return(composite_mask); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w D a s h P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawDashPolygon() draws a dashed polygon (line, rectangle, ellipse) on the % image while respecting the dash offset and dash pattern attributes. % % The format of the DrawDashPolygon method is: % % MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, % const PrimitiveInfo *primitive_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception) { double length, maximum_length, offset, scale, total_length; DrawInfo *clone_info; MagickStatusType status; PrimitiveInfo *dash_polygon; double dx, dy; ssize_t i; size_t number_vertices; ssize_t j, n; assert(draw_info != (const DrawInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash"); for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; number_vertices=(size_t) i; dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (2UL*number_vertices+32UL),sizeof(*dash_polygon)); if (dash_polygon == (PrimitiveInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } (void) memset(dash_polygon,0,(2UL*number_vertices+32UL)* sizeof(*dash_polygon)); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->miterlimit=0; dash_polygon[0]=primitive_info[0]; scale=ExpandAffine(&draw_info->affine); length=scale*draw_info->dash_pattern[0]; offset=fabs(draw_info->dash_offset) >= MagickEpsilon ? scale*draw_info->dash_offset : 0.0; j=1; for (n=0; offset > 0.0; j=0) { if (draw_info->dash_pattern[n] <= 0.0) break; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); if (offset > length) { offset-=length; n++; length=scale*draw_info->dash_pattern[n]; continue; } if (offset < length) { length-=offset; offset=0.0; break; } offset=0.0; n++; } status=MagickTrue; maximum_length=0.0; total_length=0.0; for (i=1; (i < (ssize_t) number_vertices) && (length >= 0.0); i++) { dx=primitive_info[i].point.x-primitive_info[i-1].point.x; dy=primitive_info[i].point.y-primitive_info[i-1].point.y; maximum_length=hypot(dx,dy); if (maximum_length > (double) (MaxBezierCoordinates >> 2)) continue; if (fabs(length) < MagickEpsilon) { if (fabs(draw_info->dash_pattern[n]) >= MagickEpsilon) n++; if (fabs(draw_info->dash_pattern[n]) < MagickEpsilon) n=0; length=scale*draw_info->dash_pattern[n]; } for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); ) { total_length+=length; if ((n & 0x01) != 0) { dash_polygon[0]=primitive_info[0]; dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx* total_length*PerceptibleReciprocal(maximum_length)); dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy* total_length*PerceptibleReciprocal(maximum_length)); j=1; } else { if ((j+1) > (ssize_t) number_vertices) break; dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx* total_length*PerceptibleReciprocal(maximum_length)); dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy* total_length*PerceptibleReciprocal(maximum_length)); dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception); if (status == MagickFalse) break; } if (fabs(draw_info->dash_pattern[n]) >= MagickEpsilon) n++; if (fabs(draw_info->dash_pattern[n]) < MagickEpsilon) n=0; length=scale*draw_info->dash_pattern[n]; } length-=(maximum_length-total_length); if ((n & 0x01) != 0) continue; dash_polygon[j]=primitive_info[i]; dash_polygon[j].coordinates=1; j++; } if ((status != MagickFalse) && (total_length < maximum_length) && ((n & 0x01) == 0) && (j > 1)) { dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x+=MagickEpsilon; dash_polygon[j].point.y+=MagickEpsilon; dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception); } dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w G r a d i e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawGradientImage() draws a linear gradient on the image. % % The format of the DrawGradientImage method is: % % MagickBooleanType DrawGradientImage(Image *image, % const DrawInfo *draw_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o exception: return any errors or warnings in this structure. % */ static inline double GetStopColorOffset(const GradientInfo *gradient, const ssize_t x,const ssize_t y) { switch (gradient->type) { case UndefinedGradient: case LinearGradient: { double gamma, length, offset, scale; PointInfo p, q; const SegmentInfo *gradient_vector; gradient_vector=(&gradient->gradient_vector); p.x=gradient_vector->x2-gradient_vector->x1; p.y=gradient_vector->y2-gradient_vector->y1; q.x=(double) x-gradient_vector->x1; q.y=(double) y-gradient_vector->y1; length=sqrt(q.x*q.x+q.y*q.y); gamma=sqrt(p.x*p.x+p.y*p.y)*length; gamma=PerceptibleReciprocal(gamma); scale=p.x*q.x+p.y*q.y; offset=gamma*scale*length; return(offset); } case RadialGradient: { PointInfo v; if (gradient->spread == RepeatSpread) { v.x=(double) x-gradient->center.x; v.y=(double) y-gradient->center.y; return(sqrt(v.x*v.x+v.y*v.y)); } v.x=(double) (((x-gradient->center.x)*cos(DegreesToRadians( gradient->angle)))+((y-gradient->center.y)*sin(DegreesToRadians( gradient->angle))))*PerceptibleReciprocal(gradient->radii.x); v.y=(double) (((x-gradient->center.x)*sin(DegreesToRadians( gradient->angle)))-((y-gradient->center.y)*cos(DegreesToRadians( gradient->angle))))*PerceptibleReciprocal(gradient->radii.y); return(sqrt(v.x*v.x+v.y*v.y)); } } return(0.0); } static int StopInfoCompare(const void *x,const void *y) { StopInfo *stop_1, *stop_2; stop_1=(StopInfo *) x; stop_2=(StopInfo *) y; if (stop_1->offset > stop_2->offset) return(1); if (fabs(stop_1->offset-stop_2->offset) <= MagickEpsilon) return(0); return(-1); } MagickExport MagickBooleanType DrawGradientImage(Image *image, const DrawInfo *draw_info,ExceptionInfo *exception) { CacheView *image_view; const GradientInfo *gradient; const SegmentInfo *gradient_vector; double length; MagickBooleanType status; PixelInfo zero; PointInfo point; RectangleInfo bounding_box; ssize_t y; /* Draw linear or radial gradient on image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); gradient=(&draw_info->gradient); qsort(gradient->stops,gradient->number_stops,sizeof(StopInfo), StopInfoCompare); gradient_vector=(&gradient->gradient_vector); point.x=gradient_vector->x2-gradient_vector->x1; point.y=gradient_vector->y2-gradient_vector->y1; length=sqrt(point.x*point.x+point.y*point.y); bounding_box=gradient->bounding_box; status=MagickTrue; GetPixelInfo(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,bounding_box.height-bounding_box.y,1) #endif for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++) { double alpha, offset; PixelInfo composite, pixel; Quantum *magick_restrict q; ssize_t i, x; ssize_t j; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } pixel=zero; composite=zero; offset=GetStopColorOffset(gradient,0,y); if (gradient->type != RadialGradient) offset*=PerceptibleReciprocal(length); for (x=bounding_box.x; x < (ssize_t) bounding_box.width; x++) { GetPixelInfoPixel(image,q,&pixel); switch (gradient->spread) { case UndefinedSpread: case PadSpread: { if ((x != CastDoubleToLong(ceil(gradient_vector->x1-0.5))) || (y != CastDoubleToLong(ceil(gradient_vector->y1-0.5)))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type != RadialGradient) offset*=PerceptibleReciprocal(length); } for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if ((offset < 0.0) || (i == 0)) composite=gradient->stops[0].color; else if ((offset > 1.0) || (i == (ssize_t) gradient->number_stops)) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } case ReflectSpread: { if ((x != CastDoubleToLong(ceil(gradient_vector->x1-0.5))) || (y != CastDoubleToLong(ceil(gradient_vector->y1-0.5)))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type != RadialGradient) offset*=PerceptibleReciprocal(length); } if (offset < 0.0) offset=(-offset); if ((ssize_t) fmod(offset,2.0) == 0) offset=fmod(offset,1.0); else offset=1.0-fmod(offset,1.0); for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if (i == 0) composite=gradient->stops[0].color; else if (i == (ssize_t) gradient->number_stops) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } case RepeatSpread: { double repeat; MagickBooleanType antialias; antialias=MagickFalse; repeat=0.0; if ((x != CastDoubleToLong(ceil(gradient_vector->x1-0.5))) || (y != CastDoubleToLong(ceil(gradient_vector->y1-0.5)))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type == LinearGradient) { repeat=fmod(offset,length); if (repeat < 0.0) repeat=length-fmod(-repeat,length); else repeat=fmod(offset,length); antialias=(repeat < length) && ((repeat+1.0) > length) ? MagickTrue : MagickFalse; offset=PerceptibleReciprocal(length)*repeat; } else { repeat=fmod(offset,gradient->radius); if (repeat < 0.0) repeat=gradient->radius-fmod(-repeat,gradient->radius); else repeat=fmod(offset,gradient->radius); antialias=repeat+1.0 > gradient->radius ? MagickTrue : MagickFalse; offset=repeat/gradient->radius; } } for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if (i == 0) composite=gradient->stops[0].color; else if (i == (ssize_t) gradient->number_stops) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); if (antialias != MagickFalse) { if (gradient->type == LinearGradient) alpha=length-repeat; else alpha=gradient->radius-repeat; i=0; j=(ssize_t) gradient->number_stops-1L; } CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } } CompositePixelInfoOver(&composite,composite.alpha,&pixel,pixel.alpha, &pixel); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawImage() draws a graphic primitive on your image. The primitive % may be represented as a string or filename. Precede the filename with an % "at" sign (@) and the contents of the file are drawn on the image. You % can affect how text is drawn by setting one or more members of the draw % info structure. % % The format of the DrawImage method is: % % MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType CheckPrimitiveExtent(MVGInfo *mvg_info, const double pad) { double extent; size_t quantum; /* Check if there is enough storage for drawing pimitives. */ quantum=sizeof(**mvg_info->primitive_info); extent=(double) mvg_info->offset+pad+PrimitiveExtentPad*quantum+1.0; if (extent <= (double) *mvg_info->extent) return(MagickTrue); if (extent == (double) CastDoubleToLong(extent)) { *mvg_info->primitive_info=(PrimitiveInfo *) ResizeQuantumMemory( *mvg_info->primitive_info,(size_t) extent,quantum); if (*mvg_info->primitive_info != (PrimitiveInfo *) NULL) { ssize_t i; *mvg_info->extent=(size_t) extent; for (i=mvg_info->offset+1; i < (ssize_t) extent; i++) (*mvg_info->primitive_info)[i].primitive=UndefinedPrimitive; return(MagickTrue); } } /* Reallocation failed, allocate a primitive to facilitate unwinding. */ (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); if (*mvg_info->primitive_info != (PrimitiveInfo *) NULL) *mvg_info->primitive_info=(PrimitiveInfo *) RelinquishMagickMemory( *mvg_info->primitive_info); *mvg_info->primitive_info=(PrimitiveInfo *) AcquireCriticalMemory( (size_t) (PrimitiveExtentPad*quantum)); (void) memset(*mvg_info->primitive_info,0,(size_t) (PrimitiveExtentPad*quantum)); *mvg_info->extent=1; return(MagickFalse); } static inline double GetDrawValue(const char *magick_restrict string, char **magick_restrict sentinal) { char **magick_restrict q; double value; q=sentinal; value=InterpretLocaleValue(string,q); sentinal=q; return(value); } static int MVGMacroCompare(const void *target,const void *source) { const char *p, *q; p=(const char *) target; q=(const char *) source; return(strcmp(p,q)); } static SplayTreeInfo *GetMVGMacros(const char *primitive) { char *macro, *token; const char *q; size_t extent; SplayTreeInfo *macros; /* Scan graphic primitives for definitions and classes. */ if (primitive == (const char *) NULL) return((SplayTreeInfo *) NULL); macros=NewSplayTree(MVGMacroCompare,RelinquishMagickMemory, RelinquishMagickMemory); macro=AcquireString(primitive); token=AcquireString(primitive); extent=strlen(token)+MagickPathExtent; for (q=primitive; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (*token == '\0') break; if (LocaleCompare("push",token) == 0) { const char *end, *start; (void) GetNextToken(q,&q,extent,token); if (*q == '"') { char name[MagickPathExtent]; const char *p; ssize_t n; /* Named macro (e.g. push graphic-context "wheel"). */ (void) GetNextToken(q,&q,extent,token); start=q; end=q; (void) CopyMagickString(name,token,MagickPathExtent); n=1; for (p=q; *p != '\0'; ) { if (GetNextToken(p,&p,extent,token) < 1) break; if (*token == '\0') break; if (LocaleCompare(token,"pop") == 0) { end=p-strlen(token)-1; n--; } if (LocaleCompare(token,"push") == 0) n++; if ((n == 0) && (end > start)) { /* Extract macro. */ (void) GetNextToken(p,&p,extent,token); (void) CopyMagickString(macro,start,(size_t) (end-start)); (void) AddValueToSplayTree(macros,ConstantString(name), ConstantString(macro)); break; } } } } } token=DestroyString(token); macro=DestroyString(macro); return(macros); } static inline MagickBooleanType IsPoint(const char *point) { char *p; double value; value=GetDrawValue(point,&p); return((fabs(value) < MagickEpsilon) && (p == point) ? MagickFalse : MagickTrue); } static inline MagickBooleanType TracePoint(PrimitiveInfo *primitive_info, const PointInfo point) { primitive_info->coordinates=1; primitive_info->closed_subpath=MagickFalse; primitive_info->point=point; return(MagickTrue); } static MagickBooleanType RenderMVGContent(Image *image, const DrawInfo *draw_info,const size_t depth,ExceptionInfo *exception) { #define RenderImageTag "Render/Image" AffineMatrix affine, current; char keyword[MagickPathExtent], geometry[MagickPathExtent], *next_token, pattern[MagickPathExtent], *primitive, *token; const char *q; double angle, coordinates, cursor, factor, primitive_extent; DrawInfo *clone_info, **graphic_context; MagickBooleanType proceed; MagickStatusType status; MVGInfo mvg_info; PointInfo point; PrimitiveInfo *primitive_info; PrimitiveType primitive_type; const char *p; ssize_t i, x; SegmentInfo bounds; size_t extent, number_points, number_stops; SplayTreeInfo *macros; ssize_t defsDepth, j, k, n, symbolDepth; StopInfo *stops; TypeMetric metrics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (depth > MagickMaxRecursionDepth) ThrowBinaryException(DrawError,"VectorGraphicsNestedTooDeeply", image->filename); if ((draw_info->primitive == (char *) NULL) || (*draw_info->primitive == '\0')) return(MagickFalse); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image"); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) { status=SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); if (status == MagickFalse) return(MagickFalse); } if ((*draw_info->primitive == '@') && (strlen(draw_info->primitive) > 1) && (*(draw_info->primitive+1) != '-') && (depth == 0)) primitive=FileToString(draw_info->primitive+1,~0UL,exception); else primitive=AcquireString(draw_info->primitive); if (primitive == (char *) NULL) return(MagickFalse); primitive_extent=(double) strlen(primitive); (void) SetImageArtifact(image,"mvg:vector-graphics",primitive); n=0; number_stops=0; stops=(StopInfo *) NULL; /* Allocate primitive info memory. */ graphic_context=(DrawInfo **) AcquireMagickMemory(sizeof(*graphic_context)); if (graphic_context == (DrawInfo **) NULL) { primitive=DestroyString(primitive); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } number_points=(size_t) PrimitiveExtentPad; primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*primitive_info)); if (primitive_info == (PrimitiveInfo *) NULL) { primitive=DestroyString(primitive); for ( ; n >= 0; n--) graphic_context[n]=DestroyDrawInfo(graphic_context[n]); graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) memset(primitive_info,0,(size_t) number_points* sizeof(*primitive_info)); (void) memset(&mvg_info,0,sizeof(mvg_info)); mvg_info.primitive_info=(&primitive_info); mvg_info.extent=(&number_points); mvg_info.exception=exception; graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info); graphic_context[n]->viewbox=image->page; if ((image->page.width == 0) || (image->page.height == 0)) { graphic_context[n]->viewbox.width=image->columns; graphic_context[n]->viewbox.height=image->rows; } token=AcquireString(primitive); extent=strlen(token)+MagickPathExtent; defsDepth=0; symbolDepth=0; cursor=0.0; macros=GetMVGMacros(primitive); status=MagickTrue; for (q=primitive; *q != '\0'; ) { /* Interpret graphic primitive. */ if (GetNextToken(q,&q,MagickPathExtent,keyword) < 1) break; if (*keyword == '\0') break; if (*keyword == '#') { /* Comment. */ while ((*q != '\n') && (*q != '\0')) q++; continue; } p=q-strlen(keyword)-1; primitive_type=UndefinedPrimitive; current=graphic_context[n]->affine; GetAffineMatrix(&affine); *token='\0'; switch (*keyword) { case ';': break; case 'a': case 'A': { if (LocaleCompare("affine",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); affine.sx=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.rx=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.ry=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.sy=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.tx=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.ty=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("alpha",keyword) == 0) { primitive_type=AlphaPrimitive; break; } if (LocaleCompare("arc",keyword) == 0) { primitive_type=ArcPrimitive; break; } status=MagickFalse; break; } case 'b': case 'B': { if (LocaleCompare("bezier",keyword) == 0) { primitive_type=BezierPrimitive; break; } if (LocaleCompare("border-color",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->border_color,exception); break; } status=MagickFalse; break; } case 'c': case 'C': { if (LocaleCompare("class",keyword) == 0) { const char *mvg_class; (void) GetNextToken(q,&q,extent,token); if (*token == '\0') { status=MagickFalse; break; } if (LocaleCompare(token,graphic_context[n]->id) == 0) break; mvg_class=(const char *) GetValueFromSplayTree(macros,token); if ((mvg_class != (const char *) NULL) && (p > primitive)) { char *elements; ssize_t offset; /* Inject class elements in stream. */ offset=(ssize_t) (p-primitive); elements=AcquireString(primitive); elements[offset]='\0'; (void) ConcatenateString(&elements,mvg_class); (void) ConcatenateString(&elements,"\n"); (void) ConcatenateString(&elements,q); primitive=DestroyString(primitive); primitive=elements; q=primitive+offset; } break; } if (LocaleCompare("clip-path",keyword) == 0) { const char *clip_path; /* Take a node from within the MVG document, and duplicate it here. */ (void) GetNextToken(q,&q,extent,token); if (*token == '\0') { status=MagickFalse; break; } (void) CloneString(&graphic_context[n]->clip_mask,token); clip_path=(const char *) GetValueFromSplayTree(macros,token); if (clip_path != (const char *) NULL) { if (graphic_context[n]->clipping_mask != (Image *) NULL) graphic_context[n]->clipping_mask= DestroyImage(graphic_context[n]->clipping_mask); graphic_context[n]->clipping_mask=DrawClippingMask(image, graphic_context[n],token,clip_path,exception); if (graphic_context[n]->compliance != SVGCompliance) { clip_path=(const char *) GetValueFromSplayTree(macros, graphic_context[n]->clip_mask); if (clip_path != (const char *) NULL) (void) SetImageArtifact(image, graphic_context[n]->clip_mask,clip_path); status&=DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); } } break; } if (LocaleCompare("clip-rule",keyword) == 0) { ssize_t fill_rule; (void) GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) { status=MagickFalse; break; } graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("clip-units",keyword) == 0) { ssize_t clip_units; (void) GetNextToken(q,&q,extent,token); clip_units=ParseCommandOption(MagickClipPathOptions,MagickFalse, token); if (clip_units == -1) { status=MagickFalse; break; } graphic_context[n]->clip_units=(ClipPathUnits) clip_units; if (clip_units == ObjectBoundingBox) { GetAffineMatrix(&current); affine.sx=draw_info->bounds.x2; affine.sy=draw_info->bounds.y2; affine.tx=draw_info->bounds.x1; affine.ty=draw_info->bounds.y1; break; } break; } if (LocaleCompare("circle",keyword) == 0) { primitive_type=CirclePrimitive; break; } if (LocaleCompare("color",keyword) == 0) { primitive_type=ColorPrimitive; break; } if (LocaleCompare("compliance",keyword) == 0) { /* MVG compliance associates a clipping mask with an image; SVG compliance associates a clipping mask with a graphics context. */ (void) GetNextToken(q,&q,extent,token); graphic_context[n]->compliance=(ComplianceType) ParseCommandOption( MagickComplianceOptions,MagickFalse,token); break; } if (LocaleCompare("currentColor",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); break; } status=MagickFalse; break; } case 'd': case 'D': { if (LocaleCompare("decorate",keyword) == 0) { ssize_t decorate; (void) GetNextToken(q,&q,extent,token); decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse, token); if (decorate == -1) { status=MagickFalse; break; } graphic_context[n]->decorate=(DecorationType) decorate; break; } if (LocaleCompare("density",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->density,token); break; } if (LocaleCompare("direction",keyword) == 0) { ssize_t direction; (void) GetNextToken(q,&q,extent,token); direction=ParseCommandOption(MagickDirectionOptions,MagickFalse, token); if (direction == -1) status=MagickFalse; else graphic_context[n]->direction=(DirectionType) direction; break; } status=MagickFalse; break; } case 'e': case 'E': { if (LocaleCompare("ellipse",keyword) == 0) { primitive_type=EllipsePrimitive; break; } if (LocaleCompare("encoding",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->encoding,token); break; } status=MagickFalse; break; } case 'f': case 'F': { if (LocaleCompare("fill",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; (void) FormatLocaleString(pattern,MagickPathExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->fill_pattern,exception); else { status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->fill,exception); if (graphic_context[n]->fill_alpha != OpaqueAlpha) graphic_context[n]->fill.alpha=graphic_context[n]->fill_alpha; } break; } if (LocaleCompare("fill-opacity",keyword) == 0) { double opacity; (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; opacity=MagickMin(MagickMax(factor* GetDrawValue(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(token,exception); if (graphic_context[n]->compliance == SVGCompliance) graphic_context[n]->fill_alpha*=opacity; else graphic_context[n]->fill_alpha=QuantumRange*opacity; if (graphic_context[n]->fill.alpha != TransparentAlpha) graphic_context[n]->fill.alpha=graphic_context[n]->fill_alpha; else graphic_context[n]->fill.alpha=(MagickRealType) ClampToQuantum(QuantumRange*(1.0-opacity)); break; } if (LocaleCompare("fill-rule",keyword) == 0) { ssize_t fill_rule; (void) GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) { status=MagickFalse; break; } graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("font",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->font,token); if (LocaleCompare("none",token) == 0) graphic_context[n]->font=(char *) RelinquishMagickMemory( graphic_context[n]->font); break; } if (LocaleCompare("font-family",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->family,token); break; } if (LocaleCompare("font-size",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->pointsize=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("font-stretch",keyword) == 0) { ssize_t stretch; (void) GetNextToken(q,&q,extent,token); stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token); if (stretch == -1) { status=MagickFalse; break; } graphic_context[n]->stretch=(StretchType) stretch; break; } if (LocaleCompare("font-style",keyword) == 0) { ssize_t style; (void) GetNextToken(q,&q,extent,token); style=ParseCommandOption(MagickStyleOptions,MagickFalse,token); if (style == -1) { status=MagickFalse; break; } graphic_context[n]->style=(StyleType) style; break; } if (LocaleCompare("font-weight",keyword) == 0) { ssize_t weight; (void) GetNextToken(q,&q,extent,token); weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token); if (weight == -1) weight=(ssize_t) StringToUnsignedLong(token); graphic_context[n]->weight=(size_t) weight; break; } status=MagickFalse; break; } case 'g': case 'G': { if (LocaleCompare("gradient-units",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("gravity",keyword) == 0) { ssize_t gravity; (void) GetNextToken(q,&q,extent,token); gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token); if (gravity == -1) { status=MagickFalse; break; } graphic_context[n]->gravity=(GravityType) gravity; break; } status=MagickFalse; break; } case 'i': case 'I': { if (LocaleCompare("image",keyword) == 0) { ssize_t compose; primitive_type=ImagePrimitive; (void) GetNextToken(q,&q,extent,token); compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token); if (compose == -1) { status=MagickFalse; break; } graphic_context[n]->compose=(CompositeOperator) compose; break; } if (LocaleCompare("interline-spacing",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->interline_spacing=GetDrawValue(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("interword-spacing",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->interword_spacing=GetDrawValue(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 'k': case 'K': { if (LocaleCompare("kerning",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->kerning=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 'l': case 'L': { if (LocaleCompare("letter-spacing",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); if (IsPoint(token) == MagickFalse) break; clone_info=CloneDrawInfo((ImageInfo *) NULL,graphic_context[n]); clone_info->text=AcquireString(" "); status&=GetTypeMetrics(image,clone_info,&metrics,exception); graphic_context[n]->kerning=metrics.width* GetDrawValue(token,&next_token); clone_info=DestroyDrawInfo(clone_info); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("line",keyword) == 0) { primitive_type=LinePrimitive; break; } status=MagickFalse; break; } case 'm': case 'M': { if (LocaleCompare("mask",keyword) == 0) { const char *mask_path; /* Take a node from within the MVG document, and duplicate it here. */ (void) GetNextToken(q,&q,extent,token); mask_path=(const char *) GetValueFromSplayTree(macros,token); if (mask_path != (const char *) NULL) { if (graphic_context[n]->composite_mask != (Image *) NULL) graphic_context[n]->composite_mask= DestroyImage(graphic_context[n]->composite_mask); graphic_context[n]->composite_mask=DrawCompositeMask(image, graphic_context[n],token,mask_path,exception); if (graphic_context[n]->compliance != SVGCompliance) status=SetImageMask(image,CompositePixelMask, graphic_context[n]->composite_mask,exception); } break; } status=MagickFalse; break; } case 'o': case 'O': { if (LocaleCompare("offset",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("opacity",keyword) == 0) { double opacity; (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; opacity=MagickMin(MagickMax(factor* GetDrawValue(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(token,exception); if (graphic_context[n]->compliance == SVGCompliance) { graphic_context[n]->fill_alpha*=opacity; graphic_context[n]->stroke_alpha*=opacity; } else { graphic_context[n]->fill_alpha=QuantumRange*opacity; graphic_context[n]->stroke_alpha=QuantumRange*opacity; } break; } status=MagickFalse; break; } case 'p': case 'P': { if (LocaleCompare("path",keyword) == 0) { primitive_type=PathPrimitive; break; } if (LocaleCompare("point",keyword) == 0) { primitive_type=PointPrimitive; break; } if (LocaleCompare("polyline",keyword) == 0) { primitive_type=PolylinePrimitive; break; } if (LocaleCompare("polygon",keyword) == 0) { primitive_type=PolygonPrimitive; break; } if (LocaleCompare("pop",keyword) == 0) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare("class",token) == 0) break; if (LocaleCompare("clip-path",token) == 0) break; if (LocaleCompare("defs",token) == 0) { defsDepth--; graphic_context[n]->render=defsDepth > 0 ? MagickFalse : MagickTrue; break; } if (LocaleCompare("gradient",token) == 0) break; if (LocaleCompare("graphic-context",token) == 0) { if (n <= 0) { (void) ThrowMagickException(exception,GetMagickModule(), DrawError,"UnbalancedGraphicContextPushPop","`%s'",token); status=MagickFalse; n=0; break; } if ((graphic_context[n]->clip_mask != (char *) NULL) && (graphic_context[n]->compliance != SVGCompliance)) if (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0) status=SetImageMask(image,WritePixelMask,(Image *) NULL, exception); graphic_context[n]=DestroyDrawInfo(graphic_context[n]); n--; break; } if (LocaleCompare("mask",token) == 0) break; if (LocaleCompare("pattern",token) == 0) break; if (LocaleCompare("symbol",token) == 0) { symbolDepth--; graphic_context[n]->render=symbolDepth > 0 ? MagickFalse : MagickTrue; break; } status=MagickFalse; break; } if (LocaleCompare("push",keyword) == 0) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare("class",token) == 0) { /* Class context. */ for (p=q; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare(token,"pop") != 0) continue; (void) GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"class") != 0) continue; break; } (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("clip-path",token) == 0) { (void) GetNextToken(q,&q,extent,token); for (p=q; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare(token,"pop") != 0) continue; (void) GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"clip-path") != 0) continue; break; } if ((q == (char *) NULL) || (p == (char *) NULL) || ((q-4) < p)) { status=MagickFalse; break; } (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("defs",token) == 0) { defsDepth++; graphic_context[n]->render=defsDepth > 0 ? MagickFalse : MagickTrue; break; } if (LocaleCompare("gradient",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent], type[MagickPathExtent]; SegmentInfo segment; (void) GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); (void) GetNextToken(q,&q,extent,token); (void) CopyMagickString(type,token,MagickPathExtent); (void) GetNextToken(q,&q,extent,token); segment.x1=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); segment.y1=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); segment.x2=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); segment.y2=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); if (LocaleCompare(type,"radial") == 0) { (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); } for (p=q; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare(token,"pop") != 0) continue; (void) GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"gradient") != 0) continue; break; } if ((q == (char *) NULL) || (p == (char *) NULL) || ((q-4) < p)) { status=MagickFalse; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); bounds.x1=graphic_context[n]->affine.sx*segment.x1+ graphic_context[n]->affine.ry*segment.y1+ graphic_context[n]->affine.tx; bounds.y1=graphic_context[n]->affine.rx*segment.x1+ graphic_context[n]->affine.sy*segment.y1+ graphic_context[n]->affine.ty; bounds.x2=graphic_context[n]->affine.sx*segment.x2+ graphic_context[n]->affine.ry*segment.y2+ graphic_context[n]->affine.tx; bounds.y2=graphic_context[n]->affine.rx*segment.x2+ graphic_context[n]->affine.sy*segment.y2+ graphic_context[n]->affine.ty; (void) FormatLocaleString(key,MagickPathExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MagickPathExtent,"%s-type",name); (void) SetImageArtifact(image,key,type); (void) FormatLocaleString(key,MagickPathExtent,"%s-geometry", name); (void) FormatLocaleString(geometry,MagickPathExtent, "%gx%g%+.15g%+.15g", MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0), MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0), bounds.x1,bounds.y1); (void) SetImageArtifact(image,key,geometry); (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("graphic-context",token) == 0) { n++; graphic_context=(DrawInfo **) ResizeQuantumMemory( graphic_context,(size_t) (n+1),sizeof(*graphic_context)); if (graphic_context == (DrawInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL, graphic_context[n-1]); if (*q == '"') { (void) GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->id,token); } break; } if (LocaleCompare("mask",token) == 0) { (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("pattern",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent]; RectangleInfo bounds; (void) GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); (void) GetNextToken(q,&q,extent,token); bounds.x=CastDoubleToLong(ceil(GetDrawValue(token, &next_token)-0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); bounds.y=CastDoubleToLong(ceil(GetDrawValue(token, &next_token)-0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); bounds.width=(size_t) CastDoubleToLong(floor(GetDrawValue( token,&next_token)+0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); bounds.height=(size_t) floor(GetDrawValue(token,&next_token)+ 0.5); if (token == next_token) ThrowPointExpectedException(token,exception); for (p=q; *q != '\0'; ) { if (GetNextToken(q,&q,extent,token) < 1) break; if (LocaleCompare(token,"pop") != 0) continue; (void) GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"pattern") != 0) continue; break; } if ((q == (char *) NULL) || (p == (char *) NULL) || ((q-4) < p)) { status=MagickFalse; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); (void) FormatLocaleString(key,MagickPathExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MagickPathExtent,"%s-geometry", name); (void) FormatLocaleString(geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) bounds.width,(double) bounds.height,(double) bounds.x,(double) bounds.y); (void) SetImageArtifact(image,key,geometry); (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("symbol",token) == 0) { symbolDepth++; graphic_context[n]->render=symbolDepth > 0 ? MagickFalse : MagickTrue; break; } status=MagickFalse; break; } status=MagickFalse; break; } case 'r': case 'R': { if (LocaleCompare("rectangle",keyword) == 0) { primitive_type=RectanglePrimitive; break; } if (LocaleCompare("rotate",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); angle=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0))); affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0))); break; } if (LocaleCompare("roundRectangle",keyword) == 0) { primitive_type=RoundRectanglePrimitive; break; } status=MagickFalse; break; } case 's': case 'S': { if (LocaleCompare("scale",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); affine.sx=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.sy=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("skewX",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); angle=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); affine.ry=sin(DegreesToRadians(angle)); break; } if (LocaleCompare("skewY",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); angle=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); affine.rx=(-tan(DegreesToRadians(angle)/2.0)); break; } if (LocaleCompare("stop-color",keyword) == 0) { PixelInfo stop_color; number_stops++; if (number_stops == 1) stops=(StopInfo *) AcquireQuantumMemory(2,sizeof(*stops)); else if (number_stops > 2) stops=(StopInfo *) ResizeQuantumMemory(stops,number_stops, sizeof(*stops)); if (stops == (StopInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } (void) GetNextToken(q,&q,extent,token); status&=QueryColorCompliance(token,AllCompliance,&stop_color, exception); stops[number_stops-1].color=stop_color; (void) GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; stops[number_stops-1].offset=factor*GetDrawValue(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("stroke",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; (void) FormatLocaleString(pattern,MagickPathExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->stroke_pattern,exception); else { status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->stroke,exception); if (graphic_context[n]->stroke_alpha != OpaqueAlpha) graphic_context[n]->stroke.alpha= graphic_context[n]->stroke_alpha; } break; } if (LocaleCompare("stroke-antialias",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->stroke_antialias=StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("stroke-dasharray",keyword) == 0) { if (graphic_context[n]->dash_pattern != (double *) NULL) graphic_context[n]->dash_pattern=(double *) RelinquishMagickMemory(graphic_context[n]->dash_pattern); if (IsPoint(q) != MagickFalse) { const char *r; r=q; (void) GetNextToken(r,&r,extent,token); if (*token == ',') (void) GetNextToken(r,&r,extent,token); for (x=0; IsPoint(token) != MagickFalse; x++) { (void) GetNextToken(r,&r,extent,token); if (*token == ',') (void) GetNextToken(r,&r,extent,token); } graphic_context[n]->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2*x+2), sizeof(*graphic_context[n]->dash_pattern)); if (graphic_context[n]->dash_pattern == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); status=MagickFalse; break; } (void) memset(graphic_context[n]->dash_pattern,0,(size_t) (2*x+2)*sizeof(*graphic_context[n]->dash_pattern)); for (j=0; j < x; j++) { (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); graphic_context[n]->dash_pattern[j]=GetDrawValue(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); if (graphic_context[n]->dash_pattern[j] < 0.0) status=MagickFalse; } if ((x & 0x01) != 0) for ( ; j < (2*x); j++) graphic_context[n]->dash_pattern[j]= graphic_context[n]->dash_pattern[j-x]; graphic_context[n]->dash_pattern[j]=0.0; break; } (void) GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("stroke-dashoffset",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->dash_offset=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("stroke-linecap",keyword) == 0) { ssize_t linecap; (void) GetNextToken(q,&q,extent,token); linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token); if (linecap == -1) { status=MagickFalse; break; } graphic_context[n]->linecap=(LineCap) linecap; break; } if (LocaleCompare("stroke-linejoin",keyword) == 0) { ssize_t linejoin; (void) GetNextToken(q,&q,extent,token); linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse, token); if (linejoin == -1) { status=MagickFalse; break; } graphic_context[n]->linejoin=(LineJoin) linejoin; break; } if (LocaleCompare("stroke-miterlimit",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->miterlimit=StringToUnsignedLong(token); break; } if (LocaleCompare("stroke-opacity",keyword) == 0) { double opacity; (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; opacity=MagickMin(MagickMax(factor* GetDrawValue(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(token,exception); if (graphic_context[n]->compliance == SVGCompliance) graphic_context[n]->stroke_alpha*=opacity; else graphic_context[n]->stroke_alpha=QuantumRange*opacity; if (graphic_context[n]->stroke.alpha != TransparentAlpha) graphic_context[n]->stroke.alpha=graphic_context[n]->stroke_alpha; else graphic_context[n]->stroke.alpha=(MagickRealType) ClampToQuantum(QuantumRange*(1.0-opacity)); break; } if (LocaleCompare("stroke-width",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; graphic_context[n]->stroke_width=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 't': case 'T': { if (LocaleCompare("text",keyword) == 0) { primitive_type=TextPrimitive; cursor=0.0; break; } if (LocaleCompare("text-align",keyword) == 0) { ssize_t align; (void) GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) { status=MagickFalse; break; } graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-anchor",keyword) == 0) { ssize_t align; (void) GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) { status=MagickFalse; break; } graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-antialias",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->text_antialias=StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("text-undercolor",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->undercolor,exception); break; } if (LocaleCompare("translate",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); affine.tx=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); affine.ty=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); cursor=0.0; break; } status=MagickFalse; break; } case 'u': case 'U': { if (LocaleCompare("use",keyword) == 0) { const char *use; /* Get a macro from the MVG document, and "use" it here. */ (void) GetNextToken(q,&q,extent,token); use=(const char *) GetValueFromSplayTree(macros,token); if (use != (const char *) NULL) { clone_info=CloneDrawInfo((ImageInfo *) NULL,graphic_context[n]); (void) CloneString(&clone_info->primitive,use); status=RenderMVGContent(image,clone_info,depth+1,exception); clone_info=DestroyDrawInfo(clone_info); } break; } status=MagickFalse; break; } case 'v': case 'V': { if (LocaleCompare("viewbox",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.x=CastDoubleToLong(ceil( GetDrawValue(token,&next_token)-0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.y=CastDoubleToLong(ceil( GetDrawValue(token,&next_token)-0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.width=(size_t) CastDoubleToLong( floor(GetDrawValue(token,&next_token)+0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.height=(size_t) CastDoubleToLong( floor(GetDrawValue(token,&next_token)+0.5)); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 'w': case 'W': { if (LocaleCompare("word-spacing",keyword) == 0) { (void) GetNextToken(q,&q,extent,token); graphic_context[n]->interword_spacing=GetDrawValue(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } default: { status=MagickFalse; break; } } if (status == MagickFalse) break; if ((fabs(affine.sx-1.0) >= MagickEpsilon) || (fabs(affine.rx) >= MagickEpsilon) || (fabs(affine.ry) >= MagickEpsilon) || (fabs(affine.sy-1.0) >= MagickEpsilon) || (fabs(affine.tx) >= MagickEpsilon) || (fabs(affine.ty) >= MagickEpsilon)) { graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx; graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx; graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy; graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy; graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+ current.tx; graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+ current.ty; } if (primitive_type == UndefinedPrimitive) { if (*q == '\0') { if (number_stops > 1) { GradientType type; type=LinearGradient; if (draw_info->gradient.type == RadialGradient) type=RadialGradient; (void) GradientImage(image,type,PadSpread,stops,number_stops, exception); } if (number_stops > 0) stops=(StopInfo *) RelinquishMagickMemory(stops); } if ((image->debug != MagickFalse) && (q > p)) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p-1),p); continue; } /* Parse the primitive attributes. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) if ((primitive_info[i].primitive == TextPrimitive) || (primitive_info[i].primitive == ImagePrimitive)) if (primitive_info[i].text != (char *) NULL) primitive_info[i].text=DestroyString(primitive_info[i].text); i=0; mvg_info.offset=i; j=0; primitive_info[0].point.x=0.0; primitive_info[0].point.y=0.0; primitive_info[0].coordinates=0; primitive_info[0].method=FloodfillMethod; primitive_info[0].closed_subpath=MagickFalse; for (x=0; *q != '\0'; x++) { /* Define points. */ if (IsPoint(q) == MagickFalse) break; (void) GetNextToken(q,&q,extent,token); point.x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,&q,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); point.y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(q,(const char **) NULL,extent,token); if (*token == ',') (void) GetNextToken(q,&q,extent,token); primitive_info[i].primitive=primitive_type; primitive_info[i].point=point; primitive_info[i].coordinates=0; primitive_info[i].method=FloodfillMethod; primitive_info[i].closed_subpath=MagickFalse; i++; mvg_info.offset=i; if (i < (ssize_t) number_points) continue; status&=CheckPrimitiveExtent(&mvg_info,(double) number_points); } if (status == MagickFalse) break; if ((primitive_info[j].primitive == TextPrimitive) || (primitive_info[j].primitive == ImagePrimitive)) if (primitive_info[j].text != (char *) NULL) primitive_info[j].text=DestroyString(primitive_info[j].text); primitive_info[j].primitive=primitive_type; primitive_info[j].coordinates=(size_t) x; primitive_info[j].method=FloodfillMethod; primitive_info[j].closed_subpath=MagickFalse; /* Circumscribe primitive within a circle. */ bounds.x1=primitive_info[j].point.x; bounds.y1=primitive_info[j].point.y; bounds.x2=primitive_info[j].point.x; bounds.y2=primitive_info[j].point.y; for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++) { point=primitive_info[j+k].point; if (point.x < bounds.x1) bounds.x1=point.x; if (point.y < bounds.y1) bounds.y1=point.y; if (point.x > bounds.x2) bounds.x2=point.x; if (point.y > bounds.y2) bounds.y2=point.y; } /* Speculate how many points our primitive might consume. */ coordinates=(double) primitive_info[j].coordinates; switch (primitive_type) { case RectanglePrimitive: { coordinates*=5.0; break; } case RoundRectanglePrimitive: { double alpha, beta, radius; alpha=bounds.x2-bounds.x1; beta=bounds.y2-bounds.y1; radius=hypot(alpha,beta); coordinates*=5.0; coordinates+=2.0*((size_t) ceil((double) MagickPI*radius))+6.0* BezierQuantum+360.0; break; } case BezierPrimitive: { coordinates=(BezierQuantum*(double) primitive_info[j].coordinates); break; } case PathPrimitive: { char *s, *t; (void) GetNextToken(q,&q,extent,token); coordinates=1.0; t=token; for (s=token; *s != '\0'; s=t) { double value; value=GetDrawValue(s,&t); (void) value; if (s == t) { t++; continue; } coordinates++; } for (s=token; *s != '\0'; s++) if (strspn(s,"AaCcQqSsTt") != 0) coordinates+=(20.0*BezierQuantum)+360.0; break; } default: break; } if (status == MagickFalse) break; if (((size_t) (i+coordinates)) >= number_points) { /* Resize based on speculative points required by primitive. */ number_points+=coordinates+1; if (number_points < (size_t) coordinates) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } mvg_info.offset=i; status&=CheckPrimitiveExtent(&mvg_info,(double) number_points); } status&=CheckPrimitiveExtent(&mvg_info,PrimitiveExtentPad); if (status == MagickFalse) break; mvg_info.offset=j; switch (primitive_type) { case PointPrimitive: default: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } status&=TracePoint(primitive_info+j,primitive_info[j].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case LinePrimitive: { double dx, dy, maximum_length; if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } dx=primitive_info[i].point.x-primitive_info[i-1].point.x; dy=primitive_info[i].point.y-primitive_info[i-1].point.y; maximum_length=hypot(dx,dy); if (maximum_length > (MaxBezierCoordinates/100.0)) ThrowPointExpectedException(keyword,exception); status&=TraceLine(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case RectanglePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } status&=TraceRectangle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case RoundRectanglePrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } if ((primitive_info[j+2].point.x < 0.0) || (primitive_info[j+2].point.y < 0.0)) { status=MagickFalse; break; } if ((primitive_info[j+1].point.x-primitive_info[j].point.x) < 0.0) { status=MagickFalse; break; } if ((primitive_info[j+1].point.y-primitive_info[j].point.y) < 0.0) { status=MagickFalse; break; } status&=TraceRoundRectangle(&mvg_info,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case ArcPrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } status&=TraceArc(&mvg_info,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case EllipsePrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } if ((primitive_info[j+1].point.x < 0.0) || (primitive_info[j+1].point.y < 0.0)) { status=MagickFalse; break; } status&=TraceEllipse(&mvg_info,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case CirclePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } status&=TraceCircle(&mvg_info,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PolylinePrimitive: { if (primitive_info[j].coordinates < 1) { status=MagickFalse; break; } break; } case PolygonPrimitive: { if (primitive_info[j].coordinates < 3) { status=MagickFalse; break; } primitive_info[i]=primitive_info[j]; primitive_info[i].coordinates=0; primitive_info[j].coordinates++; primitive_info[j].closed_subpath=MagickTrue; i++; break; } case BezierPrimitive: { if (primitive_info[j].coordinates < 3) { status=MagickFalse; break; } status&=TraceBezier(&mvg_info,primitive_info[j].coordinates); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PathPrimitive: { coordinates=(double) TracePath(&mvg_info,token,exception); if (coordinates < 0.0) { status=MagickFalse; break; } i=(ssize_t) (j+coordinates); break; } case AlphaPrimitive: case ColorPrimitive: { ssize_t method; if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } (void) GetNextToken(q,&q,extent,token); method=ParseCommandOption(MagickMethodOptions,MagickFalse,token); if (method == -1) { status=MagickFalse; break; } primitive_info[j].method=(PaintMethod) method; break; } case TextPrimitive: { char geometry[MagickPathExtent]; if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } if (*token != ',') (void) GetNextToken(q,&q,extent,token); (void) CloneString(&primitive_info[j].text,token); /* Compute text cursor offset. */ clone_info=CloneDrawInfo((ImageInfo *) NULL,graphic_context[n]); if ((fabs(mvg_info.point.x-primitive_info->point.x) < MagickEpsilon) && (fabs(mvg_info.point.y-primitive_info->point.y) < MagickEpsilon)) { mvg_info.point=primitive_info->point; primitive_info->point.x+=cursor; } else { mvg_info.point=primitive_info->point; cursor=0.0; } (void) FormatLocaleString(geometry,MagickPathExtent,"%+f%+f", primitive_info->point.x,primitive_info->point.y); clone_info->render=MagickFalse; clone_info->text=AcquireString(token); status&=GetTypeMetrics(image,clone_info,&metrics,exception); clone_info=DestroyDrawInfo(clone_info); cursor+=metrics.width; if (graphic_context[n]->compliance != SVGCompliance) cursor=0.0; break; } case ImagePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } (void) GetNextToken(q,&q,extent,token); (void) CloneString(&primitive_info[j].text,token); break; } } mvg_info.offset=i; if (status == 0) break; primitive_info[i].primitive=UndefinedPrimitive; if ((image->debug != MagickFalse) && (q > p)) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p-1), p); /* Sanity check. */ status&=CheckPrimitiveExtent(&mvg_info,ExpandAffine( &graphic_context[n]->affine)); if (status == 0) break; status&=CheckPrimitiveExtent(&mvg_info,(double) graphic_context[n]->stroke_width); if (status == 0) break; if (i == 0) continue; /* Transform points. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { point=primitive_info[i].point; primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+ graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx; primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+ graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty; point=primitive_info[i].point; if (point.x < graphic_context[n]->bounds.x1) graphic_context[n]->bounds.x1=point.x; if (point.y < graphic_context[n]->bounds.y1) graphic_context[n]->bounds.y1=point.y; if (point.x > graphic_context[n]->bounds.x2) graphic_context[n]->bounds.x2=point.x; if (point.y > graphic_context[n]->bounds.y2) graphic_context[n]->bounds.y2=point.y; if (primitive_info[i].primitive == ImagePrimitive) break; if (i >= (ssize_t) number_points) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); } if (graphic_context[n]->render != MagickFalse) { if ((n != 0) && (graphic_context[n]->compliance != SVGCompliance) && (graphic_context[n]->clip_mask != (char *) NULL) && (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0)) { const char *clip_path; clip_path=(const char *) GetValueFromSplayTree(macros, graphic_context[n]->clip_mask); if (clip_path != (const char *) NULL) (void) SetImageArtifact(image,graphic_context[n]->clip_mask, clip_path); status&=DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); } status&=DrawPrimitive(image,graphic_context[n],primitive_info, exception); } proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType) primitive_extent); if (proceed == MagickFalse) break; if (status == 0) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end draw-image"); /* Relinquish resources. */ macros=DestroySplayTree(macros); token=DestroyString(token); if (primitive_info != (PrimitiveInfo *) NULL) { for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) if ((primitive_info[i].primitive == TextPrimitive) || (primitive_info[i].primitive == ImagePrimitive)) if (primitive_info[i].text != (char *) NULL) primitive_info[i].text=DestroyString(primitive_info[i].text); primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info); } primitive=DestroyString(primitive); if (stops != (StopInfo *) NULL) stops=(StopInfo *) RelinquishMagickMemory(stops); for ( ; n >= 0; n--) graphic_context[n]=DestroyDrawInfo(graphic_context[n]); graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context); if (status == MagickFalse) ThrowBinaryException(DrawError,"NonconformingDrawingPrimitiveDefinition", keyword); return(status != 0 ? MagickTrue : MagickFalse); } MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, ExceptionInfo *exception) { return(RenderMVGContent(image,draw_info,0,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w P a t t e r n P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPatternPath() draws a pattern. % % The format of the DrawPatternPath method is: % % MagickBooleanType DrawPatternPath(Image *image,const DrawInfo *draw_info, % const char *name,Image **pattern,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o name: the pattern name. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType DrawPatternPath(Image *image, const DrawInfo *draw_info,const char *name,Image **pattern, ExceptionInfo *exception) { char property[MagickPathExtent]; const char *geometry, *path, *type; DrawInfo *clone_info; ImageInfo *image_info; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); assert(name != (const char *) NULL); (void) FormatLocaleString(property,MagickPathExtent,"%s",name); path=GetImageArtifact(image,property); if (path == (const char *) NULL) return(MagickFalse); (void) FormatLocaleString(property,MagickPathExtent,"%s-geometry",name); geometry=GetImageArtifact(image,property); if (geometry == (const char *) NULL) return(MagickFalse); if ((*pattern) != (Image *) NULL) *pattern=DestroyImage(*pattern); image_info=AcquireImageInfo(); image_info->size=AcquireString(geometry); *pattern=AcquireImage(image_info,exception); image_info=DestroyImageInfo(image_info); (void) QueryColorCompliance("#00000000",AllCompliance, &(*pattern)->background_color,exception); (void) SetImageBackgroundColor(*pattern,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), "begin pattern-path %s %s",name,geometry); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); if (clone_info->fill_pattern != (Image *) NULL) clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern); if (clone_info->stroke_pattern != (Image *) NULL) clone_info->stroke_pattern=DestroyImage(clone_info->stroke_pattern); (void) FormatLocaleString(property,MagickPathExtent,"%s-type",name); type=GetImageArtifact(image,property); if (type != (const char *) NULL) clone_info->gradient.type=(GradientType) ParseCommandOption( MagickGradientOptions,MagickFalse,type); (void) CloneString(&clone_info->primitive,path); status=RenderMVGContent(*pattern,clone_info,0,exception); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end pattern-path"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w P o l y g o n P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPolygonPrimitive() draws a polygon on the image. % % The format of the DrawPolygonPrimitive method is: % % MagickBooleanType DrawPolygonPrimitive(Image *image, % const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % o exception: return any errors or warnings in this structure. % */ static PolygonInfo **DestroyPolygonThreadSet(PolygonInfo **polygon_info) { ssize_t i; assert(polygon_info != (PolygonInfo **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (polygon_info[i] != (PolygonInfo *) NULL) polygon_info[i]=DestroyPolygonInfo(polygon_info[i]); polygon_info=(PolygonInfo **) RelinquishMagickMemory(polygon_info); return(polygon_info); } static PolygonInfo **AcquirePolygonThreadSet( const PrimitiveInfo *primitive_info,ExceptionInfo *exception) { PathInfo *magick_restrict path_info; PolygonInfo **polygon_info; ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); polygon_info=(PolygonInfo **) AcquireQuantumMemory(number_threads, sizeof(*polygon_info)); if (polygon_info == (PolygonInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return((PolygonInfo **) NULL); } (void) memset(polygon_info,0,number_threads*sizeof(*polygon_info)); path_info=ConvertPrimitiveToPath(primitive_info,exception); if (path_info == (PathInfo *) NULL) return(DestroyPolygonThreadSet(polygon_info)); polygon_info[0]=ConvertPathToPolygon(path_info,exception); if (polygon_info[0] == (PolygonInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonThreadSet(polygon_info)); } for (i=1; i < (ssize_t) number_threads; i++) { EdgeInfo *edge_info; ssize_t j; polygon_info[i]=(PolygonInfo *) AcquireMagickMemory( sizeof(*polygon_info[i])); if (polygon_info[i] == (PolygonInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonThreadSet(polygon_info)); } polygon_info[i]->number_edges=0; edge_info=polygon_info[0]->edges; polygon_info[i]->edges=(EdgeInfo *) AcquireQuantumMemory( polygon_info[0]->number_edges,sizeof(*edge_info)); if (polygon_info[i]->edges == (EdgeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonThreadSet(polygon_info)); } (void) memcpy(polygon_info[i]->edges,edge_info, polygon_info[0]->number_edges*sizeof(*edge_info)); for (j=0; j < (ssize_t) polygon_info[i]->number_edges; j++) polygon_info[i]->edges[j].points=(PointInfo *) NULL; polygon_info[i]->number_edges=polygon_info[0]->number_edges; for (j=0; j < (ssize_t) polygon_info[i]->number_edges; j++) { edge_info=polygon_info[0]->edges+j; polygon_info[i]->edges[j].points=(PointInfo *) AcquireQuantumMemory( edge_info->number_points,sizeof(*edge_info)); if (polygon_info[i]->edges[j].points == (PointInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(DestroyPolygonThreadSet(polygon_info)); } (void) memcpy(polygon_info[i]->edges[j].points,edge_info->points, edge_info->number_points*sizeof(*edge_info->points)); } } path_info=(PathInfo *) RelinquishMagickMemory(path_info); return(polygon_info); } static size_t DestroyEdge(PolygonInfo *polygon_info,const ssize_t edge) { assert(edge < (ssize_t) polygon_info->number_edges); polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory( polygon_info->edges[edge].points); polygon_info->number_edges--; if (edge < (ssize_t) polygon_info->number_edges) (void) memmove(polygon_info->edges+edge,polygon_info->edges+edge+1, (size_t) (polygon_info->number_edges-edge)*sizeof(*polygon_info->edges)); return(polygon_info->number_edges); } static double GetFillAlpha(PolygonInfo *polygon_info,const double mid, const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x, const ssize_t y,double *stroke_alpha) { double alpha, beta, distance, subpath_alpha; PointInfo delta; const PointInfo *q; EdgeInfo *p; ssize_t i; ssize_t j, winding_number; /* Compute fill & stroke opacity for this (x,y) point. */ *stroke_alpha=0.0; subpath_alpha=0.0; p=polygon_info->edges; for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++) { if ((double) y <= (p->bounds.y1-mid-0.5)) break; if ((double) y > (p->bounds.y2+mid+0.5)) { (void) DestroyEdge(polygon_info,j); continue; } if (((double) x <= (p->bounds.x1-mid-0.5)) || ((double) x > (p->bounds.x2+mid+0.5))) continue; i=(ssize_t) MagickMax((double) p->highwater,1.0); for ( ; i < (ssize_t) p->number_points; i++) { if ((double) y <= (p->points[i-1].y-mid-0.5)) break; if ((double) y > (p->points[i].y+mid+0.5)) continue; if (p->scanline != (double) y) { p->scanline=(double) y; p->highwater=(size_t) i; } /* Compute distance between a point and an edge. */ q=p->points+i-1; delta.x=(q+1)->x-q->x; delta.y=(q+1)->y-q->y; beta=delta.x*(x-q->x)+delta.y*(y-q->y); if (beta <= 0.0) { delta.x=(double) x-q->x; delta.y=(double) y-q->y; distance=delta.x*delta.x+delta.y*delta.y; } else { alpha=delta.x*delta.x+delta.y*delta.y; if (beta >= alpha) { delta.x=(double) x-(q+1)->x; delta.y=(double) y-(q+1)->y; distance=delta.x*delta.x+delta.y*delta.y; } else { alpha=PerceptibleReciprocal(alpha); beta=delta.x*(y-q->y)-delta.y*(x-q->x)+MagickEpsilon; distance=alpha*beta*beta; } } /* Compute stroke & subpath opacity. */ beta=0.0; if (p->ghostline == MagickFalse) { alpha=mid+0.5; if ((*stroke_alpha < 1.0) && (distance <= ((alpha+0.25)*(alpha+0.25)))) { alpha=mid-0.5; if (distance <= ((alpha+0.25)*(alpha+0.25))) *stroke_alpha=1.0; else { beta=1.0; if (fabs(distance-1.0) >= MagickEpsilon) beta=sqrt((double) distance); alpha=beta-mid-0.5; if (*stroke_alpha < ((alpha-0.25)*(alpha-0.25))) *stroke_alpha=(alpha-0.25)*(alpha-0.25); } } } if ((fill == MagickFalse) || (distance > 1.0) || (subpath_alpha >= 1.0)) continue; if (distance <= 0.0) { subpath_alpha=1.0; continue; } if (distance > 1.0) continue; if (fabs(beta) < MagickEpsilon) { beta=1.0; if (fabs(distance-1.0) >= MagickEpsilon) beta=sqrt(distance); } alpha=beta-1.0; if (subpath_alpha < (alpha*alpha)) subpath_alpha=alpha*alpha; } } /* Compute fill opacity. */ if (fill == MagickFalse) return(0.0); if (subpath_alpha >= 1.0) return(1.0); /* Determine winding number. */ winding_number=0; p=polygon_info->edges; for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++) { if ((double) y <= p->bounds.y1) break; if (((double) y > p->bounds.y2) || ((double) x <= p->bounds.x1)) continue; if ((double) x > p->bounds.x2) { winding_number+=p->direction ? 1 : -1; continue; } i=(ssize_t) MagickMax((double) p->highwater,1.0); for ( ; i < (ssize_t) (p->number_points-1); i++) if ((double) y <= p->points[i].y) break; q=p->points+i-1; if ((((q+1)->x-q->x)*(y-q->y)) <= (((q+1)->y-q->y)*(x-q->x))) winding_number+=p->direction ? 1 : -1; } if (fill_rule != NonZeroRule) { if ((MagickAbsoluteValue(winding_number) & 0x01) != 0) return(1.0); } else if (MagickAbsoluteValue(winding_number) != 0) return(1.0); return(subpath_alpha); } static MagickBooleanType DrawPolygonPrimitive(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { CacheView *image_view; const char *artifact; MagickBooleanType fill, status; double mid; PolygonInfo **magick_restrict polygon_info; EdgeInfo *p; ssize_t i; SegmentInfo bounds; ssize_t start_y, stop_y, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); assert(primitive_info != (PrimitiveInfo *) NULL); if (primitive_info->coordinates <= 1) return(MagickTrue); /* Compute bounding box. */ polygon_info=AcquirePolygonThreadSet(primitive_info,exception); if (polygon_info == (PolygonInfo **) NULL) return(MagickFalse); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-polygon"); fill=(primitive_info->method == FillToBorderMethod) || (primitive_info->method == FloodfillMethod) ? MagickTrue : MagickFalse; mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; bounds=polygon_info[0]->edges[0].bounds; artifact=GetImageArtifact(image,"draw:render-bounding-rectangles"); if (IsStringTrue(artifact) != MagickFalse) (void) DrawBoundingRectangles(image,draw_info,polygon_info[0],exception); for (i=1; i < (ssize_t) polygon_info[0]->number_edges; i++) { p=polygon_info[0]->edges+i; if (p->bounds.x1 < bounds.x1) bounds.x1=p->bounds.x1; if (p->bounds.y1 < bounds.y1) bounds.y1=p->bounds.y1; if (p->bounds.x2 > bounds.x2) bounds.x2=p->bounds.x2; if (p->bounds.y2 > bounds.y2) bounds.y2=p->bounds.y2; } bounds.x1-=(mid+1.0); bounds.y1-=(mid+1.0); bounds.x2+=(mid+1.0); bounds.y2+=(mid+1.0); if ((bounds.x1 >= (double) image->columns) || (bounds.y1 >= (double) image->rows) || (bounds.x2 <= 0.0) || (bounds.y2 <= 0.0)) { polygon_info=DestroyPolygonThreadSet(polygon_info); return(MagickTrue); /* virtual polygon */ } bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double) image->columns-1.0 ? (double) image->columns-1.0 : bounds.x1; bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double) image->rows-1.0 ? (double) image->rows-1.0 : bounds.y1; bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double) image->columns-1.0 ? (double) image->columns-1.0 : bounds.x2; bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double) image->rows-1.0 ? (double) image->rows-1.0 : bounds.y2; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); if ((primitive_info->coordinates == 1) || (polygon_info[0]->number_edges == 0)) { /* Draw point. */ start_y=CastDoubleToLong(ceil(bounds.y1-0.5)); stop_y=CastDoubleToLong(floor(bounds.y2+0.5)); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,stop_y-start_y+1,1) #endif for (y=start_y; y <= stop_y; y++) { MagickBooleanType sync; PixelInfo pixel; ssize_t x; Quantum *magick_restrict q; ssize_t start_x, stop_x; if (status == MagickFalse) continue; start_x=CastDoubleToLong(ceil(bounds.x1-0.5)); stop_x=CastDoubleToLong(floor(bounds.x2+0.5)); x=start_x; q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop_x-x+1),1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for ( ; x <= stop_x; x++) { if ((x == CastDoubleToLong(ceil(primitive_info->point.x-0.5))) && (y == CastDoubleToLong(ceil(primitive_info->point.y-0.5)))) { GetFillColor(draw_info,x-start_x,y-start_y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); } q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); polygon_info=DestroyPolygonThreadSet(polygon_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " end draw-polygon"); return(status); } /* Draw polygon or line. */ start_y=CastDoubleToLong(ceil(bounds.y1-0.5)); stop_y=CastDoubleToLong(floor(bounds.y2+0.5)); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,stop_y-start_y+1,1) #endif for (y=start_y; y <= stop_y; y++) { const int id = GetOpenMPThreadId(); Quantum *magick_restrict q; ssize_t x; ssize_t start_x, stop_x; if (status == MagickFalse) continue; start_x=CastDoubleToLong(ceil(bounds.x1-0.5)); stop_x=CastDoubleToLong(floor(bounds.x2+0.5)); q=GetCacheViewAuthenticPixels(image_view,start_x,y,(size_t) (stop_x-start_x+ 1),1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=start_x; x <= stop_x; x++) { double fill_alpha, stroke_alpha; PixelInfo fill_color, stroke_color; /* Fill and/or stroke. */ fill_alpha=GetFillAlpha(polygon_info[id],mid,fill,draw_info->fill_rule, x,y,&stroke_alpha); if (draw_info->stroke_antialias == MagickFalse) { fill_alpha=fill_alpha > 0.5 ? 1.0 : 0.0; stroke_alpha=stroke_alpha > 0.5 ? 1.0 : 0.0; } GetFillColor(draw_info,x-start_x,y-start_y,&fill_color,exception); CompositePixelOver(image,&fill_color,fill_alpha*fill_color.alpha,q, (double) GetPixelAlpha(image,q),q); GetStrokeColor(draw_info,x-start_x,y-start_y,&stroke_color,exception); CompositePixelOver(image,&stroke_color,stroke_alpha*stroke_color.alpha,q, (double) GetPixelAlpha(image,q),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); polygon_info=DestroyPolygonThreadSet(polygon_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-polygon"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPrimitive() draws a primitive (line, rectangle, ellipse) on the image. % % The format of the DrawPrimitive method is: % % MagickBooleanType DrawPrimitive(Image *image,const DrawInfo *draw_info, % PrimitiveInfo *primitive_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % o exception: return any errors or warnings in this structure. % */ static void LogPrimitiveInfo(const PrimitiveInfo *primitive_info) { const char *methods[] = { "point", "replace", "floodfill", "filltoborder", "reset", "?" }; PointInfo p, point, q; ssize_t i, x; ssize_t coordinates, y; x=CastDoubleToLong(ceil(primitive_info->point.x-0.5)); y=CastDoubleToLong(ceil(primitive_info->point.y-0.5)); switch (primitive_info->primitive) { case AlphaPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "AlphaPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case ColorPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "ColorPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case ImagePrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "ImagePrimitive %.20g,%.20g",(double) x,(double) y); return; } case PointPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "PointPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case TextPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "TextPrimitive %.20g,%.20g",(double) x,(double) y); return; } default: break; } coordinates=0; p=primitive_info[0].point; q.x=(-1.0); q.y=(-1.0); for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { point=primitive_info[i].point; if (coordinates <= 0) { coordinates=(ssize_t) primitive_info[i].coordinates; (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin open (%.20g)",(double) coordinates); p=point; } point=primitive_info[i].point; if ((fabs(q.x-point.x) >= MagickEpsilon) || (fabs(q.y-point.y) >= MagickEpsilon)) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %.20g: %.18g,%.18g",(double) coordinates,point.x,point.y); else (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %.20g: %g %g (duplicate)",(double) coordinates,point.x,point.y); q=point; coordinates--; if (coordinates > 0) continue; if ((fabs(p.x-point.x) >= MagickEpsilon) || (fabs(p.y-point.y) >= MagickEpsilon)) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end last (%.20g)", (double) coordinates); else (void) LogMagickEvent(DrawEvent,GetMagickModule()," end open (%.20g)", (double) coordinates); } } MagickExport MagickBooleanType DrawPrimitive(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { CacheView *image_view; MagickStatusType status; ssize_t i, x; ssize_t y; if (image->debug != MagickFalse) { (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin draw-primitive"); (void) LogMagickEvent(DrawEvent,GetMagickModule(), " affine: %g,%g,%g,%g,%g,%g",draw_info->affine.sx, draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy, draw_info->affine.tx,draw_info->affine.ty); } status=MagickTrue; if ((IsGrayColorspace(image->colorspace) != MagickFalse) && ((IsPixelInfoGray(&draw_info->fill) == MagickFalse) || (IsPixelInfoGray(&draw_info->stroke) == MagickFalse))) status&=SetImageColorspace(image,sRGBColorspace,exception); if (draw_info->compliance == SVGCompliance) { status&=SetImageMask(image,WritePixelMask,draw_info->clipping_mask, exception); status&=SetImageMask(image,CompositePixelMask,draw_info->composite_mask, exception); } x=CastDoubleToLong(ceil(primitive_info->point.x-0.5)); y=CastDoubleToLong(ceil(primitive_info->point.y-0.5)); image_view=AcquireAuthenticCacheView(image,exception); switch (primitive_info->primitive) { case AlphaPrimitive: { if (image->alpha_trait == UndefinedPixelTrait) status&=SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); switch (primitive_info->method) { case PointMethod: default: { PixelInfo pixel; Quantum *q; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (Quantum *) NULL) break; GetFillColor(draw_info,x,y,&pixel,exception); SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); status&=SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { PixelInfo pixel, target; status&=GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, exception); GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,q,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse) { q+=GetPixelChannels(image); continue; } GetFillColor(draw_info,x,y,&pixel,exception); SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } status&=SyncCacheViewAuthenticPixels(image_view,exception); if (status == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { ChannelType channel_mask; PixelInfo target; status&=GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y, &target,exception); if (primitive_info->method == FillToBorderMethod) { target.red=(double) draw_info->border_color.red; target.green=(double) draw_info->border_color.green; target.blue=(double) draw_info->border_color.blue; } channel_mask=SetImageChannelMask(image,AlphaChannel); status&=FloodfillPaintImage(image,draw_info,&target,x,y, primitive_info->method == FloodfillMethod ? MagickFalse : MagickTrue,exception); (void) SetImageChannelMask(image,channel_mask); break; } case ResetMethod: { PixelInfo pixel; for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetFillColor(draw_info,x,y,&pixel,exception); SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } status&=SyncCacheViewAuthenticPixels(image_view,exception); if (status == MagickFalse) break; } break; } } break; } case ColorPrimitive: { switch (primitive_info->method) { case PointMethod: default: { PixelInfo pixel; Quantum *q; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (Quantum *) NULL) break; GetPixelInfo(image,&pixel); GetFillColor(draw_info,x,y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); status&=SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { PixelInfo pixel, target; status&=GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, exception); for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,q,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse) { q+=GetPixelChannels(image); continue; } GetFillColor(draw_info,x,y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } status&=SyncCacheViewAuthenticPixels(image_view,exception); if (status == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { PixelInfo target; status&=GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y, &target,exception); if (primitive_info->method == FillToBorderMethod) { target.red=(double) draw_info->border_color.red; target.green=(double) draw_info->border_color.green; target.blue=(double) draw_info->border_color.blue; } status&=FloodfillPaintImage(image,draw_info,&target,x,y, primitive_info->method == FloodfillMethod ? MagickFalse : MagickTrue,exception); break; } case ResetMethod: { PixelInfo pixel; GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetFillColor(draw_info,x,y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } status&=SyncCacheViewAuthenticPixels(image_view,exception); if (status == MagickFalse) break; } break; } } break; } case ImagePrimitive: { AffineMatrix affine; char composite_geometry[MagickPathExtent]; Image *composite_image, *composite_images; ImageInfo *clone_info; RectangleInfo geometry; ssize_t x1, y1; if (primitive_info->text == (char *) NULL) break; clone_info=AcquireImageInfo(); composite_images=(Image *) NULL; if (LocaleNCompare(primitive_info->text,"data:",5) == 0) composite_images=ReadInlineImage(clone_info,primitive_info->text, exception); else if (*primitive_info->text != '\0') { (void) CopyMagickString(clone_info->filename,primitive_info->text, MagickPathExtent); status&=SetImageInfo(clone_info,0,exception); if ((LocaleNCompare(clone_info->magick,"http",4) == 0) || (LocaleCompare(clone_info->magick,"mpri") == 0)) (void) CopyMagickString(clone_info->filename,primitive_info->text, MagickPathExtent); if (clone_info->size != (char *) NULL) clone_info->size=DestroyString(clone_info->size); if (clone_info->extract != (char *) NULL) clone_info->extract=DestroyString(clone_info->extract); if (*clone_info->filename != '\0') composite_images=ReadImage(clone_info,exception); } clone_info=DestroyImageInfo(clone_info); if (composite_images == (Image *) NULL) { status=MagickFalse; break; } composite_image=RemoveFirstImageFromList(&composite_images); composite_images=DestroyImageList(composite_images); (void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor) NULL,(void *) NULL); x1=CastDoubleToLong(ceil(primitive_info[1].point.x-0.5)); y1=CastDoubleToLong(ceil(primitive_info[1].point.y-0.5)); if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) || ((y1 != 0L) && (y1 != (ssize_t) composite_image->rows))) { /* Resize image. */ (void) FormatLocaleString(composite_geometry,MagickPathExtent, "%gx%g!",primitive_info[1].point.x,primitive_info[1].point.y); composite_image->filter=image->filter; status&=TransformImage(&composite_image,(char *) NULL, composite_geometry,exception); } if (composite_image->alpha_trait == UndefinedPixelTrait) status&=SetImageAlphaChannel(composite_image,OpaqueAlphaChannel, exception); if (draw_info->alpha != OpaqueAlpha) status&=SetImageAlpha(composite_image,draw_info->alpha,exception); SetGeometry(image,&geometry); image->gravity=draw_info->gravity; geometry.x=x; geometry.y=y; (void) FormatLocaleString(composite_geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,(double) composite_image->rows,(double) geometry.x,(double) geometry.y); (void) ParseGravityGeometry(image,composite_geometry,&geometry,exception); affine=draw_info->affine; affine.tx=(double) geometry.x; affine.ty=(double) geometry.y; composite_image->interpolate=image->interpolate; if ((draw_info->compose == OverCompositeOp) || (draw_info->compose == SrcOverCompositeOp)) status&=DrawAffineImage(image,composite_image,&affine,exception); else status&=CompositeImage(image,composite_image,draw_info->compose, MagickTrue,geometry.x,geometry.y,exception); composite_image=DestroyImage(composite_image); break; } case PointPrimitive: { PixelInfo fill_color; Quantum *q; if ((y < 0) || (y >= (ssize_t) image->rows)) break; if ((x < 0) || (x >= (ssize_t) image->columns)) break; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (Quantum *) NULL) break; GetFillColor(draw_info,x,y,&fill_color,exception); CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q,(double) GetPixelAlpha(image,q),q); status&=SyncCacheViewAuthenticPixels(image_view,exception); break; } case TextPrimitive: { char geometry[MagickPathExtent]; DrawInfo *clone_info; if (primitive_info->text == (char *) NULL) break; clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->text,primitive_info->text); (void) FormatLocaleString(geometry,MagickPathExtent,"%+f%+f", primitive_info->point.x,primitive_info->point.y); (void) CloneString(&clone_info->geometry,geometry); status&=AnnotateImage(image,clone_info,exception); clone_info=DestroyDrawInfo(clone_info); break; } default: { double mid, scale; DrawInfo *clone_info; if (IsEventLogging() != MagickFalse) LogPrimitiveInfo(primitive_info); scale=ExpandAffine(&draw_info->affine); if ((draw_info->dash_pattern != (double *) NULL) && (fabs(draw_info->dash_pattern[0]) >= MagickEpsilon) && (fabs(scale*draw_info->stroke_width) >= MagickEpsilon) && (draw_info->stroke.alpha != (Quantum) TransparentAlpha)) { /* Draw dash polygon. */ clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->stroke_width=0.0; clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; status&=DrawPolygonPrimitive(image,clone_info,primitive_info, exception); clone_info=DestroyDrawInfo(clone_info); if (status != MagickFalse) status&=DrawDashPolygon(draw_info,primitive_info,image,exception); break; } mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; if ((mid > 1.0) && ((draw_info->stroke.alpha != (Quantum) TransparentAlpha) || (draw_info->stroke_pattern != (Image *) NULL))) { double x, y; MagickBooleanType closed_path; /* Draw strokes while respecting line cap/join attributes. */ closed_path=primitive_info[0].closed_subpath; i=(ssize_t) primitive_info[0].coordinates; x=fabs(primitive_info[i-1].point.x-primitive_info[0].point.x); y=fabs(primitive_info[i-1].point.y-primitive_info[0].point.y); if ((x < MagickEpsilon) && (y < MagickEpsilon)) closed_path=MagickTrue; if ((((draw_info->linecap == RoundCap) || (closed_path != MagickFalse)) && (draw_info->linejoin == RoundJoin)) || (primitive_info[i].primitive != UndefinedPrimitive)) { status&=DrawPolygonPrimitive(image,draw_info,primitive_info, exception); break; } clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->stroke_width=0.0; clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; status&=DrawPolygonPrimitive(image,clone_info,primitive_info, exception); clone_info=DestroyDrawInfo(clone_info); if (status != MagickFalse) status&=DrawStrokePolygon(image,draw_info,primitive_info,exception); break; } status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception); break; } } image_view=DestroyCacheView(image_view); if (draw_info->compliance == SVGCompliance) { status&=SetImageMask(image,WritePixelMask,(Image *) NULL,exception); status&=SetImageMask(image,CompositePixelMask,(Image *) NULL,exception); } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-primitive"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w S t r o k e P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawStrokePolygon() draws a stroked polygon (line, rectangle, ellipse) on % the image while respecting the line cap and join attributes. % % The format of the DrawStrokePolygon method is: % % MagickBooleanType DrawStrokePolygon(Image *image, % const DrawInfo *draw_info,const PrimitiveInfo *primitive_info) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % */ static MagickBooleanType DrawRoundLinecap(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { PrimitiveInfo linecap[5]; ssize_t i; for (i=0; i < 4; i++) linecap[i]=(*primitive_info); linecap[0].coordinates=4; linecap[1].point.x+=2.0*MagickEpsilon; linecap[2].point.x+=2.0*MagickEpsilon; linecap[2].point.y+=2.0*MagickEpsilon; linecap[3].point.y+=2.0*MagickEpsilon; linecap[4].primitive=UndefinedPrimitive; return(DrawPolygonPrimitive(image,draw_info,linecap,exception)); } static MagickBooleanType DrawStrokePolygon(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { DrawInfo *clone_info; MagickBooleanType closed_path; MagickStatusType status; PrimitiveInfo *stroke_polygon; const PrimitiveInfo *p, *q; /* Draw stroked polygon. */ if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin draw-stroke-polygon"); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->fill=draw_info->stroke; if (clone_info->fill_pattern != (Image *) NULL) clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern); if (clone_info->stroke_pattern != (Image *) NULL) clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0, MagickTrue,exception); clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; clone_info->stroke_width=0.0; clone_info->fill_rule=NonZeroRule; status=MagickTrue; for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates) { if (p->coordinates == 1) continue; stroke_polygon=TraceStrokePolygon(draw_info,p,exception); if (stroke_polygon == (PrimitiveInfo *) NULL) { status=0; break; } status&=DrawPolygonPrimitive(image,clone_info,stroke_polygon,exception); stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon); if (status == 0) break; q=p+p->coordinates-1; closed_path=p->closed_subpath; if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse)) { status&=DrawRoundLinecap(image,draw_info,p,exception); status&=DrawRoundLinecap(image,draw_info,q,exception); } } clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " end draw-stroke-polygon"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A f f i n e M a t r i x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAffineMatrix() returns an AffineMatrix initialized to the identity % matrix. % % The format of the GetAffineMatrix method is: % % void GetAffineMatrix(AffineMatrix *affine_matrix) % % A description of each parameter follows: % % o affine_matrix: the affine matrix. % */ MagickExport void GetAffineMatrix(AffineMatrix *affine_matrix) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(affine_matrix != (AffineMatrix *) NULL); (void) memset(affine_matrix,0,sizeof(*affine_matrix)); affine_matrix->sx=1.0; affine_matrix->sy=1.0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetDrawInfo() initializes draw_info to default values from image_info. % % The format of the GetDrawInfo method is: % % void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) % % A description of each parameter follows: % % o image_info: the image info.. % % o draw_info: the draw info. % */ MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) { char *next_token; const char *option; ExceptionInfo *exception; ImageInfo *clone_info; /* Initialize draw attributes. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info != (DrawInfo *) NULL); (void) memset(draw_info,0,sizeof(*draw_info)); clone_info=CloneImageInfo(image_info); GetAffineMatrix(&draw_info->affine); exception=AcquireExceptionInfo(); (void) QueryColorCompliance("#000F",AllCompliance,&draw_info->fill, exception); (void) QueryColorCompliance("#FFF0",AllCompliance,&draw_info->stroke, exception); draw_info->stroke_antialias=clone_info->antialias; draw_info->stroke_width=1.0; draw_info->fill_rule=EvenOddRule; draw_info->alpha=OpaqueAlpha; draw_info->fill_alpha=OpaqueAlpha; draw_info->stroke_alpha=OpaqueAlpha; draw_info->linecap=ButtCap; draw_info->linejoin=MiterJoin; draw_info->miterlimit=10; draw_info->decorate=NoDecoration; draw_info->pointsize=12.0; draw_info->undercolor.alpha=(MagickRealType) TransparentAlpha; draw_info->compose=OverCompositeOp; draw_info->render=MagickTrue; draw_info->clip_path=MagickFalse; draw_info->debug=IsEventLogging(); if (clone_info->font != (char *) NULL) draw_info->font=AcquireString(clone_info->font); if (clone_info->density != (char *) NULL) draw_info->density=AcquireString(clone_info->density); draw_info->text_antialias=clone_info->antialias; if (fabs(clone_info->pointsize) >= MagickEpsilon) draw_info->pointsize=clone_info->pointsize; draw_info->border_color=clone_info->border_color; if (clone_info->server_name != (char *) NULL) draw_info->server_name=AcquireString(clone_info->server_name); option=GetImageOption(clone_info,"direction"); if (option != (const char *) NULL) draw_info->direction=(DirectionType) ParseCommandOption( MagickDirectionOptions,MagickFalse,option); else draw_info->direction=UndefinedDirection; option=GetImageOption(clone_info,"encoding"); if (option != (const char *) NULL) (void) CloneString(&draw_info->encoding,option); option=GetImageOption(clone_info,"family"); if (option != (const char *) NULL) (void) CloneString(&draw_info->family,option); option=GetImageOption(clone_info,"fill"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->fill, exception); option=GetImageOption(clone_info,"gravity"); if (option != (const char *) NULL) draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,option); option=GetImageOption(clone_info,"interline-spacing"); if (option != (const char *) NULL) draw_info->interline_spacing=GetDrawValue(option,&next_token); option=GetImageOption(clone_info,"interword-spacing"); if (option != (const char *) NULL) draw_info->interword_spacing=GetDrawValue(option,&next_token); option=GetImageOption(clone_info,"kerning"); if (option != (const char *) NULL) draw_info->kerning=GetDrawValue(option,&next_token); option=GetImageOption(clone_info,"stroke"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke, exception); option=GetImageOption(clone_info,"strokewidth"); if (option != (const char *) NULL) draw_info->stroke_width=GetDrawValue(option,&next_token); option=GetImageOption(clone_info,"style"); if (option != (const char *) NULL) draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions, MagickFalse,option); option=GetImageOption(clone_info,"undercolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor, exception); option=GetImageOption(clone_info,"weight"); if (option != (const char *) NULL) { ssize_t weight; weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option); if (weight == -1) weight=(ssize_t) StringToUnsignedLong(option); draw_info->weight=(size_t) weight; } exception=DestroyExceptionInfo(exception); draw_info->signature=MagickCoreSignature; clone_info=DestroyImageInfo(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P e r m u t a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Permutate() returns the permuation of the (n,k). % % The format of the Permutate method is: % % void Permutate(ssize_t n,ssize_t k) % % A description of each parameter follows: % % o n: % % o k: % % */ static inline double Permutate(const ssize_t n,const ssize_t k) { double r; ssize_t i; r=1.0; for (i=k+1; i <= n; i++) r*=i; for (i=1; i <= (n-k); i++) r/=i; return(r); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + T r a c e P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TracePrimitive is a collection of methods for generating graphic % primitives such as arcs, ellipses, paths, etc. % */ static MagickBooleanType TraceArc(MVGInfo *mvg_info,const PointInfo start, const PointInfo end,const PointInfo degrees) { PointInfo center, radius; center.x=0.5*(end.x+start.x); center.y=0.5*(end.y+start.y); radius.x=fabs(center.x-start.x); radius.y=fabs(center.y-start.y); return(TraceEllipse(mvg_info,center,radius,degrees)); } static MagickBooleanType TraceArcPath(MVGInfo *mvg_info,const PointInfo start, const PointInfo end,const PointInfo arc,const double angle, const MagickBooleanType large_arc,const MagickBooleanType sweep) { double alpha, beta, delta, factor, gamma, theta; MagickStatusType status; PointInfo center, points[3], radii; double cosine, sine; PrimitiveInfo *primitive_info; PrimitiveInfo *p; ssize_t i; size_t arc_segments; ssize_t offset; offset=mvg_info->offset; primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; primitive_info->coordinates=0; if ((fabs(start.x-end.x) < MagickEpsilon) && (fabs(start.y-end.y) < MagickEpsilon)) return(TracePoint(primitive_info,end)); radii.x=fabs(arc.x); radii.y=fabs(arc.y); if ((radii.x < MagickEpsilon) || (radii.y < MagickEpsilon)) return(TraceLine(primitive_info,start,end)); cosine=cos(DegreesToRadians(fmod((double) angle,360.0))); sine=sin(DegreesToRadians(fmod((double) angle,360.0))); center.x=(double) (cosine*(end.x-start.x)/2+sine*(end.y-start.y)/2); center.y=(double) (cosine*(end.y-start.y)/2-sine*(end.x-start.x)/2); delta=(center.x*center.x)/(radii.x*radii.x)+(center.y*center.y)/ (radii.y*radii.y); if (delta < MagickEpsilon) return(TraceLine(primitive_info,start,end)); if (delta > 1.0) { radii.x*=sqrt((double) delta); radii.y*=sqrt((double) delta); } points[0].x=(double) (cosine*start.x/radii.x+sine*start.y/radii.x); points[0].y=(double) (cosine*start.y/radii.y-sine*start.x/radii.y); points[1].x=(double) (cosine*end.x/radii.x+sine*end.y/radii.x); points[1].y=(double) (cosine*end.y/radii.y-sine*end.x/radii.y); alpha=points[1].x-points[0].x; beta=points[1].y-points[0].y; if (fabs(alpha*alpha+beta*beta) < MagickEpsilon) return(TraceLine(primitive_info,start,end)); factor=PerceptibleReciprocal(alpha*alpha+beta*beta)-0.25; if (factor <= 0.0) factor=0.0; else { factor=sqrt((double) factor); if (sweep == large_arc) factor=(-factor); } center.x=(double) ((points[0].x+points[1].x)/2-factor*beta); center.y=(double) ((points[0].y+points[1].y)/2+factor*alpha); alpha=atan2(points[0].y-center.y,points[0].x-center.x); theta=atan2(points[1].y-center.y,points[1].x-center.x)-alpha; if ((theta < 0.0) && (sweep != MagickFalse)) theta+=2.0*MagickPI; else if ((theta > 0.0) && (sweep == MagickFalse)) theta-=2.0*MagickPI; arc_segments=(size_t) CastDoubleToLong(ceil(fabs((double) (theta/(0.5* MagickPI+MagickEpsilon))))); status=MagickTrue; p=primitive_info; for (i=0; i < (ssize_t) arc_segments; i++) { beta=0.5*((alpha+(i+1)*theta/arc_segments)-(alpha+i*theta/arc_segments)); gamma=(8.0/3.0)*sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))* sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))/ sin(fmod((double) beta,DegreesToRadians(360.0))); points[0].x=(double) (center.x+cos(fmod((double) (alpha+(double) i*theta/ arc_segments),DegreesToRadians(360.0)))-gamma*sin(fmod((double) (alpha+ (double) i*theta/arc_segments),DegreesToRadians(360.0)))); points[0].y=(double) (center.y+sin(fmod((double) (alpha+(double) i*theta/ arc_segments),DegreesToRadians(360.0)))+gamma*cos(fmod((double) (alpha+ (double) i*theta/arc_segments),DegreesToRadians(360.0)))); points[2].x=(double) (center.x+cos(fmod((double) (alpha+(double) (i+1)* theta/arc_segments),DegreesToRadians(360.0)))); points[2].y=(double) (center.y+sin(fmod((double) (alpha+(double) (i+1)* theta/arc_segments),DegreesToRadians(360.0)))); points[1].x=(double) (points[2].x+gamma*sin(fmod((double) (alpha+(double) (i+1)*theta/arc_segments),DegreesToRadians(360.0)))); points[1].y=(double) (points[2].y-gamma*cos(fmod((double) (alpha+(double) (i+1)*theta/arc_segments),DegreesToRadians(360.0)))); p->point.x=(p == primitive_info) ? start.x : (p-1)->point.x; p->point.y=(p == primitive_info) ? start.y : (p-1)->point.y; (p+1)->point.x=(double) (cosine*radii.x*points[0].x-sine*radii.y* points[0].y); (p+1)->point.y=(double) (sine*radii.x*points[0].x+cosine*radii.y* points[0].y); (p+2)->point.x=(double) (cosine*radii.x*points[1].x-sine*radii.y* points[1].y); (p+2)->point.y=(double) (sine*radii.x*points[1].x+cosine*radii.y* points[1].y); (p+3)->point.x=(double) (cosine*radii.x*points[2].x-sine*radii.y* points[2].y); (p+3)->point.y=(double) (sine*radii.x*points[2].x+cosine*radii.y* points[2].y); if (i == (ssize_t) (arc_segments-1)) (p+3)->point=end; status&=TraceBezier(mvg_info,4); if (status == 0) break; p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; p+=p->coordinates; } if (status == 0) return(MagickFalse); mvg_info->offset=offset; primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } return(MagickTrue); } static MagickBooleanType TraceBezier(MVGInfo *mvg_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; PrimitiveInfo *primitive_info; PrimitiveInfo *p; ssize_t i, j; size_t control_points, quantum; /* Allocate coefficients. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=number_coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { for (j=i+1; j < (ssize_t) number_coordinates; j++) { alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x); if (alpha > (double) MAGICK_SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) MAGICK_SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; } } primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=MagickMin(quantum/number_coordinates,BezierQuantum); coefficients=(double *) AcquireQuantumMemory(number_coordinates, sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates* sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) { if (points != (PointInfo *) NULL) points=(PointInfo *) RelinquishMagickMemory(points); if (coefficients != (double *) NULL) coefficients=(double *) RelinquishMagickMemory(coefficients); (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } control_points=quantum*number_coordinates; if (CheckPrimitiveExtent(mvg_info,(double) control_points+1) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; /* Compute bezier points. */ end=primitive_info[number_coordinates-1].point; for (i=0; i < (ssize_t) number_coordinates; i++) coefficients[i]=Permutate((ssize_t) number_coordinates-1,i); weight=0.0; for (i=0; i < (ssize_t) control_points; i++) { p=primitive_info; point.x=0.0; point.y=0.0; alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0); for (j=0; j < (ssize_t) number_coordinates; j++) { point.x+=alpha*coefficients[j]*p->point.x; point.y+=alpha*coefficients[j]*p->point.y; alpha*=weight/(1.0-weight); p++; } points[i]=point; weight+=1.0/control_points; } /* Bezier curves are just short segmented polys. */ p=primitive_info; for (i=0; i < (ssize_t) control_points; i++) { if (TracePoint(p,points[i]) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; } if (TracePoint(p,end) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickTrue); } static MagickBooleanType TraceCircle(MVGInfo *mvg_info,const PointInfo start, const PointInfo end) { double alpha, beta, radius; PointInfo offset, degrees; alpha=end.x-start.x; beta=end.y-start.y; radius=hypot((double) alpha,(double) beta); offset.x=(double) radius; offset.y=(double) radius; degrees.x=0.0; degrees.y=360.0; return(TraceEllipse(mvg_info,start,offset,degrees)); } static MagickBooleanType TraceEllipse(MVGInfo *mvg_info,const PointInfo center, const PointInfo radii,const PointInfo arc) { double coordinates, delta, step, x, y; PointInfo angle, point; PrimitiveInfo *primitive_info; PrimitiveInfo *p; ssize_t i; /* Ellipses are just short segmented polys. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; primitive_info->coordinates=0; if ((fabs(radii.x) < MagickEpsilon) || (fabs(radii.y) < MagickEpsilon)) return(MagickTrue); delta=2.0*PerceptibleReciprocal(MagickMax(radii.x,radii.y)); step=MagickPI/8.0; if ((delta >= 0.0) && (delta < (MagickPI/8.0))) step=MagickPI/4.0/(MagickPI*PerceptibleReciprocal(delta)/2.0); angle.x=DegreesToRadians(arc.x); y=arc.y; while (y < arc.x) y+=360.0; angle.y=DegreesToRadians(y); coordinates=ceil((angle.y-angle.x)/step+1.0); if (CheckPrimitiveExtent(mvg_info,coordinates) == MagickFalse) return(MagickFalse); primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; for (p=primitive_info; angle.x < angle.y; angle.x+=step) { point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*radii.x+center.x; point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*radii.y+center.y; if (TracePoint(p,point) == MagickFalse) return(MagickFalse); p+=p->coordinates; } point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*radii.x+center.x; point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*radii.y+center.y; if (TracePoint(p,point) == MagickFalse) return(MagickFalse); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; x=fabs(primitive_info[0].point.x- primitive_info[primitive_info->coordinates-1].point.x); y=fabs(primitive_info[0].point.y- primitive_info[primitive_info->coordinates-1].point.y); if ((x < MagickEpsilon) && (y < MagickEpsilon)) primitive_info->closed_subpath=MagickTrue; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } return(MagickTrue); } static MagickBooleanType TraceLine(PrimitiveInfo *primitive_info, const PointInfo start,const PointInfo end) { if (TracePoint(primitive_info,start) == MagickFalse) return(MagickFalse); if ((fabs(start.x-end.x) < MagickEpsilon) && (fabs(start.y-end.y) < MagickEpsilon)) { primitive_info->primitive=PointPrimitive; primitive_info->coordinates=1; return(MagickTrue); } if (TracePoint(primitive_info+1,end) == MagickFalse) return(MagickFalse); (primitive_info+1)->primitive=primitive_info->primitive; primitive_info->coordinates=2; primitive_info->closed_subpath=MagickFalse; return(MagickTrue); } static ssize_t TracePath(MVGInfo *mvg_info,const char *path, ExceptionInfo *exception) { char *next_token, token[MagickPathExtent]; const char *p; double x, y; int attribute, last_attribute; MagickBooleanType status; PointInfo end = {0.0, 0.0}, points[4] = { {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0} }, point = {0.0, 0.0}, start = {0.0, 0.0}; PrimitiveInfo *primitive_info; PrimitiveType primitive_type; PrimitiveInfo *q; ssize_t i; size_t number_coordinates, z_count; ssize_t subpath_offset; subpath_offset=mvg_info->offset; primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; status=MagickTrue; attribute=0; number_coordinates=0; z_count=0; primitive_type=primitive_info->primitive; q=primitive_info; for (p=path; *p != '\0'; ) { if (status == MagickFalse) break; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == '\0') break; last_attribute=attribute; attribute=(int) (*p++); switch (attribute) { case 'a': case 'A': { double angle = 0.0; MagickBooleanType large_arc = MagickFalse, sweep = MagickFalse; PointInfo arc = {0.0, 0.0}; /* Elliptical arc. */ do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); arc.x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); arc.y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); angle=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse; (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse; if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); end.x=(double) (attribute == (int) 'A' ? x : point.x+x); end.y=(double) (attribute == (int) 'A' ? y : point.y+y); if (TraceArcPath(mvg_info,point,end,arc,angle,large_arc,sweep) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'c': case 'C': { /* Cubic Bézier curve. */ do { points[0]=point; for (i=1; i < 4; i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); end.x=(double) (attribute == (int) 'C' ? x : point.x+x); end.y=(double) (attribute == (int) 'C' ? y : point.y+y); points[i]=end; } for (i=0; i < 4; i++) (q+i)->point=points[i]; if (TraceBezier(mvg_info,4) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'H': case 'h': { do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); point.x=(double) (attribute == (int) 'H' ? x: point.x+x); if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(-1); mvg_info->offset+=q->coordinates; q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'l': case 'L': { /* Line to. */ do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); point.x=(double) (attribute == (int) 'L' ? x : point.x+x); point.y=(double) (attribute == (int) 'L' ? y : point.y+y); if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(-1); mvg_info->offset+=q->coordinates; q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'M': case 'm': { /* Move to. */ if (mvg_info->offset != subpath_offset) { primitive_info=(*mvg_info->primitive_info)+subpath_offset; primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; primitive_info=q; subpath_offset=mvg_info->offset; } i=0; do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); point.x=(double) (attribute == (int) 'M' ? x : point.x+x); point.y=(double) (attribute == (int) 'M' ? y : point.y+y); if (i == 0) start=point; i++; if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(-1); mvg_info->offset+=q->coordinates; q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'q': case 'Q': { /* Quadratic Bézier curve. */ do { points[0]=point; for (i=1; i < 3; i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); if (*p == ',') p++; end.x=(double) (attribute == (int) 'Q' ? x : point.x+x); end.y=(double) (attribute == (int) 'Q' ? y : point.y+y); points[i]=end; } for (i=0; i < 3; i++) (q+i)->point=points[i]; if (TraceBezier(mvg_info,3) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 's': case 'S': { /* Cubic Bézier curve. */ do { points[0]=points[3]; points[1].x=2.0*points[3].x-points[2].x; points[1].y=2.0*points[3].y-points[2].y; for (i=2; i < 4; i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); if (*p == ',') p++; end.x=(double) (attribute == (int) 'S' ? x : point.x+x); end.y=(double) (attribute == (int) 'S' ? y : point.y+y); points[i]=end; } if (strchr("CcSs",last_attribute) == (char *) NULL) { points[0]=point; points[1]=point; } for (i=0; i < 4; i++) (q+i)->point=points[i]; if (TraceBezier(mvg_info,4) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; last_attribute=attribute; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 't': case 'T': { /* Quadratic Bézier curve. */ do { points[0]=points[2]; points[1].x=2.0*points[2].x-points[1].x; points[1].y=2.0*points[2].y-points[1].y; for (i=2; i < 3; i++) { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); x=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); end.x=(double) (attribute == (int) 'T' ? x : point.x+x); end.y=(double) (attribute == (int) 'T' ? y : point.y+y); points[i]=end; } if (status == MagickFalse) break; if (strchr("QqTt",last_attribute) == (char *) NULL) { points[0]=point; points[1]=point; } for (i=0; i < 3; i++) (q+i)->point=points[i]; if (TraceBezier(mvg_info,3) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=q->coordinates; q+=q->coordinates; point=end; last_attribute=attribute; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'v': case 'V': { /* Line to. */ do { (void) GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') (void) GetNextToken(p,&p,MagickPathExtent,token); y=GetDrawValue(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); point.y=(double) (attribute == (int) 'V' ? y : point.y+y); if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(-1); mvg_info->offset+=q->coordinates; q+=q->coordinates; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'z': case 'Z': { /* Close path. */ point=start; if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(-1); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(-1); mvg_info->offset+=q->coordinates; q+=q->coordinates; primitive_info=(*mvg_info->primitive_info)+subpath_offset; primitive_info->coordinates=(size_t) (q-primitive_info); primitive_info->closed_subpath=MagickTrue; number_coordinates+=primitive_info->coordinates; primitive_info=q; subpath_offset=mvg_info->offset; z_count++; break; } default: { ThrowPointExpectedException(token,exception); break; } } } if (status == MagickFalse) return(-1); primitive_info=(*mvg_info->primitive_info)+subpath_offset; primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { q--; q->primitive=primitive_type; if (z_count > 1) q->method=FillToBorderMethod; } q=primitive_info; return((ssize_t) number_coordinates); } static MagickBooleanType TraceRectangle(PrimitiveInfo *primitive_info, const PointInfo start,const PointInfo end) { PointInfo point; PrimitiveInfo *p; ssize_t i; p=primitive_info; if (TracePoint(p,start) == MagickFalse) return(MagickFalse); p+=p->coordinates; point.x=start.x; point.y=end.y; if (TracePoint(p,point) == MagickFalse) return(MagickFalse); p+=p->coordinates; if (TracePoint(p,end) == MagickFalse) return(MagickFalse); p+=p->coordinates; point.x=end.x; point.y=start.y; if (TracePoint(p,point) == MagickFalse) return(MagickFalse); p+=p->coordinates; if (TracePoint(p,start) == MagickFalse) return(MagickFalse); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickTrue; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } return(MagickTrue); } static MagickBooleanType TraceRoundRectangle(MVGInfo *mvg_info, const PointInfo start,const PointInfo end,PointInfo arc) { PointInfo degrees, point, segment; PrimitiveInfo *primitive_info; PrimitiveInfo *p; ssize_t i; ssize_t offset; offset=mvg_info->offset; segment.x=fabs(end.x-start.x); segment.y=fabs(end.y-start.y); if ((segment.x < MagickEpsilon) || (segment.y < MagickEpsilon)) { (*mvg_info->primitive_info+mvg_info->offset)->coordinates=0; return(MagickTrue); } if (arc.x > (0.5*segment.x)) arc.x=0.5*segment.x; if (arc.y > (0.5*segment.y)) arc.y=0.5*segment.y; point.x=start.x+segment.x-arc.x; point.y=start.y+arc.y; degrees.x=270.0; degrees.y=360.0; if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; point.x=start.x+segment.x-arc.x; point.y=start.y+segment.y-arc.y; degrees.x=0.0; degrees.y=90.0; if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; point.x=start.x+arc.x; point.y=start.y+segment.y-arc.y; degrees.x=90.0; degrees.y=180.0; if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; point.x=start.x+arc.x; point.y=start.y+arc.y; degrees.x=180.0; degrees.y=270.0; if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse) return(MagickFalse); p=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(p,(*mvg_info->primitive_info+offset)->point) == MagickFalse) return(MagickFalse); p+=p->coordinates; mvg_info->offset=offset; primitive_info=(*mvg_info->primitive_info)+offset; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickTrue; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } return(MagickTrue); } static MagickBooleanType TraceSquareLinecap(PrimitiveInfo *primitive_info, const size_t number_vertices,const double offset) { double distance; double dx, dy; ssize_t i; ssize_t j; dx=0.0; dy=0.0; for (i=1; i < (ssize_t) number_vertices; i++) { dx=primitive_info[0].point.x-primitive_info[i].point.x; dy=primitive_info[0].point.y-primitive_info[i].point.y; if ((fabs((double) dx) >= MagickEpsilon) || (fabs((double) dy) >= MagickEpsilon)) break; } if (i == (ssize_t) number_vertices) i=(ssize_t) number_vertices-1L; distance=hypot((double) dx,(double) dy); primitive_info[0].point.x=(double) (primitive_info[i].point.x+ dx*(distance+offset)/distance); primitive_info[0].point.y=(double) (primitive_info[i].point.y+ dy*(distance+offset)/distance); for (j=(ssize_t) number_vertices-2; j >= 0; j--) { dx=primitive_info[number_vertices-1].point.x-primitive_info[j].point.x; dy=primitive_info[number_vertices-1].point.y-primitive_info[j].point.y; if ((fabs((double) dx) >= MagickEpsilon) || (fabs((double) dy) >= MagickEpsilon)) break; } distance=hypot((double) dx,(double) dy); primitive_info[number_vertices-1].point.x=(double) (primitive_info[j].point.x+ dx*(distance+offset)/distance); primitive_info[number_vertices-1].point.y=(double) (primitive_info[j].point.y+ dy*(distance+offset)/distance); return(MagickTrue); } static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info,ExceptionInfo *exception) { #define MaxStrokePad (6*BezierQuantum+360) #define CheckPathExtent(pad_p,pad_q) \ { \ if ((pad_p) > MaxBezierCoordinates) \ stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); \ else \ if ((ssize_t) (p+(pad_p)) >= (ssize_t) extent_p) \ { \ if (~extent_p < (pad_p)) \ stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); \ else \ { \ extent_p+=(pad_p); \ stroke_p=(PointInfo *) ResizeQuantumMemory(stroke_p,extent_p+ \ MaxStrokePad,sizeof(*stroke_p)); \ } \ } \ if ((pad_q) > MaxBezierCoordinates) \ stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); \ else \ if ((ssize_t) (q+(pad_q)) >= (ssize_t) extent_q) \ { \ if (~extent_q < (pad_q)) \ stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); \ else \ { \ extent_q+=(pad_q); \ stroke_q=(PointInfo *) ResizeQuantumMemory(stroke_q,extent_q+ \ MaxStrokePad,sizeof(*stroke_q)); \ } \ } \ if ((stroke_p == (PointInfo *) NULL) || (stroke_q == (PointInfo *) NULL)) \ { \ if (stroke_p != (PointInfo *) NULL) \ stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); \ if (stroke_q != (PointInfo *) NULL) \ stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); \ polygon_primitive=(PrimitiveInfo *) \ RelinquishMagickMemory(polygon_primitive); \ (void) ThrowMagickException(exception,GetMagickModule(), \ ResourceLimitError,"MemoryAllocationFailed","`%s'",""); \ return((PrimitiveInfo *) NULL); \ } \ } typedef struct _StrokeSegment { double p, q; } StrokeSegment; double delta_theta, dot_product, mid, miterlimit; MagickBooleanType closed_path; PointInfo box_p[5], box_q[5], center, offset, *stroke_p, *stroke_q; PrimitiveInfo *polygon_primitive, *stroke_polygon; ssize_t i; size_t arc_segments, extent_p, extent_q, number_vertices; ssize_t j, n, p, q; StrokeSegment dx = {0.0, 0.0}, dy = {0.0, 0.0}, inverse_slope = {0.0, 0.0}, slope = {0.0, 0.0}, theta = {0.0, 0.0}; /* Allocate paths. */ number_vertices=primitive_info->coordinates; polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_vertices+2UL,sizeof(*polygon_primitive)); if (polygon_primitive == (PrimitiveInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return((PrimitiveInfo *) NULL); } (void) memcpy(polygon_primitive,primitive_info,(size_t) number_vertices* sizeof(*polygon_primitive)); offset.x=primitive_info[number_vertices-1].point.x-primitive_info[0].point.x; offset.y=primitive_info[number_vertices-1].point.y-primitive_info[0].point.y; closed_path=(fabs(offset.x) < MagickEpsilon) && (fabs(offset.y) < MagickEpsilon) ? MagickTrue : MagickFalse; if (((draw_info->linejoin == RoundJoin) || (draw_info->linejoin == MiterJoin)) && (closed_path != MagickFalse)) { polygon_primitive[number_vertices]=primitive_info[1]; number_vertices++; } polygon_primitive[number_vertices].primitive=UndefinedPrimitive; /* Compute the slope for the first line segment, p. */ dx.p=0.0; dy.p=0.0; for (n=1; n < (ssize_t) number_vertices; n++) { dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x; dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y; if ((fabs(dx.p) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon)) break; } if (n == (ssize_t) number_vertices) { if ((draw_info->linecap != RoundCap) || (closed_path != MagickFalse)) { /* Zero length subpath. */ stroke_polygon=(PrimitiveInfo *) AcquireCriticalMemory( sizeof(*stroke_polygon)); stroke_polygon[0]=polygon_primitive[0]; stroke_polygon[0].coordinates=0; polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory( polygon_primitive); return(stroke_polygon); } n=(ssize_t) number_vertices-1L; } extent_p=2*number_vertices; extent_q=2*number_vertices; stroke_p=(PointInfo *) AcquireQuantumMemory((size_t) extent_p+MaxStrokePad, sizeof(*stroke_p)); stroke_q=(PointInfo *) AcquireQuantumMemory((size_t) extent_q+MaxStrokePad, sizeof(*stroke_q)); if ((stroke_p == (PointInfo *) NULL) || (stroke_q == (PointInfo *) NULL)) { if (stroke_p != (PointInfo *) NULL) stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); if (stroke_q != (PointInfo *) NULL) stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return((PrimitiveInfo *) NULL); } slope.p=0.0; inverse_slope.p=0.0; if (fabs(dx.p) < MagickEpsilon) { if (dx.p >= 0.0) slope.p=dy.p < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon; else slope.p=dy.p < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon; } else if (fabs(dy.p) < MagickEpsilon) { if (dy.p >= 0.0) inverse_slope.p=dx.p < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon; else inverse_slope.p=dx.p < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon; } else { slope.p=dy.p/dx.p; inverse_slope.p=(-1.0/slope.p); } mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*mid*mid); if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse)) (void) TraceSquareLinecap(polygon_primitive,number_vertices,mid); offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0))); offset.y=(double) (offset.x*inverse_slope.p); if ((dy.p*offset.x-dx.p*offset.y) > 0.0) { box_p[0].x=polygon_primitive[0].point.x-offset.x; box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p; box_p[1].x=polygon_primitive[n].point.x-offset.x; box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p; box_q[0].x=polygon_primitive[0].point.x+offset.x; box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p; box_q[1].x=polygon_primitive[n].point.x+offset.x; box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p; } else { box_p[0].x=polygon_primitive[0].point.x+offset.x; box_p[0].y=polygon_primitive[0].point.y+offset.y; box_p[1].x=polygon_primitive[n].point.x+offset.x; box_p[1].y=polygon_primitive[n].point.y+offset.y; box_q[0].x=polygon_primitive[0].point.x-offset.x; box_q[0].y=polygon_primitive[0].point.y-offset.y; box_q[1].x=polygon_primitive[n].point.x-offset.x; box_q[1].y=polygon_primitive[n].point.y-offset.y; } /* Create strokes for the line join attribute: bevel, miter, round. */ p=0; q=0; stroke_q[p++]=box_q[0]; stroke_p[q++]=box_p[0]; for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++) { /* Compute the slope for this line segment, q. */ dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x; dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y; dot_product=dx.q*dx.q+dy.q*dy.q; if (dot_product < 0.25) continue; slope.q=0.0; inverse_slope.q=0.0; if (fabs(dx.q) < MagickEpsilon) { if (dx.q >= 0.0) slope.q=dy.q < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon; else slope.q=dy.q < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon; } else if (fabs(dy.q) < MagickEpsilon) { if (dy.q >= 0.0) inverse_slope.q=dx.q < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon; else inverse_slope.q=dx.q < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon; } else { slope.q=dy.q/dx.q; inverse_slope.q=(-1.0/slope.q); } offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0))); offset.y=(double) (offset.x*inverse_slope.q); dot_product=dy.q*offset.x-dx.q*offset.y; if (dot_product > 0.0) { box_p[2].x=polygon_primitive[n].point.x-offset.x; box_p[2].y=polygon_primitive[n].point.y-offset.y; box_p[3].x=polygon_primitive[i].point.x-offset.x; box_p[3].y=polygon_primitive[i].point.y-offset.y; box_q[2].x=polygon_primitive[n].point.x+offset.x; box_q[2].y=polygon_primitive[n].point.y+offset.y; box_q[3].x=polygon_primitive[i].point.x+offset.x; box_q[3].y=polygon_primitive[i].point.y+offset.y; } else { box_p[2].x=polygon_primitive[n].point.x+offset.x; box_p[2].y=polygon_primitive[n].point.y+offset.y; box_p[3].x=polygon_primitive[i].point.x+offset.x; box_p[3].y=polygon_primitive[i].point.y+offset.y; box_q[2].x=polygon_primitive[n].point.x-offset.x; box_q[2].y=polygon_primitive[n].point.y-offset.y; box_q[3].x=polygon_primitive[i].point.x-offset.x; box_q[3].y=polygon_primitive[i].point.y-offset.y; } if (fabs((double) (slope.p-slope.q)) < MagickEpsilon) { box_p[4]=box_p[1]; box_q[4]=box_q[1]; } else { box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+ box_p[3].y)/(slope.p-slope.q)); box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y); box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+ box_q[3].y)/(slope.p-slope.q)); box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y); } CheckPathExtent(MaxStrokePad,MaxStrokePad); dot_product=dx.q*dy.p-dx.p*dy.q; if (dot_product <= 0.0) switch (draw_info->linejoin) { case BevelJoin: { stroke_q[q++]=box_q[1]; stroke_q[q++]=box_q[2]; dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) stroke_p[p++]=box_p[4]; else { stroke_p[p++]=box_p[1]; stroke_p[p++]=box_p[2]; } break; } case MiterJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) { stroke_q[q++]=box_q[4]; stroke_p[p++]=box_p[4]; } else { stroke_q[q++]=box_q[1]; stroke_q[q++]=box_q[2]; stroke_p[p++]=box_p[1]; stroke_p[p++]=box_p[2]; } break; } case RoundJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) stroke_p[p++]=box_p[4]; else { stroke_p[p++]=box_p[1]; stroke_p[p++]=box_p[2]; } center=polygon_primitive[n].point; theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x); theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x); if (theta.q < theta.p) theta.q+=2.0*MagickPI; arc_segments=(size_t) CastDoubleToLong(ceil((double) ((theta. q-theta.p)/(2.0*sqrt(PerceptibleReciprocal(mid)))))); CheckPathExtent(MaxStrokePad,arc_segments+MaxStrokePad); stroke_q[q].x=box_q[1].x; stroke_q[q].y=box_q[1].y; q++; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); stroke_q[q].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); stroke_q[q].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); q++; } stroke_q[q++]=box_q[2]; break; } default: break; } else switch (draw_info->linejoin) { case BevelJoin: { stroke_p[p++]=box_p[1]; stroke_p[p++]=box_p[2]; dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) stroke_q[q++]=box_q[4]; else { stroke_q[q++]=box_q[1]; stroke_q[q++]=box_q[2]; } break; } case MiterJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) { stroke_q[q++]=box_q[4]; stroke_p[p++]=box_p[4]; } else { stroke_q[q++]=box_q[1]; stroke_q[q++]=box_q[2]; stroke_p[p++]=box_p[1]; stroke_p[p++]=box_p[2]; } break; } case RoundJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) stroke_q[q++]=box_q[4]; else { stroke_q[q++]=box_q[1]; stroke_q[q++]=box_q[2]; } center=polygon_primitive[n].point; theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x); theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x); if (theta.p < theta.q) theta.p+=2.0*MagickPI; arc_segments=(size_t) CastDoubleToLong(ceil((double) ((theta.p- theta.q)/(2.0*sqrt((double) (1.0/mid)))))); CheckPathExtent(arc_segments+MaxStrokePad,MaxStrokePad); stroke_p[p++]=box_p[1]; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); stroke_p[p].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); stroke_p[p].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); p++; } stroke_p[p++]=box_p[2]; break; } default: break; } slope.p=slope.q; inverse_slope.p=inverse_slope.q; box_p[0]=box_p[2]; box_p[1]=box_p[3]; box_q[0]=box_q[2]; box_q[1]=box_q[3]; dx.p=dx.q; dy.p=dy.q; n=i; } stroke_p[p++]=box_p[1]; stroke_q[q++]=box_q[1]; /* Trace stroked polygon. */ stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon)); if (stroke_polygon == (PrimitiveInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory( polygon_primitive); return(stroke_polygon); } for (i=0; i < (ssize_t) p; i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_p[i]; } if (closed_path != MagickFalse) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[0].point; i++; } for ( ; i < (ssize_t) (p+q+closed_path); i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_q[p+q+closed_path-(i+1)]; } if (closed_path != MagickFalse) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[p+closed_path].point; i++; } stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[0].point; i++; stroke_polygon[i].primitive=UndefinedPrimitive; stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1); stroke_p=(PointInfo *) RelinquishMagickMemory(stroke_p); stroke_q=(PointInfo *) RelinquishMagickMemory(stroke_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); return(stroke_polygon); }
GB_binop__lt_int8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__lt_int8 // A.*B function (eWiseMult): GB_AemultB__lt_int8 // A*D function (colscale): GB_AxD__lt_int8 // D*A function (rowscale): GB_DxB__lt_int8 // C+=B function (dense accum): GB_Cdense_accumB__lt_int8 // C+=b function (dense accum): GB_Cdense_accumb__lt_int8 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__lt_int8 // C=scalar+B GB_bind1st__lt_int8 // C=scalar+B' GB_bind1st_tran__lt_int8 // C=A+scalar GB_bind2nd__lt_int8 // C=A'+scalar GB_bind2nd_tran__lt_int8 // C type: bool // A type: int8_t // B,b type: int8_t // BinaryOp: cij = (aij < bij) #define GB_ATYPE \ int8_t #define GB_BTYPE \ int8_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int8_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = (x < y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LT || GxB_NO_INT8 || GxB_NO_LT_INT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__lt_int8 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__lt_int8 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__lt_int8 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type int8_t int8_t bwork = (*((int8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__lt_int8 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *GB_RESTRICT Cx = (bool *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__lt_int8 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *GB_RESTRICT Cx = (bool *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__lt_int8 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__lt_int8 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__lt_int8 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; int8_t x = (*((int8_t *) x_input)) ; int8_t *Bx = (int8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int8_t bij = Bx [p] ; Cx [p] = (x < bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__lt_int8 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; int8_t *Ax = (int8_t *) Ax_input ; int8_t y = (*((int8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int8_t aij = Ax [p] ; Cx [p] = (aij < y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = Ax [pA] ; \ Cx [pC] = (x < aij) ; \ } GrB_Info GB_bind1st_tran__lt_int8 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t x = (*((const int8_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = Ax [pA] ; \ Cx [pC] = (aij < y) ; \ } GrB_Info GB_bind2nd_tran__lt_int8 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t y = (*((const int8_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
p2p.c
/* Copyright (c) 2013, Intel Corporation Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /******************************************************************* NAME: Pipeline PURPOSE: This program tests the efficiency with which point-to-point synchronization can be carried out. It does so by executing a pipelined algorithm on an m*n grid. The first array dimension is distributed among the threads (stripwise decomposition). USAGE: The program takes as input the number of threads, the dimensions of the grid, and the number of iterations on the grid <progname> <# threads> <iterations> <m> <n> The output consists of diagnostics to make sure the algorithm worked, and of timing statistics. FUNCTIONS CALLED: Other than OpenMP or standard C functions, the following functions are used in this program: wtime() bail_out() HISTORY: - Written by Rob Van der Wijngaart, March 2006. - modified by Rob Van der Wijngaart, August 2006: * changed boundary conditions and stencil computation to avoid overflow * introduced multiple iterations over grid and dependency between iterations *******************************************************************/ #include <par-res-kern_general.h> #include <par-res-kern_omp.h> /* define shorthand for indexing a multi-dimensional array */ #define ARRAY(i,j) vector[i+(j)*(m)] /* define shorthand for flag with cache line padding */ #define LINEWORDS 16 #define flag(TID,j) flag[((TID)+(j)*nthread)*LINEWORDS] int main(int argc, char ** argv) { int TID; /* Thread ID */ int m, n; /* grid dimensions */ int i, j, jj, iter, ID; /* dummies */ int iterations; /* number of times to run the pipeline algorithm */ int *flag; /* used for pairwise synchronizations */ int *start, *end; /* starts and ends of grid slices */ int segment_size; double pipeline_time, /* timing parameters */ avgtime; double epsilon = 1.e-8; /* error tolerance */ double corner_val; /* verification value at top right corner of grid */ int nthread_input, /* thread parameters */ nthread; int grp; /* grid line aggregation factor */ int jjsize; /* actual line group size */ double RESTRICT *vector;/* array holding grid values */ long total_length; /* total required length to store grid values */ int num_error=0; /* flag that signals that requested and obtained numbers of threads are the same */ int true, false; /* toggled booleans used for synchronization */ /******************************************************************************* ** process and test input parameters ********************************************************************************/ if (argc != 5 && argc != 6){ printf("Usage: %s <# threads> <# iterations> <first array dimension> ", *argv); printf("<second array dimension> [group factor]\n"); return(EXIT_FAILURE); } /* Take number of threads to request from command line */ nthread_input = atoi(*++argv); if ((nthread_input < 1) || (nthread_input > MAX_THREADS)) { printf("ERROR: Invalid number of threads: %d\n", nthread_input); exit(EXIT_FAILURE); } omp_set_num_threads(nthread_input); iterations = atoi(*++argv); if (iterations < 1){ printf("ERROR: iterations must be >= 1 : %d \n",iterations); exit(EXIT_FAILURE); } m = atoi(*++argv); n = atoi(*++argv); if (m < 1 || n < 1){ printf("ERROR: grid dimensions must be positive: %d, %d \n", m, n); exit(EXIT_FAILURE); } if (argc==6) { grp = atoi(*++argv); if (grp < 1) grp = 1; else if (grp >= n) grp = n-1; } else grp = 1; total_length = sizeof(double)*m*n; vector = (double *) malloc(total_length); if (!vector) { printf("ERROR: Could not allocate space for vector: %ld\n", total_length); exit(EXIT_FAILURE); } if (m<nthread_input) { printf("First grid dimension %d smaller than number of threads requested: %d\n", m, nthread_input); exit(EXIT_FAILURE); } start = (int *) malloc(2*nthread_input*sizeof(int)); if (!start) { printf("ERROR: Could not allocate space for array of slice boundaries\n"); exit(EXIT_FAILURE); } end = start + nthread_input; start[0] = 0; for (ID=0; ID<nthread_input; ID++) { segment_size = m/nthread_input; if (ID < (m%nthread_input)) segment_size++; if (ID>0) start[ID] = end[ID-1]+1; end[ID] = start[ID]+segment_size-1; } flag = (int *) malloc(sizeof(int)*nthread_input*LINEWORDS*n); if (!flag) { printf("ERROR: COuld not allocate space for synchronization flags\n"); exit(EXIT_FAILURE); } #pragma omp parallel private(i, j, jj, jjsize, TID, iter, true, false) { #pragma omp master { nthread = omp_get_num_threads(); printf("OpenMP pipeline execution on 2D grid\n"); if (nthread != nthread_input) { num_error = 1; printf("ERROR: number of requested threads %d does not equal ", nthread_input); printf("number of spawned threads %d\n", nthread); } else { printf("Number of threads = %d\n",nthread_input); printf("Grid sizes = %d, %d\n", m, n); printf("Number of iterations = %d\n", iterations); if (grp > 1) printf("Group factor = %d (cheating!)\n", grp); #ifdef SYNCHRONOUS printf("Handshake between neighbor threads\n"); #else printf("No handshake between neighbor threads\n"); #endif } } bail_out(num_error); TID = omp_get_thread_num(); /* clear the array, assuming first-touch memory placement */ for (j=0; j<n; j++) for (i=start[TID]; i<=end[TID]; i++) ARRAY(i,j) = 0.0; /* set boundary values (bottom and left side of grid */ if (TID==0) for (j=0; j<n; j++) ARRAY(start[TID],j) = (double) j; for (i=start[TID]; i<=end[TID]; i++) ARRAY(i,0) = (double) i; /* set flags to zero to indicate no data is available yet */ true = 1; false = !true; for (j=0; j<n; j++) flag(TID,j) = false; /* we need a barrier after setting the flags, to make sure each is visible to all threads, and to synchronize before the iterations start */ #pragma omp barrier for (iter = 0; iter<=iterations; iter++){ #ifndef SYNCHRONOUS /* true and false toggle each iteration */ true = (iter+1)%2; false = !true; #endif /* start timer after a warmup iteration */ if (iter == 1) { #pragma omp barrier #pragma omp master { pipeline_time = wtime(); } } if (TID==0) { /* first thread waits for corner value to be copied */ while (flag(0,0) == true) { #pragma omp flush } #ifdef SYNCHRONOUS flag(0,0)= true; #pragma omp flush #endif } for (j=1; j<n; j+=grp) { /* apply grouping */ jjsize = MIN(grp, n-j); /* if not on left boundary, wait for left neighbor to produce data */ if (TID > 0) { while (flag(TID-1,j) == false) { #pragma omp flush } #ifdef SYNCHRONOUS flag(TID-1,j)= false; #pragma omp flush #endif } for (jj=j; jj<j+jjsize; jj++) for (i=MAX(start[TID],1); i<= end[TID]; i++) { ARRAY(i,jj) = ARRAY(i-1,jj) + ARRAY(i,jj-1) - ARRAY(i-1,jj-1); } /* if not on right boundary, signal right neighbor it has new data */ if (TID < nthread-1) { #ifdef SYNCHRONOUS while (flag(TID,j) == true) { #pragma omp flush } #endif flag(TID,j) = true; #pragma omp flush } } if (TID==nthread-1) { /* if on right boundary, copy top right corner value to bottom left corner to create dependency and signal completion */ ARRAY(0,0) = -ARRAY(m-1,n-1); #ifdef SYNCHRONOUS while (flag(0,0) == false) { #pragma omp flush } flag(0,0) = false; #else #pragma omp flush flag(0,0) = true; #endif #pragma omp flush } } /* end of iterations */ #pragma omp barrier #pragma omp master { pipeline_time = wtime() - pipeline_time; } } /* end of OPENMP parallel region */ /******************************************************************************* ** Analyze and output results. ********************************************************************************/ /* verify correctness, using top right value; */ corner_val = (double)((iterations+1)*(n+m-2)); if (abs(ARRAY(m-1,n-1)-corner_val)/corner_val > epsilon) { printf("ERROR: checksum %lf does not match verification value %lf\n", ARRAY(m-1,n-1), corner_val); exit(EXIT_FAILURE); } #ifdef VERBOSE printf("Solution validates; verification value = %lf\n", corner_val); printf("Point-to-point synchronizations/s: %lf\n", ((float)((n-1)*(nthread-1)))/(avgtime)); #else printf("Solution validates\n"); #endif avgtime = pipeline_time/iterations; /* flip the sign of the execution time to indicate cheating */ if (grp>1) avgtime *= -1.0; printf("Rate (MFlops/s): %lf Avg time (s): %lf\n", 1.0E-06 * 2 * ((double)((m-1)*(n-1)))/avgtime, avgtime); exit(EXIT_SUCCESS); }
GB_unop__cimag_fp32_fc32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__cimag_fp32_fc32) // op(A') function: GB (_unop_tran__cimag_fp32_fc32) // C type: float // A type: GxB_FC32_t // cast: GxB_FC32_t cij = (aij) // unaryop: cij = cimagf (aij) #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = cimagf (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC32_t z = (aij) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC32_t z = (aij) ; \ Cx [pC] = cimagf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_CIMAG || GxB_NO_FP32 || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__cimag_fp32_fc32) ( float *Cx, // Cx and Ax may be aliased const GxB_FC32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = (aij) ; Cx [p] = cimagf (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = (aij) ; Cx [p] = cimagf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__cimag_fp32_fc32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__identity_bool_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_bool_fp32) // op(A') function: GB (_unop_tran__identity_bool_fp32) // C type: bool // A type: float // cast: bool cij = (aij != 0) // unaryop: cij = aij #define GB_ATYPE \ float #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ bool z = (aij != 0) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ bool z = (aij != 0) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_BOOL || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_bool_fp32) ( bool *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; bool z = (aij != 0) ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; bool z = (aij != 0) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_bool_fp32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_binop__first_bool.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__first_bool) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__first_bool) // A.*B function (eWiseMult): GB (_AemultB_03__first_bool) // A.*B function (eWiseMult): GB (_AemultB_bitmap__first_bool) // A*D function (colscale): GB (_AxD__first_bool) // D*A function (rowscale): GB (_DxB__first_bool) // C+=B function (dense accum): GB (_Cdense_accumB__first_bool) // C+=b function (dense accum): GB (_Cdense_accumb__first_bool) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__first_bool) // C=scalar+B GB (_bind1st__first_bool) // C=scalar+B' GB (_bind1st_tran__first_bool) // C=A+scalar GB ((none)) // C=A'+scalar GB ((none)) // C type: bool // A type: bool // B,b type: bool // BinaryOp: cij = aij #define GB_ATYPE \ bool #define GB_BTYPE \ bool #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ bool aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ ; // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = x ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_FIRST || GxB_NO_BOOL || GxB_NO_FIRST_BOOL) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__first_bool) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__first_bool) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__first_bool) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type bool bool bwork = (*((bool *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__first_bool) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__first_bool) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__first_bool) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__first_bool) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__first_bool) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__first_bool) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__first_bool) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__first_bool) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; bool x = (*((bool *) x_input)) ; bool *Bx = (bool *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; ; ; Cx [p] = x ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; bool *Ax = (bool *) Ax_input ; bool y = (*((bool *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; bool aij = Ax [p] ; Cx [p] = aij ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = x ; \ } GrB_Info GB (_bind1st_tran__first_bool) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ bool #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool x = (*((const bool *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ bool } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ bool aij = Ax [pA] ; \ Cx [pC] = aij ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool y = (*((const bool *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
zgeadd.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> s d c * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_tuning.h" #include "plasma_types.h" #include "plasma_workspace.h" /***************************************************************************//** * * @ingroup plasma_geadd * * Performs an addition of two general rectangular matrices similarly to the * pzgeadd() function from the PBLAS library: * * \f[ B = \alpha * op( A ) + \beta * B, \f] * * where op( X ) is one of: * \f[ op( X ) = X, \f] * \f[ op( X ) = X^T, \f] * \f[ op( X ) = X^H, \f] * * alpha and beta are scalars and A, B are matrices with op( A ) an m-by-n or * n-by-m matrix depending on the value of transa and B an m-by-n matrix. * ******************************************************************************* * * @param[in] transa * Specifies whether the matrix A is non-transposed, transposed, or * conjugate transposed * - PlasmaNoTrans: op( A ) = A * - PlasmaTrans: op( A ) = A^T * - PlasmaConjTrans: op( A ) = A^H * * @param[in] m * Number of rows of the matrices op( A ) and B. * m >= 0. * * @param[in] n * Number of columns of the matrices op( A ) and B. * n >= 0. * * @param[in] alpha * Scalar factor of A. * * @param[in] pA * Matrix of size lda-by-k, where k is n when transa == PlasmaNoTrans * and m otherwise. * * @param[in] lda * Leading dimension of the array A. lda >= max(1,l), where l is m * when transa = PlasmaNoTrans and n otherwise. * * @param[in] beta * Scalar factor of B. * * @param[in,out] pB * Matrix of size ldb-by-n. * On exit, B = alpha * op( A ) + beta * B * * @param[in] ldb * Leading dimension of the array B. * ldb >= max(1,m). * ******************************************************************************* * * @retval PlasmaSuccess successful exit * ******************************************************************************* * * @sa plasma_omp_zgeadd * @sa plasma_cgeadd * @sa plasma_dgeadd * @sa plasma_sgeadd * ******************************************************************************/ int plasma_zgeadd(plasma_enum_t transa, int m, int n, plasma_complex64_t alpha, plasma_complex64_t *pA, int lda, plasma_complex64_t beta, plasma_complex64_t *pB, int ldb) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); return PlasmaErrorNotInitialized; } // Check input arguments. if ((transa != PlasmaNoTrans) && (transa != PlasmaTrans) && (transa != PlasmaConjTrans)) { plasma_error("illegal value of transa"); return -1; } if (m < 0) { plasma_error("illegal value of m"); return -2; } if (n < 0) { plasma_error("illegal value of n"); return -3; } if (pA == NULL) { plasma_error("NULL A"); return -5; } int am, an; if (transa == PlasmaNoTrans) { am = m; an = n; } else { am = n; an = m; } int bm = m; int bn = n; if (lda < imax(1, am)) { plasma_error("illegal value of lda"); return -6; } if (pB == NULL) { plasma_error("NULL B"); return -8; } if (ldb < imax(1, bm)) { plasma_error("illegal value of ldb"); return -9; } // quick return if (m == 0 || n == 0 || (alpha == 0.0 && beta == 1.0)) return PlasmaSuccess; // Tune parameters. if (plasma->tuning) plasma_tune_geadd(plasma, PlasmaComplexDouble, m, n); // Set tiling parameters. int nb = plasma->nb; // Create tile matrices. plasma_desc_t A; plasma_desc_t B; int retval; retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, am, an, 0, 0, am, an, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); return retval; } retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, bm, bn, 0, 0, bm, bn, &B); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); plasma_desc_destroy(&A); return retval; } // Initialize sequence. plasma_sequence_t sequence; retval = plasma_sequence_init(&sequence); // Initialize request. plasma_request_t request; retval = plasma_request_init(&request); // asynchronous block #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_zge2desc(pA, lda, A, &sequence, &request); plasma_omp_zge2desc(pB, ldb, B, &sequence, &request); // Call tile async function. plasma_omp_zgeadd(transa, alpha, A, beta, B, &sequence, &request); // Translate back to LAPACK layout. plasma_omp_zdesc2ge(A, pA, lda, &sequence, &request); plasma_omp_zdesc2ge(B, pB, ldb, &sequence, &request); } // implicit synchronization // Free matrices in tile layout. plasma_desc_destroy(&A); plasma_desc_destroy(&B); // Return status. int status = sequence.status; return status; } /***************************************************************************//** * * @ingroup plasma_geadd * * Performs an addition of two general rectangular matrices similarly to the * pzgeadd() function from the PBLAS library. Non-blocking tile version of * plasma_zgeadd(). May return before the computation is finished. Operates on * matrices stored by tiles. All matrices are passed through descriptors. All * dimensions are taken from the descriptors. Allows for pipelining of * operations at runtime. * ******************************************************************************* * * @param[in] transa * Specifies whether the matrix A is non-transposed, transposed, or * conjugate transposed * - PlasmaNoTrans: op( A ) = A * - PlasmaTrans: op( A ) = A^T * - PlasmaConjTrans: op( A ) = A^H * * @param[in] alpha * The scalar alpha. * * @param[in] A * Descriptor of matrix A. * * @param[in] beta * The scalar beta. * * @param[in,out] B * Descriptor of matrix B. * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). Check the * sequence->status for errors. * * @param[out] request * Identifies this function call (for exception handling purposes). * * @retval void * Errors are returned by setting sequence->status and * request->status to error values. The sequence->status and * request->status should never be set to PlasmaSuccess (the * initial values) since another async call may be setting a * failure value at the same time. * ******************************************************************************* * * @sa plasma_zgeadd * @sa plasma_omp_cgeadd * @sa plasma_omp_dgeadd * @sa plasma_omp_sgeadd * ******************************************************************************/ void plasma_omp_zgeadd(plasma_enum_t transa, plasma_complex64_t alpha, plasma_desc_t A, plasma_complex64_t beta, plasma_desc_t B, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if ((transa != PlasmaNoTrans) && (transa != PlasmaTrans) && (transa != PlasmaConjTrans)) { plasma_error("illegal value of transa"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(A) != PlasmaSuccess) { plasma_error("invalid A"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(B) != PlasmaSuccess) { plasma_error("invalid B"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (sequence == NULL) { plasma_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // quick return int am = transa == PlasmaNoTrans ? A.m : A.n; if ((alpha == 0.0 || am == 0) && beta == 1.0) return; // Call the parallel function. plasma_pzgeadd(transa, alpha, A, beta, B, sequence, request); }
a2a_impl.h
//Implementations of methods in a2a.h template<typename VWtype> inline double VW_Mbyte_size(const A2AArg &_args, const typename VWtype::FieldInputParamType &field_setup_params){ typedef typename VWtype::DilutionType DilutionType; typedef typename VWtype::FermionFieldType FermionFieldType; DilutionType dil(_args); const int sz = dil.getNmodes(); double field_size = double(FermionFieldType::byte_size(field_setup_params))/(1024.*1024.); return sz * field_size; } template< typename mf_Policies> double A2AvectorV<mf_Policies>::Mbyte_size(const A2AArg &_args, const FieldInputParamType &field_setup_params){ return VW_Mbyte_size<A2AvectorV<mf_Policies> >(_args,field_setup_params); } template< typename mf_Policies> double A2AvectorVfftw<mf_Policies>::Mbyte_size(const A2AArg &_args, const FieldInputParamType &field_setup_params){ return VW_Mbyte_size<A2AvectorVfftw<mf_Policies> >(_args,field_setup_params); } template< typename mf_Policies> double A2AvectorW<mf_Policies>::Mbyte_size(const A2AArg &_args, const FieldInputParamType &field_setup_params){ FullyPackedIndexDilution dil(_args); double ffield_size = double(FermionFieldType::byte_size(field_setup_params))/(1024.*1024.); double cfield_size = double(ComplexFieldType::byte_size(field_setup_params))/(1024.*1024.); return dil.getNl() * ffield_size + dil.getNhits() * cfield_size; } template< typename mf_Policies> double A2AvectorWfftw<mf_Policies>::Mbyte_size(const A2AArg &_args, const FieldInputParamType &field_setup_params){ return VW_Mbyte_size<A2AvectorWfftw<mf_Policies> >(_args,field_setup_params); } struct VFFTfieldPolicyBasic{ template<typename T> static inline void actionOutputMode(T &v, const int i){} template<typename T> static inline void actionInputMode(T &v, const int i){} }; struct VFFTfieldPolicyAllocFree{ template<typename T> static inline void actionOutputMode(T &v, const int i){ v.allocMode(i); } template<typename T> static inline void actionInputMode(T &v, const int i){ v.freeMode(i); } }; template<typename OutputType, typename InputType, typename FFTfieldPolicy> struct _V_fft_impl{ typedef typename InputType::FermionFieldType FermionFieldType; static inline void fft(OutputType &to, InputType &from, fieldOperation<FermionFieldType>* mode_preop){ if(!UniqueID()){ printf("Doing V FFT\n"); fflush(stdout); } typedef typename FermionFieldType::InputParamType FieldParamType; FieldParamType field_setup = from.getMode(0).getDimPolParams(); FermionFieldType tmp(field_setup); Float preop_time = 0; Float fft_time = 0; const bool fft_dirs[4] = {true,true,true,false}; for(int mode=0;mode<from.getNmodes();mode++){ FermionFieldType const* init_gather_from = &from.getMode(mode); if(mode_preop != NULL){ Float dtime = dclock(); (*mode_preop)(from.getMode(mode),tmp); init_gather_from = &tmp; preop_time += dclock()-dtime; } Float dtime = dclock(); FFTfieldPolicy::actionOutputMode(to, mode); //alloc #ifndef MEMTEST_MODE cps::fft_opt(to.getMode(mode), *init_gather_from, fft_dirs); #endif fft_time += dclock() - dtime; FFTfieldPolicy::actionInputMode(from, mode); //free } if(!UniqueID()){ printf("Finishing V FFT\n"); fflush(stdout); } print_time("A2AvectorVfftw::fft","Preop",preop_time); print_time("A2AvectorVfftw::fft","FFT",fft_time); } }; //Set this object to be the fast Fourier transform of the input field //Can optionally supply an object mode_preop that performs a transformation on each mode prior to the FFT template< typename mf_Policies> void A2AvectorVfftw<mf_Policies>::fft(const A2AvectorV<mf_Policies> &from, fieldOperation<FermionFieldType>* mode_preop){ _V_fft_impl<A2AvectorVfftw<mf_Policies>, const A2AvectorV<mf_Policies>, VFFTfieldPolicyBasic>::fft(*this,from,mode_preop); } template< typename mf_Policies> template<typename P> void A2AvectorVfftw<mf_Policies>::destructivefft(A2AvectorV<P> &from, fieldOperation<typename P::FermionFieldType>* mode_preop, VFFTW_ENABLE_IF_MANUAL_ALLOC(P) ){ _V_fft_impl<A2AvectorVfftw<P>, A2AvectorV<P>, VFFTfieldPolicyAllocFree>::fft(*this,from,mode_preop); } template<typename OutputType, typename InputType, typename FFTfieldPolicy> struct _V_invfft_impl{ typedef typename InputType::FermionFieldType FermionFieldType; static inline void inversefft(OutputType &to, InputType &from, fieldOperation<FermionFieldType>* mode_postop){ if(!UniqueID()){ printf("Doing V inverse FFT\n"); fflush(stdout); } typedef typename FermionFieldType::InputParamType FieldParamType; FieldParamType field_setup = from.getMode(0).getDimPolParams(); FermionFieldType tmp(field_setup); Float postop_time = 0; Float fft_time = 0; const bool fft_dirs[4] = {true,true,true,false}; for(int mode=0;mode<from.getNmodes();mode++){ //if(!UniqueID()) printf("Mode %d, memory before output alloc\n",mode); //printMem(); FFTfieldPolicy::actionOutputMode(to, mode); //alloc //if(!UniqueID()) printf("Mode %d, memory after output alloc\n",mode); //printMem(); FermionFieldType* out = mode_postop == NULL ? &to.getMode(mode) : &tmp; Float dtime = dclock(); #ifndef MEMTEST_MODE cps::fft_opt(*out, from.getMode(mode), fft_dirs, true); #endif //if(!UniqueID()) printf("Mode %d, memory before input free\n",mode); //printMem(); FFTfieldPolicy::actionInputMode(from, mode); //alloc //if(!UniqueID()) printf("Mode %d, memory after input free\n",mode); //printMem(); if(mode_postop != NULL){ Float dtime = dclock(); (*mode_postop)(tmp,to.getMode(mode)); postop_time += dclock()-dtime; } fft_time += dclock() - dtime; //printMem(); } if(!UniqueID()){ printf("Finishing V invert FFT\n"); fflush(stdout); } print_time("A2AvectorVfftw::inversefft","FFT",fft_time); print_time("A2AvectorVfftw::inversefft","Postop",postop_time); } }; template< typename mf_Policies> void A2AvectorVfftw<mf_Policies>::inversefft(A2AvectorV<Policies> &to, fieldOperation<FermionFieldType>* mode_postop) const{ _V_invfft_impl<A2AvectorV<Policies>, const A2AvectorVfftw<mf_Policies>, VFFTfieldPolicyBasic>::inversefft(to,*this,mode_postop); } template< typename mf_Policies> template<typename P> void A2AvectorVfftw<mf_Policies>::destructiveInversefft(A2AvectorV<P> &to, fieldOperation<typename P::FermionFieldType>* mode_postop, VFFTW_ENABLE_IF_MANUAL_ALLOC(P) ){ _V_invfft_impl<A2AvectorV<Policies>, A2AvectorVfftw<mf_Policies>, VFFTfieldPolicyAllocFree>::inversefft(to,*this,mode_postop); } struct WFFTfieldPolicyBasic{ template<typename T> static inline void actionOutputLowMode(T &v, const int i){} template<typename T> static inline void actionOutputHighMode(T &v, const int i){} template<typename T> static inline void actionInputLowMode(T &v, const int i){} template<typename T> static inline void actionInputHighMode(T &v, const int i){} }; struct WFFTfieldPolicyAllocFree{ template<typename T> static inline void actionOutputLowMode(T &v, const int i){ v.allocLowMode(i); } template<typename T> static inline void actionOutputHighMode(T &v, const int i){ v.allocHighMode(i); } template<typename T> static inline void actionInputLowMode(T &v, const int i){ v.freeLowMode(i); } template<typename T> static inline void actionInputHighMode(T &v, const int i){ v.freeHighMode(i); } }; template<typename OutputType, typename InputType, typename FFTfieldPolicy> struct _W_fft_impl{ typedef typename InputType::FermionFieldType FermionFieldType; inline static void fft(OutputType &to, InputType &from, fieldOperation<FermionFieldType>* mode_preop){ if(!UniqueID()){ printf("Doing W FFT\n"); fflush(stdout); } typedef typename FermionFieldType::InputParamType FieldParamType; FieldParamType field_setup = from.getWh(0).getDimPolParams(); FermionFieldType tmp(field_setup), tmp2(field_setup); Float preop_time = 0; Float fft_time = 0; const bool fft_dirs[4] = {true,true,true,false}; //Do wl for(int mode=0;mode<from.getNl();mode++){ FermionFieldType const* init_gather_from = &from.getWl(mode); if(mode_preop != NULL){ Float dtime = dclock(); (*mode_preop)(from.getWl(mode),tmp); init_gather_from = &tmp; preop_time += dclock()-dtime; } FFTfieldPolicy::actionOutputLowMode(to, mode); //alloc Float dtime = dclock(); #ifndef MEMTEST_MODE cps::fft_opt(to.getWl(mode), *init_gather_from, fft_dirs); #endif fft_time += dclock() - dtime; FFTfieldPolicy::actionInputLowMode(from, mode); //free } //Do wh. First we need to uncompact the spin/color index as this is acted upon by the operator for(int hit=0;hit<from.getNhits();hit++){ for(int sc=0;sc<12;sc++){ //spin/color dilution index from.getSpinColorDilutedSource(tmp2,hit,sc); FermionFieldType* init_gather_from = &tmp2; if(mode_preop != NULL){ Float dtime = dclock(); (*mode_preop)(tmp2,tmp); init_gather_from = &tmp; preop_time += dclock()-dtime; } Float dtime = dclock(); FFTfieldPolicy::actionOutputHighMode(to, sc+12*hit); //alloc #ifndef MEMTEST_MODE cps::fft_opt(to.getWh(hit,sc), *init_gather_from, fft_dirs); #endif fft_time += dclock()-dtime; } FFTfieldPolicy::actionInputHighMode(from, hit); //free } if(!UniqueID()){ printf("Finishing W FFT\n"); fflush(stdout); } print_time("A2AvectorWfftw::fft","Preop",preop_time); print_time("A2AvectorWfftw::fft","FFT",fft_time); } }; //Set this object to be the fast Fourier transform of the input field //Can optionally supply an object mode_preop that performs a transformation on each mode prior to the FFT template< typename mf_Policies> void A2AvectorWfftw<mf_Policies>::fft(const A2AvectorW<mf_Policies> &from, fieldOperation<FermionFieldType>* mode_preop){ _W_fft_impl<A2AvectorWfftw<mf_Policies>, const A2AvectorW<mf_Policies>, WFFTfieldPolicyBasic>::fft(*this,from,mode_preop); } template< typename mf_Policies> template<typename P> void A2AvectorWfftw<mf_Policies>::destructivefft(A2AvectorW<mf_Policies> &from, fieldOperation<FermionFieldType>* mode_preop, WFFTW_ENABLE_IF_MANUAL_ALLOC(P) ){ _W_fft_impl<A2AvectorWfftw<mf_Policies>, A2AvectorW<mf_Policies>, WFFTfieldPolicyAllocFree>::fft(*this,from,mode_preop); } template<typename OutputType, typename InputType, typename FFTfieldPolicy> struct _W_invfft_impl{ typedef typename InputType::FermionFieldType FermionFieldType; static inline void inversefft(OutputType &to, InputType &from, fieldOperation<FermionFieldType>* mode_postop){ if(!UniqueID()){ printf("Doing W inverse FFT\n"); fflush(stdout); } typedef typename FermionFieldType::InputParamType FieldParamType; FieldParamType field_setup = from.getWh(0,0).getDimPolParams(); FermionFieldType tmp(field_setup), tmp2(field_setup); Float postop_time = 0; Float fft_time = 0; const bool fft_dirs[4] = {true,true,true,false}; //Do wl for(int mode=0;mode<from.getNl();mode++){ FFTfieldPolicy::actionOutputLowMode(to, mode); //alloc FermionFieldType * unfft_to = mode_postop == NULL ? &to.getWl(mode) : &tmp; Float dtime = dclock(); #ifndef MEMTEST_MODE cps::fft_opt(*unfft_to, from.getWl(mode), fft_dirs, true); #endif fft_time += dclock() - dtime; if(mode_postop != NULL){ Float dtime = dclock(); (*mode_postop)(tmp,to.getWl(mode)); postop_time += dclock()-dtime; } FFTfieldPolicy::actionInputLowMode(from, mode); //free } //Do wh. First we need to uncompact the spin/color index as this is acted upon by the operator for(int hit=0;hit<from.getNhits();hit++){ FFTfieldPolicy::actionOutputHighMode(to, hit); //alloc typename InputType::ComplexFieldType & to_hit = to.getWh(hit); const int sc = 0; FermionFieldType * compress = mode_postop == NULL ? &tmp2 : &tmp; Float dtime = dclock(); #ifndef MEMTEST_MODE cps::fft_opt(tmp2, from.getWh(hit,sc), fft_dirs, true); #endif fft_time += dclock()-dtime; if(mode_postop != NULL){ Float dtime = dclock(); (*mode_postop)(tmp2,tmp); postop_time += dclock()-dtime; } //Should give a multiple of the 12-component unit vector with 1 on index sc #pragma omp parallel for for(int i=0;i<to_hit.nfsites();i++) *(to_hit.fsite_ptr(i)) = *(compress->fsite_ptr(i) + sc); for(int ssc=0;ssc<12;ssc++) FFTfieldPolicy::actionInputHighMode(from, ssc + 12*hit); //free for all sc } if(!UniqueID()){ printf("Finishing W inverse FFT\n"); fflush(stdout); } print_time("A2AvectorWfftw::fftinverse","FFT",fft_time); print_time("A2AvectorWfftw::fftinverse","Postop",postop_time); } }; template< typename mf_Policies> void A2AvectorWfftw<mf_Policies>::inversefft(A2AvectorW<mf_Policies> &to, fieldOperation<FermionFieldType>* mode_postop) const{ _W_invfft_impl<A2AvectorW<mf_Policies>, const A2AvectorWfftw<mf_Policies>, WFFTfieldPolicyBasic>::inversefft(to,*this,mode_postop); } template< typename mf_Policies> template<typename P> void A2AvectorWfftw<mf_Policies>::destructiveInversefft(A2AvectorW<mf_Policies> &to, fieldOperation<FermionFieldType>* mode_postop, WFFTW_ENABLE_IF_MANUAL_ALLOC(P)){ _W_invfft_impl<A2AvectorW<mf_Policies>, A2AvectorWfftw<mf_Policies>, WFFTfieldPolicyAllocFree>::inversefft(to,*this,mode_postop); } //Generate the wh field. We store in a compact notation that knows nothing about any dilution we apply when generating V from this //For reproducibility we want to generate the wh field in the same order that Daiqian did originally. Here nhit random numbers are generated for each site/flavor template<typename ComplexFieldType, typename complex_class> struct _set_wh_random_impl{}; template<typename ComplexFieldType> struct _set_wh_random_impl<ComplexFieldType, complex_double_or_float_mark>{ static void doit(std::vector<PtrWrapper<ComplexFieldType> > &wh, const RandomType &type, const int nhits){ typedef typename ComplexFieldType::FieldSiteType FieldSiteType; LRG.SetInterval(1, 0); int sites = wh[0]->nsites(), flavors = wh[0]->nflavors(); for(int i = 0; i < sites*flavors; ++i) { int flav = i / sites; int st = i % sites; LRG.AssignGenerator(st,flav); for(int j = 0; j < nhits; ++j) { FieldSiteType* p = wh[j]->site_ptr(st,flav); RandomComplex<FieldSiteType>::rand(p,type,FOUR_D); } } } }; template< typename mf_Policies> void A2AvectorW<mf_Policies>::setWhRandom(const RandomType &type){ _set_wh_random_impl<typename mf_Policies::ComplexFieldType, typename ComplexClassify<typename mf_Policies::ComplexFieldType::FieldSiteType>::type>::doit(wh,type,nhits); } //Get the diluted source with index id. //We use the same set of random numbers for each spin and dilution as we do not need to rely on stochastic cancellation to separate them //For legacy reasons we use different random numbers for the two G-parity flavors, although this is not strictly necessary template< typename mf_Policies> template<typename TargetFermionFieldType> void A2AvectorW<mf_Policies>::getDilutedSource(TargetFermionFieldType &into, const int dil_id) const{ typedef FieldSiteType mf_Complex; typedef typename TargetFermionFieldType::FieldSiteType TargetComplex; const char* fname = "getDilutedSource(...)"; int hit, tblock, spin_color, flavor; StandardIndexDilution stdidx(getArgs()); stdidx.indexUnmap(dil_id,hit,tblock,spin_color,flavor); VRB.Result("A2AvectorW", fname, "Generating random wall source %d = (%d, %d, %d, %d).\n ", dil_id, hit, tblock, flavor, spin_color); int tblock_origt = tblock * args.src_width; into.zero(); if(tblock_origt / GJP.TnodeSites() != GJP.TnodeCoor()){ VRB.Result("A2AvectorW", fname, "Not on node\n "); return; } int tblock_origt_lcl = tblock_origt % GJP.TnodeSites(); int src_size = GJP.VolNodeSites()/GJP.TnodeSites() * args.src_width; //size of source in units of complex numbers #pragma omp parallel for for(int i=0;i<src_size;i++){ int x[4]; int rem = i; x[0] = rem % GJP.XnodeSites(); rem /= GJP.XnodeSites(); x[1] = rem % GJP.YnodeSites(); rem /= GJP.YnodeSites(); x[2] = rem % GJP.ZnodeSites(); rem /= GJP.ZnodeSites(); x[3] = tblock_origt_lcl + rem; TargetComplex *into_site = (TargetComplex*)(into.site_ptr(x,flavor) + spin_color); mf_Complex const* from_site = (mf_Complex*)wh[hit]->site_ptr(x,flavor); //note same random numbers for each spin/color! *into_site = *from_site; } } //When gauge fixing prior to taking the FFT it is necessary to uncompact the wh field in the spin-color index, as these indices are acted upon by the gauge fixing //(I suppose technically only the color indices need uncompacting; this might be considered as a future improvement) template< typename mf_Policies> void A2AvectorW<mf_Policies>::getSpinColorDilutedSource(FermionFieldType &into, const int hit, const int sc_id) const{ const char* fname = "getSpinColorDilutedSource(...)"; into.zero(); #pragma omp parallel for for(int i=0;i<wh[hit]->nfsites();i++){ //same mapping, different site_size FieldSiteType &into_site = *(into.fsite_ptr(i) + sc_id); const FieldSiteType &from_site = *(wh[hit]->fsite_ptr(i)); into_site = from_site; } } template<typename mf_Policies, typename my_enable_if<_equal<typename ComplexClassify<typename mf_Policies::ComplexType>::type, complex_double_or_float_mark>::value, int>::type = 0> void randomizeVW(A2AvectorV<mf_Policies> &V, A2AvectorW<mf_Policies> &W){ typedef typename mf_Policies::FermionFieldType FermionFieldType; typedef typename mf_Policies::ComplexFieldType ComplexFieldType; int nl = V.getNl(); int nh = V.getNh(); //number of fully diluted high-mode indices int nhit = V.getNhits(); assert(nl == W.getNl()); assert(nh == W.getNh()); assert(nhit == W.getNhits()); std::vector<FermionFieldType> wl(nl); for(int i=0;i<nl;i++) wl[i].setUniformRandom(); std::vector<FermionFieldType> vl(nl); for(int i=0;i<nl;i++) vl[i].setUniformRandom(); std::vector<ComplexFieldType> wh(nhit); for(int i=0;i<nhit;i++) wh[i].setUniformRandom(); std::vector<FermionFieldType> vh(nh); for(int i=0;i<nh;i++) vh[i].setUniformRandom(); for(int i=0;i<nl;i++){ V.importVl(vl[i],i); W.importWl(wl[i],i); } for(int i=0;i<nh;i++) V.importVh(vh[i],i); for(int i=0;i<nhit;i++) W.importWh(wh[i],i); } //Ensure this generates randoms in the same order as the scalar version template<typename mf_Policies, typename my_enable_if<_equal<typename ComplexClassify<typename mf_Policies::ComplexType>::type, grid_vector_complex_mark>::value, int>::type = 0> void randomizeVW(A2AvectorV<mf_Policies> &V, A2AvectorW<mf_Policies> &W){ typedef typename mf_Policies::FermionFieldType::FieldDimensionPolicy::EquivalentScalarPolicy ScalarDimensionPolicy; typedef CPSfermion4D<typename mf_Policies::ScalarComplexType, ScalarDimensionPolicy, DynamicFlavorPolicy, StandardAllocPolicy> ScalarFermionFieldType; typedef CPScomplex4D<typename mf_Policies::ScalarComplexType, ScalarDimensionPolicy, DynamicFlavorPolicy, StandardAllocPolicy> ScalarComplexFieldType; int nl = V.getNl(); int nh = V.getNh(); //number of fully diluted high-mode indices int nhit = V.getNhits(); assert(nl == W.getNl()); assert(nh == W.getNh()); assert(nhit == W.getNhits()); ScalarFermionFieldType tmp; ScalarComplexFieldType tmp_cmplx; for(int i=0;i<nl;i++){ tmp.setUniformRandom(); W.getWl(i).importField(tmp); } for(int i=0;i<nl;i++){ tmp.setUniformRandom(); V.getVl(i).importField(tmp); } for(int i=0;i<nhit;i++){ tmp_cmplx.setUniformRandom(); W.getWh(i).importField(tmp_cmplx); } for(int i=0;i<nh;i++){ tmp.setUniformRandom(); V.getVh(i).importField(tmp); } } template< typename FieldType> FieldType const * getBaseAndShift(int shift[3], const int p[3], FieldType const *base_p, FieldType const *base_m){ //With G-parity base_p has momentum +1 in each G-parity direction, base_m has momentum -1 in each G-parity direction. //Non-Gparity directions are assumed to have momentum 0 //Units of momentum are 2pi/L for periodic BCs, pi/L for antiperiodic and pi/2L for Gparity FieldType const * out = GJP.Gparity() ? NULL : base_p; for(int d=0;d<3;d++){ if(GJP.Bc(d) == BND_CND_GPARITY){ //Type 1 : f_{p=4b+1}(n) = f_+1(n+b) // p \in {.. -7 , -3, 1, 5, 9 ..} //Type 2 : f_{p=4b-1}(n) = f_-1(n+b) // p \n {.. -5, -1, 3, 7 , 11 ..} if( (p[d]-1) % 4 == 0 ){ //Type 1 int b = (p[d]-1)/4; shift[d] = -b; //shift f_+1 backwards by b if(out == NULL) out = base_p; else if(out != base_p) ERR.General("","getBaseAndShift","Momentum (%d,%d,%d) appears to be invalid because momenta in different G-parity directions do not reside in the same set\n",p[0],p[1],p[2]); }else if( (p[d]+1) % 4 == 0 ){ //Type 2 int b = (p[d]+1)/4; shift[d] = -b; //shift f_-1 backwards by b if(out == NULL) out = base_m; else if(out != base_m) ERR.General("","getBaseAndShift","Momentum (%d,%d,%d) appears to be invalid because momenta in different G-parity directions do not reside in the same set\n",p[0],p[1],p[2]); }else ERR.General("","getBaseAndShift","Momentum (%d,%d,%d) appears to be invalid because one or more components in G-parity directions are not allowed\n",p[0],p[1],p[2]); }else{ //f_b(n) = f_0(n+b) //Let the other directions decide on which base to use if some of them are G-parity dirs ; otherwise the pointer defaults to base_p above shift[d] = -p[d]; } } if(!UniqueID()) printf("getBaseAndShift for p=(%d,%d,%d) determined shift=(%d,%d,%d) from ptr %c\n",p[0],p[1],p[2],shift[0],shift[1],shift[2],out == base_p ? 'p' : 'm'); assert(out != NULL); return out; } //Use the relations between FFTs to obtain the FFT for a chosen quark momentum //With G-parity BCs there are 2 disjoint sets of momenta hence there are 2 base FFTs template< typename mf_Policies> void A2AvectorWfftw<mf_Policies>::getTwistedFFT(const int p[3], A2AvectorWfftw<Policies> const *base_p, A2AvectorWfftw<Policies> const *base_m){ Float time = -dclock(); std::vector<int> shift(3); A2AvectorWfftw<mf_Policies> const* base = getBaseAndShift(&shift[0], p, base_p, base_m); if(base == NULL) ERR.General("A2AvectorWfftw","getTwistedFFT","Base pointer for twist momentum (%d,%d,%d) is NULL\n",p[0],p[1],p[2]); wl = base->wl; wh = base->wh; int nshift = 0; for(int i=0;i<3;i++) if(shift[i]) nshift++; if(nshift > 0){ for(int i=0;i<this->getNmodes();i++) shiftPeriodicField( this->getMode(i), base->getMode(i), shift); } time += dclock(); print_time("A2AvectorWfftw::getTwistedFFT","Twist",time); } template< typename mf_Policies> void A2AvectorWfftw<mf_Policies>::shiftFieldsInPlace(const std::vector<int> &shift){ Float time = -dclock(); int nshift = 0; for(int i=0;i<3;i++) if(shift[i]) nshift++; if(nshift > 0){ for(int i=0;i<this->getNmodes();i++) shiftPeriodicField( this->getMode(i), this->getMode(i), shift); } print_time("A2AvectorWfftw::shiftFieldsInPlace","Total",time + dclock()); } //A version of the above that directly shifts the base Wfftw rather than outputting into a separate storage //Returns the pointer to the Wfftw acted upon and the *shift required to restore the Wfftw to it's original form* template< typename mf_Policies> std::pair< A2AvectorWfftw<mf_Policies>*, std::vector<int> > A2AvectorWfftw<mf_Policies>::inPlaceTwistedFFT(const int p[3], A2AvectorWfftw<mf_Policies> *base_p, A2AvectorWfftw<mf_Policies> *base_m){ Float time = -dclock(); std::vector<int> shift(3); A2AvectorWfftw<mf_Policies>* base = getBaseAndShift(&shift[0], p, base_p, base_m); if(base == NULL) ERR.General("A2AvectorWfftw","getTwistedFFT","Base pointer for twist momentum (%d,%d,%d) is NULL\n",p[0],p[1],p[2]); base->shiftFieldsInPlace(shift); for(int i=0;i<3;i++) shift[i] = -shift[i]; time += dclock(); print_time("A2AvectorWfftw::inPlaceTwistedFFT","Twist",time); return std::pair< A2AvectorWfftw<mf_Policies>*, std::vector<int> >(base,shift); } template< typename mf_Policies> void A2AvectorVfftw<mf_Policies>::getTwistedFFT(const int p[3], A2AvectorVfftw<Policies> const *base_p, A2AvectorVfftw<Policies> const *base_m){ Float time = -dclock(); std::vector<int> shift(3); A2AvectorVfftw<mf_Policies> const* base = getBaseAndShift(&shift[0], p, base_p, base_m); if(base == NULL) ERR.General("A2AvectorVfftw","getTwistedFFT","Base pointer for twist momentum (%d,%d,%d) is NULL\n",p[0],p[1],p[2]); v = base->v; int nshift = 0; for(int i=0;i<3;i++) if(shift[i]) nshift++; if(nshift > 0){ for(int i=0;i<this->getNmodes();i++) shiftPeriodicField( this->getMode(i), base->getMode(i), shift); } time += dclock(); print_time("A2AvectorVfftw::getTwistedFFT","Twist",time); } template< typename mf_Policies> void A2AvectorVfftw<mf_Policies>::shiftFieldsInPlace(const std::vector<int> &shift){ Float time = -dclock(); int nshift = 0; for(int i=0;i<3;i++) if(shift[i]) nshift++; if(nshift > 0){ for(int i=0;i<this->getNmodes();i++) shiftPeriodicField( this->getMode(i), this->getMode(i), shift); } print_time("A2AvectorVfftw::shiftFieldsInPlace","Total",time + dclock()); } //A version of the above that directly shifts the base Wfftw rather than outputting into a separate storage //Returns the pointer to the Wfftw acted upon and the *shift required to restore the Wfftw to it's original form* template< typename mf_Policies> std::pair< A2AvectorVfftw<mf_Policies>*, std::vector<int> > A2AvectorVfftw<mf_Policies>::inPlaceTwistedFFT(const int p[3], A2AvectorVfftw<mf_Policies> *base_p, A2AvectorVfftw<mf_Policies> *base_m){ Float time = -dclock(); std::vector<int> shift(3); A2AvectorVfftw<mf_Policies>* base = getBaseAndShift(&shift[0], p, base_p, base_m); if(base == NULL) ERR.General("A2AvectorWfftw","getTwistedFFT","Base pointer for twist momentum (%d,%d,%d) is NULL\n",p[0],p[1],p[2]); base->shiftFieldsInPlace(shift); for(int i=0;i<3;i++) shift[i] = -shift[i]; time += dclock(); print_time("A2AvectorVfftw::inPlaceTwistedFFT","Twist",time); return std::pair< A2AvectorVfftw<mf_Policies>*, std::vector<int> >(base,shift); }
inneronly1-orig-no.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //Example with loop-carried data dependence at the outer level loop. #include <string.h> int main(int argc,char *argv[]) { int i; int j; double a[20][20]; memset(a,0,(sizeof(a))); for (i = 0; i < 20 -1; i += 1) { #pragma omp parallel for for (j = 0; j < 20; j += 1) { a[i][j] += a[i + 1][j]; } } return 0; }
color_transform.c
#include <stdlib.h> #include "private/imcore_private.h" #undef RGB struct color_t RGB(uint8_t r, uint8_t g, uint8_t b) { // create a color member struct color_t colorCode; // fill it with the given values colorCode.red = r; colorCode.green = g; colorCode.blue = b; // return the color return colorCode; } // get h,s,v component and create one 32 bit RGB integer from them struct color_t HSV(uint8_t h, uint8_t s, uint8_t v) { // create an inline switch case for the hsv2rgb conversion int swich = (h / 43); // switch to this value int fpart = (h - 43*swich) * 6; uint8_t p = clamp((v * (255 - s)) >> 8, 0, 255); uint8_t q = clamp((v * (255 - ((s * fpart) >> 8))) >> 8, 0, 255); uint8_t t = clamp((v * (255 - ((s * (255 - fpart)) >> 8))) >> 8, 0, 255); // create a color and fill it with the corresponding BGR value struct color_t colorCode = RGB(0,0,0); if(swich == 0) { colorCode = RGB(v,t,p); } else if(swich == 1) { colorCode = RGB(q,v,p); } else if(swich == 2) { colorCode = RGB(p,v,t); } else if(swich == 3) { colorCode = RGB(p,q,v); } else if(swich == 4) { colorCode = RGB(t,p,v); } else { colorCode = RGB(v,p,q); } return colorCode; } // Integral Image Computation. This does not check any error so check everything before calling this. #define compute_histogram(input_type, min_value, bin_size, matrix_ptr, hist_ptr, width, height, channels) \ do \ { \ uint32_t _m, _n, _c, _idx, _step, _bin; \ input_type *_matrix_ptr = matrix_ptr; \ _step = channels * width; \ /* compute thehistogram */ \ for (_n = 0; _n < height; _n++) \ { \ _idx = _n * _step; \ for (_m = 0; _m < width; _m++) \ { \ _bin = 0; \ for (_c = 0; _c < channels; _c++) \ { \ hist_ptr[_matrix_ptr[_idx + _c] - min_value + _bin]++; \ } \ _idx += channels; \ _bin += bin_size; \ } \ } \ /* done */ \ } while (0); return_t histogram(matrix_t *in, int32_t min, int32_t max, uint32_t **histogram) { int cond = is_integer(in); check_condition(cond, ERROR_TYPE_MISMATCH, "input must be an integer matrix"); // compute the histogram size uint32_t histogram_bin_size = (max - min + 1); uint32_t histogram_size = channels(in) * histogram_bin_size; // allocate the histogram if necessary if (histogram[0] == NULL) { histogram[0] = (uint32_t *)calloc(histogram_size, sizeof(uint32_t)); } else { memset(histogram[0], 0, histogram_size * sizeof(uint32_t)); } if(is_8s(in)) { compute_histogram(int8_t, min, histogram_bin_size, mdata(in, 0), histogram[0], cols(in), rows(in), channels(in)); } else if(is_8u(in)) { compute_histogram(uint8_t, min, histogram_bin_size, mdata(in, 0), histogram[0], cols(in), rows(in), channels(in)); } else if (is_16s(in)) { compute_histogram(int16_t, min, histogram_bin_size, mdata(in, 0), histogram[0], cols(in), rows(in), channels(in)); } else if (is_16u(in)) { compute_histogram(uint16_t, min, histogram_bin_size, mdata(in, 0), histogram[0], cols(in), rows(in), channels(in)); } else if (is_32s(in)) { compute_histogram(int32_t, min, histogram_bin_size, mdata(in, 0), histogram[0], cols(in), rows(in), channels(in)); } else if (is_32u(in)) { compute_histogram(uint32_t, min, histogram_bin_size, mdata(in, 0), histogram[0], cols(in), rows(in), channels(in)); } return SUCCESS; } // otsu algorithm for threshold value detection uint32_t otsu(uint32_t *histogram, uint32_t hist_length) { uint32_t t = 0, thr = 0; float sum = 0, sum1 = 0, sum2 = 0; float wsum = 0, wsum1 = 0, wsum2 = 0; float sigma = 0; for (t = 0; t < hist_length; t++) { sum += histogram[t]; wsum += t * histogram[t]; } for (t = 0; t < 256; t++) { sum1 += histogram[t]; sum2 = (sum - sum1); // if the weighted sum under threshold t is 0, continue to the next threshold if (sum1 == 0) { continue; } // if the weighted sum over threshold t is 0, break the threshold search if (sum2 == 0) { break; } wsum1 += t * histogram[t]; wsum2 = (wsum - wsum1); // find the average float avg1 = wsum1 / sum1; float avg2 = wsum2 / wsum2; // compute the standart deviation float std = sum1 * sum2 * (avg1 - avg2) * (avg1 - avg2); // if the current value of the std is higher, choose it as the best threshold if (std > sigma) { sigma = std; thr = t; } } return thr; } uint32_t imotsu(matrix_t *in) { int cond = is_image(in) && (channels(in) == 1); check_condition(cond, -1, "input must be a grayscale image"); // get histogram of the input image uint32_t *hist = (uint32_t *)calloc(256, sizeof(uint32_t)); // get histogram for gray or color image uint32_t n; // TODO: create in_data pointer based on the input type uint8_t *in_data = data(uint8_t, in); for(n = 0; n < width(in)*height(in); n++) { hist[in_data[n]]++; } // compute otsu threshold on the input uint32_t otsuthr = otsu(hist, 256); // clear unused memory free(hist); return otsuthr; } // use adaptive threshold to binarize the input image return_t imbinarize(matrix_t *in, uint32_t block_width, uint32_t block_height, float threshold, matrix_t *out) { // allocate out before use it matrix_resize(out, height(in), width(in), 1); int cond1 = channels(in) == 1 && channels(out) == 1; check_condition(cond1, ERROR_DIMENSION_MISMATCH, "input and output must be grayscale image"); int cond2 = is_image(in) & is_image(out); check_condition(cond2, ERROR_NOT_IMAGE, "input and output must be image"); // fast memory intensive threshold uint32_t i, j, h = 0; // TODO: create in_data pointer based on the input type uint8_t *in_data = data(uint8_t, in); uint8_t *out_data = data(uint8_t, out); matrix_t *sums = matrix_create(float); matrix_t *ssum = matrix_create(float); // compute the integral image integral(in, sums, ssum); // if the block is even sized, make it odd if(block_width % 2 == 0) { block_width = block_width + 1; } if(block_height % 2 == 0) { block_height = block_height + 1; } // get the half block size uint32_t half_block_width = (block_width - 1) / 2; uint32_t half_block_height = (block_height - 1) / 2; // compute the block area float block_area = block_width*block_height; uint32_t sx, sy, ex, ey; //#pragma omp parallel for for(j = 0; j < height(in); j++) { for(i = 0; i < width(in); i++) { if(i > half_block_width && i < width(in)-half_block_width) { sx = i - half_block_width; ex = i + half_block_width; } else if(i < half_block_width) { sx = 0; ex = block_width - 1; } else { sx = width(in) - block_width - 1; ex = width(in) -1; } if(j > half_block_height && j < height(in)-half_block_height) { sy = j - half_block_height; ey = j + half_block_height; } else if(i < half_block_width) { sy = 0; ey = block_height - 1; } else { sy = height(in) - block_height - 1; ey = height(in) -1; } float sum = 255 * integral_get_float(sums, sx, sy, ex, ey, 0) / block_area; out_data[h] = in_data[h] > (sum - threshold) ? (uint8_t )255 : (uint8_t )0; h++; } } //done return SUCCESS; } return_t imthreshold(matrix_t *in, uint32_t threshold, matrix_t *out) { // allocate out before use it matrix_resize(out, height(in), width(in), 1); int cond1 = channels(in)==1 && channels(out)==1; check_condition(cond1, ERROR_DIMENSION_MISMATCH, "input and output must be grayscale image"); int cond2 = is_image(in) & is_image(out); check_condition(cond2, ERROR_NOT_IMAGE, "input and output must be image"); // fast memory intensive threshold uint32_t h; // TODO: create in_data pointer based on the input type uint8_t *in_data = data(uint8_t, in); uint8_t *out_data = data(uint8_t, out); char hist[256] = {0}; for(h=threshold; h < 256; h++) { hist[h] = 255; } // If dim==1, it is already grayscale //#pragma omp parallel for for(h=0; h < width(in)*height(in); h++) { out_data[h] = hist[ in_data[h] ]; } //done return SUCCESS; } return_t rgb2gray(matrix_t *in, matrix_t *out) { // allocate out before use it matrix_resize(out, height(in), width(in), 1); int cond1 = channels(in)==3 && channels(out)==1; check_condition(cond1, ERROR_DIMENSION_MISMATCH, "input must be color and the output must be grayscale image"); int cond2 = is_image(in) & is_image(out); check_condition(cond2, ERROR_NOT_IMAGE, "input and output must be image"); // TODO: create in_data pointer based on the input type uint8_t *in_data = data(uint8_t, in); uint8_t *out_data = data(uint8_t, out); uint32_t h; //#pragma omp parallel for for(h=0; h < width(in)*height(in); h++) { out_data[h] = clamp( (int)(28*in_data[3*h] + 153*in_data[3*h+1] + 74*in_data[3*h+2]) >> 8 , 0,255); } //done return SUCCESS; } return_t gray2rgb(matrix_t *in, matrix_t *out) { // allocate out before use it matrix_resize(out, height(in), width(in), 3); int cond1 = channels(in) == 1 && channels(out) == 3; check_condition(cond1, ERROR_DIMENSION_MISMATCH, "input must be grayscale and the output must be color image"); int cond2 = is_image(in) & is_image(out); check_condition(cond2, ERROR_NOT_IMAGE, "input and output must be image"); // TODO: create in_data pointer based on the input type uint8_t *in_data = data(uint8_t, in); uint8_t *out_data = data(uint8_t, out); uint32_t h; //#pragma omp parallel for for (h = 0; h < width(in) * height(in); h++) { out_data[3 * h + 0] = in_data[h]; out_data[3 * h + 1] = in_data[h]; out_data[3 * h + 2] = in_data[h]; } //done return SUCCESS; } // Multi-Channel Transforms return_t rgb2hsv(matrix_t *in, matrix_t *out) { // allocate out before use it matrix_resize(out, height(in), width(in), 3); int cond1 = channels(in)==3 && channels(out)==3; check_condition(cond1, ERROR_DIMENSION_MISMATCH, "input and output must be color image"); int cond2 = is_image(in) & is_image(out); check_condition(cond2, ERROR_NOT_IMAGE, "input and output must be image"); uint32_t h = 0; int mx, mn; // TODO: create in_data pointer based on the input type uint8_t *in_data = data(uint8_t, in); uint8_t *out_data = data(uint8_t, out); #pragma omp parallel for private(h, mx, mn) for(h=0; h < width(in)*height(in); h++) { mx = maximum(in_data[3*h+0], maximum(in_data[3*h+1], in_data[3*h+2])); mn = minimum(in_data[3*h+0], minimum(in_data[3*h+1], in_data[3*h+2])); // set value to it out_data[3*h + 0] = mx; out_data[3*h + 1] = 0; out_data[3*h + 2] = 0; if(mx == mn) { continue; } // set saturation out_data[3*h + 1] = 255*(mx-mn)/mx; if(mx == in_data[3*h+2]) { out_data[3*h+2] = clamp( 43*(in_data[3*h+1]-in_data[3*h+0])/(mx-mn), 0, 255 ); } if(mx == in_data[3*h+1]) { out_data[3*h+2] = clamp(85 + 43*(in_data[3*h+0]-in_data[3*h+2])/(mx-mn), 0, 255 ); } if(mx == in_data[3*h+0]) { out_data[3*h+2] = clamp(171+ 43*(in_data[3*h+2]-in_data[3*h+1])/(mx-mn), 0, 255 ); } } return SUCCESS; } return_t hsv2rgb(matrix_t *in, matrix_t *out) { // allocate out before use it matrix_resize(out, height(in), width(in), 3); int cond1 = channels(in)==3 && channels(out)==3; check_condition(cond1, ERROR_DIMENSION_MISMATCH, "input and output must be color image"); int cond2 = is_image(in) & is_image(out); check_condition(cond2, ERROR_NOT_IMAGE, "input and output must be image"); uint32_t h, swich, fpart; // TODO: create in_data pointer based on the input type uint8_t *in_data = data(uint8_t, in); uint8_t *out_data = data(uint8_t, out); #pragma omp parallel for private(h, swich, fpart) for(h=0; h < width(in)*height(in); h++) { int v = in_data[3*h + 0]; int s = in_data[3*h + 1]; //int h = in_data[3*h + 2]; // check if it is a grayscale color if( s == 0 ) { out_data[3*h + 0] = v; out_data[3*h + 1] = v; out_data[3*h + 2] = v; continue; } swich = (in_data[3*h + 2] / 43); // switch to this value fpart = (in_data[3*h + 2] - 43*swich) * 6; int p = (v * (255 - s)) >> 8; int q = (v * (255 - ((s * fpart) >> 8))) >> 8; int t = (v * (255 - ((s * (255 - fpart)) >> 8))) >> 8; if(swich == 0) { out_data[3*h + 0] = p; out_data[3*h + 1] = t; out_data[3*h + 2] = v; } else if(swich == 1) { out_data[3*h + 0] = p; out_data[3*h + 1] = v; out_data[3*h + 2] = q; } else if(swich == 2) { out_data[3*h + 0] = t; out_data[3*h + 1] = v; out_data[3*h + 2] = p; } else if(swich == 3) { out_data[3*h + 0] = v; out_data[3*h + 1] = q; out_data[3*h + 2] = p; } else if(swich == 4) { out_data[3*h + 0] = v; out_data[3*h + 1] = p; out_data[3*h + 2] = t; } else { out_data[3*h + 0] = q; out_data[3*h + 1] = p; out_data[3*h + 2] = v; } } return SUCCESS; } // General Multi Channel Color transform return_t rgb2any(matrix_t *in, const float tr[3][4], matrix_t *out) { // allocate out before use it matrix_resize(out, height(in), width(in), 3); int cond1 = channels(in)==3 && channels(out)==3; check_condition(cond1, ERROR_DIMENSION_MISMATCH, "input and output must be color image"); int cond2 = is_image(in) & is_image(out); check_condition(cond2, ERROR_NOT_IMAGE, "input and output must be image"); // TODO: create in_data pointer based on the input type uint8_t *in_data = data(uint8_t, in); uint8_t *out_data = data(uint8_t, out); int h = 0; float tr00[256]; // float tr01[256]; // float tr02[256]; // float tr10[256]; // float tr11[256]; // float tr12[256]; // float tr20[256]; // float tr21[256]; // float tr22[256]; // for(h=0; h < 256; h++) { tr00[h] = h*tr[0][0]; tr01[h] = h*tr[0][1]; tr02[h] = h*tr[0][2]; tr10[h] = h*tr[1][0]; tr11[h] = h*tr[1][1]; tr12[h] = h*tr[1][2]; tr20[h] = h*tr[2][0]; tr21[h] = h*tr[2][1]; tr22[h] = h*tr[2][2]; } #pragma omp parallel for for(int h=0; h < width(in)*height(in); h++) { // get the input data to local variables, // this will allow input and output pointers to indicate the same position uint8_t d1 = in_data[3*h + 0]; uint8_t d2 = in_data[3*h + 1]; uint8_t d3 = in_data[3*h + 2]; out_data[3*h + 2] = clamp(tr02[d1]+tr01[d2]+tr00[d3] + tr[0][3], 0, 255); out_data[3*h + 1] = clamp(tr12[d1]+tr11[d2]+tr10[d3] + tr[1][3], 0, 255); out_data[3*h + 0] = clamp(tr22[d1]+tr21[d2]+tr20[d3] + tr[2][3], 0, 255); } return SUCCESS; } // convert RGB color into Lab color space void rgb2lab(struct color_t C1, float *L, float *a, float *b) { float R = C1.red < 10 ? C1.red /3294.6f : powf((C1.red /255.0f + 0.055f)/1.055f, 2.4f); float G = C1.green < 10 ? C1.green/3294.6f : powf((C1.green/255.0f + 0.055f)/1.055f, 2.4f); float B = C1.blue < 10 ? C1.blue /3294.6f : powf((C1.blue /255.0f + 0.055f)/1.055f, 2.4f); // Observer. = 2°, Illuminant = D65 float X = R * 0.4124f + G * 0.3576f + B * 0.1804f; float Y = R * 0.2126f + G * 0.7152f + B * 0.0722f; float Z = R * 0.0193f + G * 0.1192f + B * 0.9505f; X /= 0.9504f; Y /= 1.0000f; Z /= 1.0890f; X = X > 0.008856f ? powf(X, 0.333334f ) : 7.878f*X + 16.0f / 116.0f; Y = Y > 0.008856f ? powf(Y, 0.333334f ) : 7.878f*Y + 16.0f / 116.0f; Z = Z > 0.008856f ? powf(Z, 0.333334f ) : 7.878f*Z + 16.0f / 116.0f; // set the Lab values L[0] = ( 116.0f * Y ) - 16.0f; a[0] = 500.0f * ( X - Y ); b[0] = 200.0f * ( Y - Z ); } return_t image_set(matrix_t *in, uint32_t y, uint32_t x, struct color_t clr) { // check that the given point is inside the image if(x >= width(in) || y >= height(in)) { return ERROR_DIMENSION_MISMATCH; } if(channels(in) == 1) { uint8_t gray = RGB2GRAY(clr); matrix_set(in, y,x,0, &gray); } else { matrix_set(in, y,x,2, &clr.red); matrix_set(in, y,x,1, &clr.green); matrix_set(in, y,x,0, &clr.blue); } return SUCCESS; } return_t image_get(matrix_t *in, uint32_t y, uint32_t x, struct color_t *clr) { // check that the given point is inside the image if(x >= width(in) || y >= height(in)) { return ERROR_DIMENSION_MISMATCH; } if(channels(in) == 1) { uint8_t colorG; matrix_get(in, y,x,0, &colorG); *clr = RGB(colorG, colorG, colorG); } else { matrix_get(in, y,x,0, &clr->red); matrix_get(in, y,x,1, &clr->green); matrix_get(in, y,x,2, &clr->blue); } return SUCCESS; } // #define integral_get(in, x0, y0, x1, y1) _Generic( (in) )
looptc.c
void deinterleave(char *page, char *transposed, const int ntabs, const int nchannels, const int ntimes, const int padded_size) { int tab; for (tab = 0; tab < ntabs; tab++) { int time; #pragma omp parallel for for (time = 0; time < ntimes; time++) { int channel; for (channel = 0; channel < nchannels; channel++) { // reverse freq order to comply with header transposed[time*nchannels+nchannels-channel-1] = page[(tab*nchannels + channel) * padded_size + time]; } } } }
matmul_simd.c
/* * Square matrix multiplication * A[N][N] * B[N][N] = C[N][N] * */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <sys/timeb.h> #include <string.h> #include <time.h> #include <omp.h> #define N 512 // read timer in second double read_timer() { struct timeb tm; ftime(&tm); return (double) tm.time + (double) tm.millitm / 1000.0; } void init(float *A) { int i, j; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { A[i*N+j] = (float)rand()/(float)(RAND_MAX/10.0); } } } void matmul_simd(float *A, float *B, float *C) { int i,j,k; float temp; for (i = 0; i < N; i++) { #pragma omp simd for (j = 0; j < N; j++) { temp = 0; for (k = 0; k < N; k++) { temp += (A[i * N + k] * B[j * N + k]); } C[i * N + j] = temp; } } } void matmul_serial(float *A, float *B, float *C) { int i,j,k; float temp; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { temp = 0; for (k = 0; k < N; k++) { temp += (A[i * N + k] * B[k * N + j]); } C[i * N + j] = temp; } } } float check(float *A, float *B){ float difference = 0; for(int i = 0;i<N; i++){ difference += A[i]- B[i];} return difference; } int main(int argc, char *argv[]) { int num_threads = 4; /* 4 is default number of threads */ omp_set_num_threads(num_threads); float *A = malloc(sizeof(float)*N*N); float *B = malloc(sizeof(float)*N*N); float *C_simd = malloc(sizeof(float)*N*N); float *C_serial = malloc(sizeof(float)*N*N); srand(time(NULL)); init(A); init(B); float *BT = malloc(sizeof(float)*N*N); for(int line = 0; line<N; line++){ for(int col = 0; col<N; col++){ BT[line*N+col] = B[col*N+line]; } } int i; int num_runs = 10; double elapsed = read_timer(); for (i=0; i<num_runs; i++) matmul_simd(A, BT, C_simd); elapsed = (read_timer() - elapsed); double elapsed_serial = read_timer(); for (i=0; i<num_runs; i++) matmul_serial(A, B, C_serial); elapsed_serial = (read_timer() - elapsed_serial); double gflops_omp = ((((2.0 * N) * N) * N * num_runs) / (1.0e9 * elapsed)); double gflops_serial = ((((2.0 * N) * N) * N * num_runs) / (1.0e9 * elapsed_serial)); printf("======================================================================================================\n"); printf("\tMatrix Multiplication: A[N][N] * B[N][N] = C[N][N], N=%d\n", N); printf("------------------------------------------------------------------------------------------------------\n"); printf("Performance:\t\tRuntime (s)\t GFLOPS\n"); printf("------------------------------------------------------------------------------------------------------\n"); printf("matmul_omp:\t\t%4f\t%4f\n", elapsed, gflops_omp); printf("matmul_serial:\t\t%4f\t%4f\n", elapsed_serial, gflops_serial); printf("Correctness check: %f\n", check(C_simd,C_serial)); return 0; }
depthwise_convolution_3x3.c
/* * Copyright (C) 2016-2022 T-Head Semiconductor Co., Ltd. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* CSI-NN2 version 1.12.x */ #include "csi_c906.h" #ifndef DWCONV3X3S1 #define DWCONV3X3S1 csi_c906_dwconv3x3s1 #endif #ifndef DWCONV3X3S2 #define DWCONV3X3S2 csi_c906_dwconv3x3s2 #endif /* (1) Algorithm works as follows: out_h2: out_h2_w8_loop --> out_h2_w4 --> out_h2_wtail out_h_tail: out_h1_w8_loop --> out_h1_w4 --> out_h1_wtail out_h2_w8: out_h2_w4: || out_h1_w8: out_h1_w4: outptr0[0-7]: outptr1[0-7]: outptr0[0-3]: outptr1[0-3] || outptr0[0-7]: outptr0[0-3]: k00 * r0[0-7] k00 * r1[0-7] k00 * r0[0-3] k00 * r1[0-3] || k00 * r0[0-7] k00 * r0[0-3] k01 * r0[1-8] k01 * r1[1-8] k01 * r0[1-4] k01 * r1[1-4] || k01 * r0[1-8] k01 * r0[1-4] k02 * r0[2-9] k02 * r1[2-9] k02 * r0[2-5] k02 * r1[2-5] || k02 * r0[2-9] k02 * r0[2-5] k10 * r1[0-7] k10 * r2[0-7] k10 * r1[0-3] k10 * r2[0-3] || k10 * r1[0-7] k10 * r1[0-3] k11 * r1[1-8] k11 * r2[1-8] k11 * r1[1-4] k11 * r2[1-4] || k11 * r1[1-8] k11 * r1[1-4] k12 * r1[2-9] k12 * r2[2-9] k12 * r1[2-5] k12 * r2[2-5] || k12 * r1[2-9] k12 * r1[2-5] k20 * r2[0-7] k20 * r3[0-7] k20 * r2[0-3] k20 * r3[0-3] || k20 * r2[0-7] k20 * r2[0-3] k21 * r2[1-8] k21 * r3[1-8] k21 * r2[1-4] k21 * r3[1-4] || k21 * r2[1-8] k21 * r2[1-4] k22 * r2[2-9] k22 * r3[2-9] k22 * r2[2-5] k22 * r3[2-5] || k22 * r2[2-9] k22 * r2[2-5] h2_w8_loop execution process: load r0[0-7] --> load r0[1-8] --> load r0[2-9] --> // Load r0[0-7] r0[1-8] r0[-9] before the loop to facilitate pipeline work --> load bias0[0-7] --> load r3[0-7] --> load bias1[0-7] --> load r3[1-8] --> k00*r0[0-7] / k20*r3[0-7] --> - - load r3[2-9] --> k01*r0[1-8] / k21*r3[1-8] --> load r1[0-7] --> k02*r0[2-9] / k22*r3[2-9] --> load r1[1-8] --> k10*r1[0-7] / k00*r1[0-7] --> - - load r1[2-9] --> k11*r1[1-8] / k01*r1[1-8] --> load r2[0-7] --> k12*r1[2-9] / k02*r1[2-9] --> load r2[1-8] --> k20*r2[0-7] / k10*r2[0-7] --> - - load r2[2-9] --> k21*r2[1-8] / k11*r2[1-8] --> load r0[0-7] --> k22*r2[2-9] / k12*r2[2-9] --> load r0[1-8] --> load r0[2-9] ---------------- - - ----------------------------------------------------------------------------------------------------------------------------------------------------------- h1_w8_loop execution process: load r0[0-7] --> load r0[1-8] --> load r0[2-9] --> --> load bias0[0-7] --> k00*r0[0-7] --> load r1[0-7] --> k01*r0[1-8] --> load r1[1-8] --> k02*r0[2-9] --> load r1[2-9] --> k10*r1[0-7] --> - - load r2[0-7] --> k11*r1[1-8] --> load r2[1-8] --> k12*r1[2-9] --> load r2[2-9] --> k20*r2[0-7] --> load r0[0-7] --> k21*r2[1-8] --> - - load r0[1-8] --> k22*r2[2-9] --> load r0[2-9] ------------------------------------------------------------------------------------------------- - - -------------------------------------------------------------------------------------------------------------------------------------------------------- (2) register definition: t0: i_out_h t1-t2: i_out_w v0-v1: bias0[0-7], output_data(acc) v2-v3: bias1[0-7], output_data(acc) v4-v9: r0 v4,v5:r0[0-7] v6,v7:r0[1-8] v8,v9:r0[2-9] v10-v15: r3 v16-v21: r1 v22-v27: r2 ft0-ft8: [ k00,k01,k02,k10,k11,k12,k20,k21,k22 ] ft11: constant float 0.0f, used by fusing relu (3) // TODO: support channel mult ?? opt padding */ int DWCONV3X3S1(struct csi_tensor *input, struct csi_tensor *output, struct csi_tensor *kernel, struct csi_tensor *bias, struct conv2d_params *params) { float *input_data = (float *)input->data; float *output_data = (float *)output->data; float *kernel_data = (float *)kernel->data; float *bias_data = (float *)bias->data; int32_t batch = input->dim[0]; int32_t in_c = input->dim[1]; // group = in_channel int32_t in_h = input->dim[2]; int32_t in_w = input->dim[3]; int32_t out_c = output->dim[1]; int32_t out_h = output->dim[2]; int32_t out_w = output->dim[3]; float *input_padd_buf = (float *)csi_mem_alloc(in_c * (in_h + params->pad_top + params->pad_down) * (in_w + params->pad_left + params->pad_right) * sizeof(float)); csi_c906_pad_input(input_data, input_padd_buf, in_c, in_h, in_w, in_h + params->pad_top + params->pad_down, in_w + params->pad_left + params->pad_right, params->pad_top, params->pad_left); in_h = in_h + params->pad_top + params->pad_down; in_w = in_w + params->pad_left + params->pad_right; #pragma omp parallel for num_threads(1) for (int c = 0; c < in_c; c++) { float *out = output_data + c * out_h * out_w; float *outptr0 = out; float *outptr1 = outptr0 + out_w; const float bias0 = bias_data ? bias_data[c] : 0.0f; const float *img0 = input_padd_buf + c * in_h * in_w; const float *r0 = img0; const float *r1 = r0 + in_w; const float *r2 = r1 + in_w; const float *r3 = r2 + in_w; const float *kernel0 = kernel_data + c * 9; #if __riscv_vector == 128 asm volatile( "vsetvli zero, zero, e32, m2\n\t" #ifdef FUSE_CONV_RELU "fmv.w.x ft11, zero\n\t" #endif // FUSE_CONV_RELU "flw ft0, 0(%0)\n\t" // k00 "flw ft1, 4(%0)\n\t" // k01 "flw ft2, 8(%0)\n\t" // k02 "flw ft3, 12(%0)\n\t" // k10 "flw ft4, 16(%0)\n\t" // k11 "flw ft5, 20(%0)\n\t" // k12 "flw ft6, 24(%0)\n\t" // k20 "flw ft7, 28(%0)\n\t" // k21 "flw ft8, 32(%0)\n\t" // k22 "srai t0, %7, 1\n\t" // t0 = out_h >> 1 "beqz t0, 7f\n\t" "1:\n\t" // out_h_loop2 "srai t1, %8, 3\n\t" // t1 = out_w >> 3 "beqz t1, 3f\n\t" "vsetvli zero, zero, e32, m2\n\t" // set vl = 8 "vlw.v v4, (%1)\n\t" // r0[0-7] "addi %1, %1, 4\n\t" // r0++ "vlw.v v6, (%1)\n\t" // r0[1-8] "addi %1, %1, 4\n\t" // r0++ "vlw.v v8, (%1)\n\t" // r0[2-9] "2:\n\t" // out_w_loop8 "vfmv.v.f v0, %20\n\t" // bias0[0-7] "addi %1, %1, 24\n\t" // r0 += 6 "vlw.v v10, (%4)\n\t" // r3[0-7] "addi %4, %4, 4\n\t" // r3++ "vfmv.v.f v2, %20\n\t" // bias1[0-7] "vlw.v v12, (%4)\n\t" // r3[1-8] "addi %4, %4, 4\n\t" // r3++ "vfmacc.vf v0, ft0, v4\n\t" // k00 * r0[0-7] "vfmacc.vf v2, ft6, v10\n\t" // k20 * r3[0-7] "vlw.v v14, (%4)\n\t" // r3[2-9] "addi %4, %4, 24\n\t" // r3 += 6 "vfmacc.vf v0, ft1, v6\n\t" // k01 * r0[1-8] "vfmacc.vf v2, ft7, v12\n\t" // k21 * r3[1-8] "vlw.v v16, (%2)\n\t" // r1[0-7] "addi %2, %2, 4\n\t" // r1++ "vfmacc.vf v0, ft2, v8\n\t" // k02 * r0[2-9] "vfmacc.vf v2, ft8, v14\n\t" // k22 * r3[2-9] "vlw.v v18, (%2)\n\t" // r1[1-8] "addi %2, %2, 4\n\t" // r1++ "vfmacc.vf v0, ft3, v16\n\t" // k10 * r1[0-7] "vfmacc.vf v2, ft0, v16\n\t" // k00 * r1[0-7] "vlw.v v20, (%2)\n\t" // r1[2-9] "addi %2, %2, 24\n\t" // r1 += 6 "vfmacc.vf v0, ft4, v18\n\t" // k11 * r1[1-8] "vfmacc.vf v2, ft1, v18\n\t" // k01 * r1[1-8] "vlw.v v22, (%3)\n\t" // r2[0-7] "addi %3, %3, 4\n\t" // r2++ "vfmacc.vf v0, ft5, v20\n\t" // k12 * r1[2-9] "vfmacc.vf v2, ft2, v20\n\t" // k02 * r1[2-9] "vlw.v v24, (%3)\n\t" // r2[1-8] "addi %3, %3, 4\n\t" // r2++ "vfmacc.vf v0, ft6, v22\n\t" // k20 * r2[0-7] "vfmacc.vf v2, ft3, v22\n\t" // k10 * r2[0-7] "vlw.v v26, (%3)\n\t" // r2[2-9] "addi %3, %3, 24\n\t" // r2 += 6 "vfmacc.vf v0, ft7, v24\n\t" // k21 * r2[1-8] "vfmacc.vf v2, ft4, v24\n\t" // k11 * r2[1-8] "vlw.v v4, (%1)\n\t" // r0[0-7] load r0 for next loop "addi %1, %1, 4\n\t" // r0++ "vfmacc.vf v0, ft8, v26\n\t" // k22 * r2[2-9] "vlw.v v6, (%1)\n\t" // r0[1-8] "addi %1, %1, 4\n\t" // r0++ #ifdef FUSE_CONV_RELU "vfmax.vf v0, v0, ft11\n\t" // **** relu **** #endif // FUSE_CONV_RELU "vsw.v v0, (%5)\n\t" // store line0 8 elements on outptr0 "addi %5, %5, 32\n\t" // outptr0 += 8 "vfmacc.vf v2, ft5, v26\n\t" // k12 * r2[2-9] "vlw.v v8, (%1)\n\t" // r0[2-9] #ifdef FUSE_CONV_RELU "vfmax.vf v2, v2, ft11\n\t" // **** relu **** #endif // FUSE_CONV_RELU "vsw.v v2, (%6)\n\t" // store line1 8 elements on outptr1 "addi %6, %6, 32\n\t" // outptr1 += 8 "addi t1, t1, -1\n\t" "bnez t1, 2b\n\t" "addi %1, %1, -8\n\t" // r0 -= 2 ********* bump r0 to origin addr ************ "3:\n\t" // out_w4 // h2循环中只有执行一次的机会 "andi t1, %8, 7\n\t" // t1 = out_w & 7 "srai t2, t1, 2\n\t" // t2 = (out_w & 7) >> 2 "beqz t2, 4f\n\t" "vsetvli zero, zero, e32, m1\n\t" // set vl = 4 "vlw.v v4, (%1)\n\t" // r0[0-3] "addi %1, %1, 4\n\t" // r0++ "vfmv.v.f v0, %20\n\t" // bias0[0-3] "vlw.v v10, (%4)\n\t" // r3[0-3] "addi %4, %4, 4\n\t" // r3++ "vfmv.v.f v2, %20\n\t" // bias1[0-3] "vlw.v v5, (%1)\n\t" // r0[1-4] "addi %1, %1, 4\n\t" // r0++ "vlw.v v11, (%4)\n\t" // r3[1-4] "addi %4, %4, 4\n\t" // r3++ "vfmacc.vf v0, ft0, v4\n\t" // k00 * r0[0-3] "vfmacc.vf v2, ft6, v10\n\t" // k20 * r3[0-3] "vlw.v v6, (%1)\n\t" // r0[2-5] "addi %1, %1, 8\n\t" // r0 += 2 "vlw.v v12, (%4)\n\t" // r3[2-5] "addi %4, %4, 8\n\t" // r3 += 2 "vfmacc.vf v0, ft1, v5\n\t" // k01 * r0[1-4] "vfmacc.vf v2, ft7, v11\n\t" // k21 * r3[1-4] "vlw.v v16, (%2)\n\t" // r1[0-3] "addi %2, %2, 4\n\t" // r1++ "vfmacc.vf v0, ft2, v6\n\t" // k02 * r0[2-5] "vfmacc.vf v2, ft8, v12\n\t" // k22 * r3[2-5] "vlw.v v17, (%2)\n\t" // r1[1-4] "addi %2, %2, 4\n\t" // r1++ "vfmacc.vf v0, ft3, v16\n\t" // k10 * r1[0-3] "vfmacc.vf v2, ft0, v16\n\t" // k00 * r1[0-3] "vlw.v v18, (%2)\n\t" // r1[2-5] "addi %2, %2, 8\n\t" // r1 += 2 "vfmacc.vf v0, ft4, v17\n\t" // k11 * r1[1-4] "vfmacc.vf v2, ft1, v17\n\t" // k01 * r1[1-4] "vlw.v v22, (%3)\n\t" // r2[0-3] "addi %3, %3, 4\n\t" // r2++ "vfmacc.vf v0, ft5, v18\n\t" // k12 * r1[2-5] "vfmacc.vf v2, ft2, v18\n\t" // k02 * r1[2-5]] "vlw.v v23, (%3)\n\t" // r2[1-4] "addi %3, %3, 4\n\t" // r2++ "vfmacc.vf v0, ft6, v22\n\t" // k20 * r2[0-3] "vfmacc.vf v2, ft3, v22\n\t" // k10 * r2[0-3] "vlw.v v24, (%3)\n\t" // r2[2-5] "addi %3, %3, 8\n\t" // r2 += 2 "vfmacc.vf v0, ft7, v23\n\t" // k21 * r2[1-4] "vfmacc.vf v2, ft4, v23\n\t" // k11 * r2[1-4] "vfmacc.vf v0, ft8, v24\n\t" // k22 * r2[2-5] "vfmacc.vf v2, ft5, v24\n\t" // k12 * r2[2-5] #ifdef FUSE_CONV_RELU "vfmax.vf v0, v0, ft11\n\t" // **** relu **** "vfmax.vf v2, v2, ft11\n\t" // **** relu **** #endif // FUSE_CONV_RELU "vsw.v v0, (%5)\n\t" // store line0 4 elements on outptr0 "addi %5, %5, 16\n\t" // outptr0 += 4 "vsw.v v2, (%6)\n\t" // store line1 4 elements on outptr1 "addi %6, %6, 16\n\t" // outptr1 += 4 "4:\n\t" // out_w_tail "andi t2, t1, 3\n\t" // t2 = (out_w & 7) & 3 "beqz t2, 6f\n\t" "vfmv.v.f v0, %20\n\t" // bias0[0-3] / bias1[0-3] "li t5, 3\n\t" "vsetvli zero, t5, e32, m1\n\t" // set vl = 3 "vlw.v v5, (%0)\n\t" // k0 "addi %0, %0, 12\n\t" "vlw.v v6, (%0)\n\t" // k1 "addi %0, %0, 12\n\t" "vlw.v v7, (%0)\n\t" // k2 "5:\n\t" // out_w_tail "vlw.v v4, (%1)\n\t" // r0 "addi %1, %1, 4\n\t" // r0++ "vlw.v v16, (%2)\n\t" // r1 "addi %2, %2, 4\n\t" // r1++ "vlw.v v22, (%3)\n\t" // r2 "addi %3, %3, 4\n\t" // r2++ "vlw.v v10, (%4)\n\t" // r3 "addi %4, %4, 4\n\t" // r3++ "vfmul.vv v8, v4, v5\n\t" // r0 * k0 "vfmacc.vv v8, v16, v6\n\t" // += r1 * k1 "vfmacc.vv v8, v22, v7\n\t" // += r2 * k2 "vfredsum.vs v11, v8, v0\n\t" // v11[0] = v0[0] + sum(v8[0..2]) "vfmv.f.s ft9, v11\n\t" // ft9 = v11[0] "vfmul.vv v9, v16, v5\n\t" // r1 * k0 "vfmacc.vv v9, v22, v6\n\t" // += r2 * k1 "vfmacc.vv v9, v10, v7\n\t" // += r3 * k2 "vfredsum.vs v12, v9, v0\n\t" // v12[0] = v0[0] + sum(v9[0..2]) "vfmv.f.s ft10, v12\n\t" // ft10 = v12[0] #ifdef FUSE_CONV_RELU "fmax.s ft9, ft9, ft11\n\t" // **** relu **** "fmax.s ft10, ft10, ft11\n\t" // **** relu **** #endif // FUSE_CONV_RELU "fsw ft9, 0(%5)\n\t" "addi %5, %5, 4\n\t" "fsw ft10, 0(%6)\n\t" "addi %6, %6, 4\n\t" "addi t2, t2, -1\n\t" "bnez t2, 5b\n\t" "addi %0, %0, -24\n\t" // kernel -= 6 ********* bump kernel_data to origin addr ************ "6:\n\t" // out_h_loop2 cnt "slli t3, %9, 2\n\t" // in_w * 4 "addi t3, t3, 8\n\t" // in_w * 4 + 8 "slli t4, %8, 2\n\t" // out_w * 4 "add %1, %1, t3\n\t" // r0 += 2 + in_w "add %2, %2, t3\n\t" // r1 += 2 + in_w "add %3, %3, t3\n\t" // r2 += 2 + in_w "add %4, %4, t3\n\t" // r3 += 2 + in_w "add %5, %5, t4\n\t" // outptr0 += out_w "add %6, %6, t4\n\t" // outptr1 += out_w "addi t0, t0, -1\n\t" "bnez t0, 1b\n\t" "7:\n\t" // out_h_tail // 只有执行一次的机会 "andi t0, %7, 1\n\t" // t0 = out_h & 1 "beqz t0, 12f\n\t" "srai t1, %8, 3\n\t" // t1 = out_w >> 3 "beqz t1, 9f\n\t" "vsetvli zero, zero, e32, m2\n\t" // set vl = 8 "vlw.v v4, (%1)\n\t" // r0[0-7] "addi %1, %1, 4\n\t" // r0++ "vlw.v v6, (%1)\n\t" // r0[1-8] "addi %1, %1, 4\n\t" // r0++ "vlw.v v8, (%1)\n\t" // r0[2-9] "8:\n\t" // out_w_loop8 (可以考虑用m1,指令更多,但是还可以再错开,便于流水?) "vfmv.v.f v0, %20\n\t" // bias0[0-7] "addi %1, %1, 24\n\t" // r0 += 6 "vfmacc.vf v0, ft0, v4\n\t" // k00 * r0[0-7] "vlw.v v16, (%2)\n\t" // r1[0-7] "addi %2, %2, 4\n\t" // r1++ "vfmacc.vf v0, ft1, v6\n\t" // k01 * r0[1-8] "vlw.v v18, (%2)\n\t" // r1[1-8] "addi %2, %2, 4\n\t" // r1++ "vfmacc.vf v0, ft2, v8\n\t" // k02 * r0[2-9] "vlw.v v20, (%2)\n\t" // r1[2-9] "addi %2, %2, 24\n\t" // r1 += 6 "vfmacc.vf v0, ft3, v16\n\t" // k10 * r1[0-7] "vlw.v v22, (%3)\n\t" // r2[0-7] "addi %3, %3, 4\n\t" // r2++ "vfmacc.vf v0, ft4, v18\n\t" // k11 * r1[1-8] "vlw.v v24, (%3)\n\t" // r2[1-8] "addi %3, %3, 4\n\t" // r2++ "vfmacc.vf v0, ft5, v20\n\t" // k12 * r1[2-9] "vlw.v v26, (%3)\n\t" // r2[2-9] "addi %3, %3, 24\n\t" // r2 += 6 "vfmacc.vf v0, ft6, v22\n\t" // k20 * r2[0-7] "vlw.v v4, (%1)\n\t" // r0[0-7] "addi %1, %1, 4\n\t" // r0++ "vfmacc.vf v0, ft7, v24\n\t" // k21 * r2[1-8] "vlw.v v6, (%1)\n\t" // r0[1-8] "addi %1, %1, 4\n\t" // r0++ "vfmacc.vf v0, ft8, v26\n\t" // k22 * r2[2-9] "vlw.v v8, (%1)\n\t" // r0[2-9] #ifdef FUSE_CONV_RELU "vfmax.vf v0, v0, ft11\n\t" // **** relu **** #endif // FUSE_CONV_RELU "vsw.v v0, (%5)\n\t" // store line0 8 elements on outptr0 "addi %5, %5, 32\n\t" // outptr0 += 8 "addi t1, t1, -1\n\t" "bnez t1, 8b\n\t" "addi %1, %1, -8\n\t" // r0 -= 8 ********* bump r0 to origin addr ************ "9:\n\t" // out_w4 "andi t1, %8, 7\n\t" // t1 = out_w & 7 "srai t2, t1, 2\n\t" // t2 = (out_w & 7) >> 2 "beqz t2, 10f\n\t" "vsetvli zero, zero, e32, m1\n\t" // set vl = 4 "vlw.v v4, (%1)\n\t" // r0[0-3] "addi %1, %1, 4\n\t" // r0++ "vfmv.v.f v0, %20\n\t" // bias0[0-3] "vlw.v v5, (%1)\n\t" // r0[1-4] "addi %1, %1, 4\n\t" // r0++ "vfmacc.vf v0, ft0, v4\n\t" // k00 * r0[0-3] "vlw.v v6, (%1)\n\t" // r0[2-5] "addi %1, %1, 8\n\t" // r0 += 2 "vfmacc.vf v0, ft1, v5\n\t" // k01 * r0[1-4] "vlw.v v16, (%2)\n\t" // r1[0-3] "addi %2, %2, 4\n\t" // r1++ "vfmacc.vf v0, ft2, v6\n\t" // k02 * r0[2-5] "vlw.v v17, (%2)\n\t" // r1[1-4] "addi %2, %2, 4\n\t" // r1++ "vfmacc.vf v0, ft3, v16\n\t" // k10 * r1[0-3] "vlw.v v18, (%2)\n\t" // r1[2-5] "addi %2, %2, 8\n\t" // r1 += 2 "vfmacc.vf v0, ft4, v17\n\t" // k11 * r1[1-4] "vlw.v v22, (%3)\n\t" // r2[0-3] "addi %3, %3, 4\n\t" // r2++ "vfmacc.vf v0, ft5, v18\n\t" // k12 * r1[2-5] "vlw.v v23, (%3)\n\t" // r2[1-4] "addi %3, %3, 4\n\t" // r2++ "vfmacc.vf v0, ft6, v22\n\t" // k20 * r2[0-3] "vlw.v v24, (%3)\n\t" // r2[2-5] "addi %3, %3, 8\n\t" // r2 += 2 "vfmacc.vf v0, ft7, v23\n\t" // k21 * r2[1-4] "vfmacc.vf v0, ft8, v24\n\t" // k22 * r2[2-5] #ifdef FUSE_CONV_RELU "vfmax.vf v0, v0, ft11\n\t" // **** relu **** #endif // FUSE_CONV_RELU "vsw.v v0, (%5)\n\t" // store line0 4 elements on outptr0 "addi %5, %5, 16\n\t" // outptr0 += 4 "10:\n\t" // out_w_tail "andi t2, t1, 3\n\t" "beqz t2, 12f\n\t" "vfmv.v.f v0, %20\n\t" // bias0[0-3] "li t5, 3\n\t" "vsetvli zero, t5, e32, m1\n\t" // set vl = 3 "vlw.v v5, (%0)\n\t" // k0 "addi %0, %0, 12\n\t" "vlw.v v6, (%0)\n\t" // k1 "addi %0, %0, 12\n\t" "vlw.v v7, (%0)\n\t" // k2 "11:\n\t" // out_w_tail "vlw.v v4, (%1)\n\t" // r0 "addi %1, %1, 4\n\t" // r0++ "vlw.v v16, (%2)\n\t" // r1 "addi %2, %2, 4\n\t" // r1++ "vlw.v v22, (%3)\n\t" // r2 "addi %3, %3, 4\n\t" // r2++ "vfmul.vv v8, v4, v5\n\t" // r0 * k0 "vfmacc.vv v8, v16, v6\n\t" // += r1 * k1 "vfmacc.vv v8, v22, v7\n\t" // += r2 * k2 "vfredsum.vs v11, v8, v0\n\t" // v11[0] = v0[0] + sum(v8[0..2]) "vfmv.f.s ft9, v11\n\t" // ft9 = v11[0] #ifdef FUSE_CONV_RELU "fmax.s ft9, ft9, ft11\n\t" // **** relu **** #endif // FUSE_CONV_RELU "fsw ft9, 0(%5)\n\t" "addi %5, %5, 4\n\t" "addi t2, t2, -1\n\t" "bnez t2, 11b\n\t" "12:\n\t" // updata addr "addi %1, %1, 8\n\t" // r0 += 2 "addi %2, %2, 8\n\t" // r1 += 2 "addi %3, %3, 8\n\t" // r2 += 2 :"=r"(kernel0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(r3), // %4 "=r"(outptr0), // %5 "=r"(outptr1), // %6 "=r"(out_h), // %7 "=r"(out_w), // %8 "=r"(in_w) // %9 :"0"(kernel0), "1"(r0), "2"(r1), "3"(r2), "4"(r3), "5"(outptr0), "6"(outptr1), "7"(out_h), "8"(out_w), "9"(in_w), "f"(bias0) // %20 :"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "ft0", "ft1", "ft2", "ft3", "ft4", "ft5", "ft6", "ft7", "ft8", "ft9", "ft10", "ft11", "t0", "t1", "t2", "t3", "t4", "t5" ); } #else const float *k0 = kernel0; const float *k1 = k0 + 3; const float *k2 = k1 + 3; int h = 0; for (; h + 1 < out_h; h += 2) { for (int w = 0; w < out_w; w++) { float sum0 = bias0; float sum1 = bias0; sum0 += r0[0] * k0[0] + r0[1] * k0[1] + r0[2] * k0[2]; sum0 += r1[0] * k1[0] + r1[1] * k1[1] + r1[2] * k1[2]; sum1 += r1[0] * k0[0] + r1[1] * k0[1] + r1[2] * k0[2]; sum0 += r2[0] * k2[0] + r2[1] * k2[1] + r2[2] * k2[2]; sum1 += r2[0] * k1[0] + r2[1] * k1[1] + r2[2] * k1[2]; sum1 += r3[0] * k2[0] + r3[1] * k2[1] + r3[2] * k2[2]; #ifdef FUSE_CONV_RELU sum0 = sum0 > 0 ? sum0 : 0; sum1 = sum1 > 0 ? sum1 : 0; #endif // FUSE_CONV_RELU *outptr0 = sum0; *outptr1 = sum1; r0++; r1++; r2++; r3++; outptr0++; outptr1++; } r0 += 2 + in_w; // jump to next line r1 += 2 + in_w; r2 += 2 + in_w; r3 += 2 + in_w; outptr0 += out_w; outptr1 += out_w; } for (; h < out_h; h++) { for (int w = 0; w < out_w; w++) { float sum0 = bias0; sum0 += r0[0] * k0[0] + r0[1] * k0[1] + r0[2] * k0[2]; sum0 += r1[0] * k1[0] + r1[1] * k1[1] + r1[2] * k1[2]; sum0 += r2[0] * k2[0] + r2[1] * k2[1] + r2[2] * k2[2]; #ifdef FUSE_CONV_RELU sum0 = sum0 > 0 ? sum0 : 0; #endif // FUSE_CONV_RELU *outptr0 = sum0; r0++; r1++; r2++; outptr0++; } r0 += 2; r1 += 2; r2 += 2; } } #endif // __riscv_vector csi_mem_free(input_padd_buf); return CSINN_TRUE; } /* (1) Algorithm works as follows: out_h1_loop: out_w4_loop --> out_w_tail k00*r00 k00*r02 k00*r04 k00*r06 k01*r01 k01*r03 k01*r05 k01*r07 k02*r02 k02*r04 k02*r06 k02*r08 ---------------------------------------- k10*r10 k10*r12 k10*r14 k10*r16 k11*r11 k11*r13 k11*r15 k11*r17 k12*r12 k12*r14 k12*r16 k12*r18 ---------------------------------------- k20*r20 k20*r22 k20*r24 k20*r26 k21*r21 k21*r23 k21*r25 k21*r27 k22*r22 k22*r24 k22*r26 k22*r28 计算 k * r 时可以用 .vv 也可以用 .vf (2) register definition: t0: i_out_h loop cnt t1-t2: i_out_w loop cnt t3: load stride 2 for r0-r2 t4: constant 3 for setting vl = 3 ft0: hold 1 output data ft1-ft9: [ k00, k01, k02, k10, k11, k12, k20, k21, k22 ] ft11: constant float 0.0f, used by fusing relu v0: bias, acc v4-v5: r0[0,2.4.6] r0[1,3,5,7] v1: r0[2,4,6,8] v6-v7: r1[0,2.4.6] r1[1,3,5,7] v2: r1[2,4,6,8] v8-v9: r2[0,2.4.6] r2[1,3,5,7] v3: r2[2,4,6,8] v10-v12: k0, k1, k2 v20-v21: [ acc(kx1*rx), acc(kx2*rx) ] (3) //TODO: support channel mult ?? Staggered instructions */ int DWCONV3X3S2(struct csi_tensor *input, struct csi_tensor *output, struct csi_tensor *kernel, struct csi_tensor *bias, struct conv2d_params *params) { float *input_data = (float *)input->data; float *output_data = (float *)output->data; float *kernel_data = (float *)kernel->data; float *bias_data = (float *)bias->data; int32_t batch = input->dim[0]; int32_t in_c = input->dim[1]; // group = in_channel int32_t in_h = input->dim[2]; int32_t in_w = input->dim[3]; int32_t out_c = output->dim[1]; int32_t out_h = output->dim[2]; int32_t out_w = output->dim[3]; float *input_padd_buf = (float *)csi_mem_alloc(in_c * (in_h + params->pad_top + params->pad_down) * (in_w + params->pad_left + params->pad_right) * sizeof(float)); csi_c906_pad_input(input_data, input_padd_buf, in_c, in_h, in_w, in_h + params->pad_top + params->pad_down, in_w + params->pad_left + params->pad_right, params->pad_top, params->pad_left); in_h = in_h + params->pad_top + params->pad_down; in_w = in_w + params->pad_left + params->pad_right; int tailstep = in_w - 2 * out_w + in_w; #pragma omp parallel for num_threads(1) for (int c = 0; c < in_c; c++) { float *out = output_data + c * out_h * out_w; float *outptr0 = out; const float bias0 = bias_data ? bias_data[c] : 0.0f; const float *img0 = input_padd_buf + c * in_h * in_w; const float *r0 = img0; const float *r1 = r0 + in_w; const float *r2 = r1 + in_w; const float *kernel0 = kernel_data + c * 9; #if __riscv_vector == 128 asm volatile( "vsetvli zero, zero, e32, m1\n\t" "li t3, 8\n\t" // load stride for r_x #ifdef FUSE_CONV_RELU "fmv.w.x ft11, zero\n\t" #endif // FUSE_CONV_RELU "flw ft1, (%0)\n\t" "flw ft2, 4(%0)\n\t" "flw ft3, 8(%0)\n\t" "flw ft4, 12(%0)\n\t" "flw ft5, 16(%0)\n\t" "flw ft6, 20(%0)\n\t" "flw ft7, 24(%0)\n\t" "flw ft8, 28(%0)\n\t" "flw ft9, 32(%0)\n\t" // load k00 - k22 "vlw.v v10, (%0)\n\t" // k0 "addi %0, %0, 12\n\t" "vlw.v v11, (%0)\n\t" // k1 "addi %0, %0, 12\n\t" "vlw.v v12, (%0)\n\t" // k2 "vfmv.v.f v0, %16\n\t" // bias0 "mv t0, %5\n\t" // i_out_h = out_h "1:\n\t" // out_h "srai t1, %6, 2\n\t" // t1 = out_w >> 2 "beqz t1, 3f\n\t" "vsetvli zero, zero, e32, m1\n\t" // pre-load rxx "vlseg2e.v v4, (%1)\n\t" // v4[0..3] = r0[0,2.4.6] v5[0..3] = r0[1,3,5,7] "addi %1, %1, 8\n\t" // r0 += 2 "vlsw.v v1, (%1), t3\n\t" // r0[2,4,6,8] "addi %1, %1, 24\n\t" "2:\n\t" // out_w_loop4 "vlseg2e.v v6, (%2)\n\t" // v6[0..3] = r1[0,2.4.6] v7[0..3] = r1[1,3,5,7] "addi %2, %2, 8\n\t" "vfmul.vf v20, v4, ft1\n\t" // = k00 * r0[0,2,4,6] "vfmul.vf v21, v5, ft2\n\t" // = k01 * r0[1,3,5,7] "vlsw.v v2, (%2), t3\n\t" "addi %2, %2, 24\n\t" "vfmacc.vf v0, ft3, v1\n\t" // += k02 * r0[2,4,6,8] "vlseg2e.v v8, (%3)\n\t" // v8[0..3] = r2[0,2.4.6] v9[0..3] = r2[1,3,5,7] "addi %3, %3, 8\n\t" "vfmacc.vf v20, ft4, v6\n\t" // += k10 * r1[0,2,4,6] "vfmacc.vf v21, ft5, v7\n\t" // += k11 * r1[1,3,5,7] "vlsw.v v3, (%3), t3\n\t" "addi %3, %3, 24\n\t" "vfmacc.vf v0, ft6, v2\n\t" // += k12 * r1[2,4,6,8] "vlseg2e.v v4, (%1)\n\t" // v4[0..3] = r0[0,2.4.6] v5[0..3] = r0[1,3,5,7] "addi %1, %1, 8\n\t" // r0 += 2 "vfmacc.vf v20, ft7, v8\n\t" // += k20 * r2[0,2,4,6] "vfmacc.vf v21, ft8, v9\n\t" // += k21 * r2[1,3,5,7] "vlsw.v v1, (%1), t3\n\t" // r0[2,4,6,8] "addi %1, %1, 24\n\t" "vfmacc.vf v0, ft9, v3\n\t" // += k22 * r2[2,4,6,8] "vfadd.vv v2, v20, v21\n\t" "vfadd.vv v0, v0, v2\n\t" #ifdef FUSE_CONV_RELU "vfmax.vf v0, v0, ft11\n\t" // **** relu **** #endif // FUSE_CONV_RELU "vsw.v v0, (%4)\n\t" "addi %4, %4, 16\n\t" // outptr += 16 "vfmv.v.f v0, %16\n\t" // bias0 "addi t1, t1, -1\n\t" "bnez t1, 2b\n\t" "addi %1, %1, -32\n\t" // r0 -= 8 ********* bump r0 to origin addr ************ "3:\n\t" // out_w_tail "andi t2, %6, 3\n\t" // t2 = out_w & 3 "beqz t2, 5f\n\t" "4:\n\t" // out_w_tail "vlw.v v4, (%1)\n\t" // r0 "addi %1, %1, 8\n\t" "vlw.v v6, (%2)\n\t" // r1 "addi %2, %2, 8\n\t" "vlw.v v8, (%3)\n\t" // r2 "addi %3, %3, 8\n\t" "vfmul.vv v20, v4, v10\n\t" // r0 * k0 "vfmacc.vv v20, v6, v11\n\t" // += r1 * k1 "vfmacc.vv v20, v8, v12\n\t" // += r2 * k2 "li t4, 3\n\t" "vsetvli zero, t4, e32, m1\n\t" // set vl = 3 "vfredsum.vs v21, v20, v0\n\t" // v21[0] = v0[0](bias) + sum(v20[0..2]) "vfmv.f.s ft0, v21\n\t" // ft0 = v21[0] #ifdef FUSE_CONV_RELU "fmax.s ft0, ft0, ft11\n\t" // **** relu **** #endif // FUSE_CONV_RELU "fsw ft0, 0(%4)\n\t" "addi %4, %4, 4\n\t" // bump output_data pointer "addi t2, t2, -1\n\t" "bnez t2, 4b\n\t" "5:\n\t" "slli t2, %7, 2\n\t" // t2 = tailstep * 4 "add %1, %1, t2\n\t" "add %2, %2, t2\n\t" "add %3, %3, t2\n\t" // r0/r1/r2 += tailstep "addi t0, t0, -1\n\t" "bnez t0, 1b\n\t" :"=r"(kernel0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(outptr0), // %4 "=r"(out_h), // %5 "=r"(out_w), // %6 "=r"(tailstep) // %7 :"0"(kernel0), "1"(r0), "2"(r1), "3"(r2), "4"(outptr0), "5"(out_h), "6"(out_w), "7"(tailstep), "f"(bias0) // %16 :"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v20", "v21", "ft0", "ft1", "ft2", "ft3", "ft4", "ft5", "ft6", "ft7", "ft8", "ft9", "ft11", "t0", "t1", "t2", "t3", "t4" ); } #else const float *k0 = kernel0; const float *k1 = k0 + 3; const float *k2 = k1 + 3; int h = 0; for (; h < out_h; h++) { for (int w = 0; w < out_w; w++) { float sum0 = bias0; sum0 += r0[0] * k0[0] + r0[1] * k0[1] + r0[2] * k0[2]; sum0 += r1[0] * k1[0] + r1[1] * k1[1] + r1[2] * k1[2]; sum0 += r2[0] * k2[0] + r2[1] * k2[1] + r2[2] * k2[2]; #ifdef FUSE_CONV_RELU sum0 = sum0 > 0 ? sum0 : 0; #endif // FUSE_CONV_RELU *outptr0 = sum0; r0 += 2; r1 += 2; r2 += 2; outptr0++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } #endif // __riscv_vector csi_mem_free(input_padd_buf); return CSINN_TRUE; }
grid_astar.h
/* * Copyright (c) 2014-2020, the neonavigation authors * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef PLANNER_CSPACE_GRID_ASTAR_H #define PLANNER_CSPACE_GRID_ASTAR_H #define _USE_MATH_DEFINES #include <cfloat> #include <cmath> #include <limits> #include <list> #include <map> #include <memory> #include <unordered_map> #include <utility> #include <vector> #include <boost/chrono.hpp> #include <planner_cspace/reservable_priority_queue.h> #include <planner_cspace/cyclic_vec.h> #include <planner_cspace/blockmem_gridmap.h> #include <planner_cspace/grid_astar_model.h> #include <omp.h> namespace planner_cspace { struct SearchStats { size_t num_loop; size_t num_search_queue; size_t num_prev_updates; size_t num_total_updates; }; template <int DIM = 3, int NONCYCLIC = 2> class GridAstar { public: using Vec = CyclicVecInt<DIM, NONCYCLIC>; using Vecf = CyclicVecFloat<DIM, NONCYCLIC>; using VecWithCost = typename GridAstarModelBase<DIM, NONCYCLIC>::VecWithCost; using ProgressCallback = std::function<bool(const std::list<Vec>&, const SearchStats&)>; template <class T, int block_width = 0x20> class Gridmap : public BlockMemGridmap<T, DIM, NONCYCLIC, block_width> { using BlockMemGridmap<T, DIM, NONCYCLIC, block_width>::BlockMemGridmap; }; class PriorityVec { public: float p_; float p_raw_; Vec v_; PriorityVec(const float p, const float p_raw, const Vec& v) : p_(p) , p_raw_(p_raw) , v_(v) { } bool operator<(const PriorityVec& b) const { // smaller first return p_ > b.p_; } }; class GridmapUpdate { private: const Vec p0_; const Vec p1_; const float cost_estim_; const float cost_; public: GridmapUpdate( const Vec& p0, const Vec& p1, const float cost_estim, const float cost) : p0_(p0) , p1_(p1) , cost_estim_(cost_estim) , cost_(cost) { } const Vec& getParentPos() const { return p0_; } const Vec& getPos() const { return p1_; } const float getCost() const { return cost_; } const PriorityVec getPriorityVec() const { return PriorityVec(cost_estim_, cost_, p1_); } }; public: constexpr int getDim() const { return DIM; } constexpr int getNoncyclic() const { return NONCYCLIC; } void setSearchTaskNum(const size_t& search_task_num) { search_task_num_ = search_task_num; } void reset(const Vec size) { g_.reset(size); g_.clear(std::numeric_limits<float>::max()); parents_.reserve(g_.ser_size() / 16); open_.reserve(g_.ser_size() / 16); } GridAstar() : queue_size_limit_(0) , search_task_num_(1) { } explicit GridAstar(const Vec size) { reset(size); queue_size_limit_ = 0; } void setQueueSizeLimit(const size_t size) { queue_size_limit_ = size; } bool search( const std::vector<VecWithCost>& ss, const Vec& e, std::list<Vec>& path, const typename GridAstarModelBase<DIM, NONCYCLIC>::Ptr& model, ProgressCallback cb_progress, const float cost_leave, const float progress_interval, const bool return_best = false) { return searchImpl( g_, ss, e, path, model, cb_progress, cost_leave, progress_interval, return_best); } protected: bool searchImpl( Gridmap<float>& g, const std::vector<VecWithCost>& sts, const Vec& en, std::list<Vec>& path, const typename GridAstarModelBase<DIM, NONCYCLIC>::Ptr& model, ProgressCallback cb_progress, const float cost_leave, const float progress_interval, const bool return_best = false) { if (sts.size() == 0) return false; auto ts = boost::chrono::high_resolution_clock::now(); Vec e = en; e.cycleUnsigned(g.size()); g.clear(std::numeric_limits<float>::max()); open_.clear(); parents_.clear(); std::vector<VecWithCost> ss_normalized; Vec better; int cost_estim_min = std::numeric_limits<int>::max(); for (const VecWithCost& st : sts) { if (st.v_ == en) return false; Vec s = st.v_; s.cycleUnsigned(g.size()); ss_normalized.emplace_back(s, st.c_); g[s] = st.c_; const int cost_estim = model->costEstim(s, e); open_.emplace(cost_estim + st.c_, st.c_, s); if (cost_estim_min > cost_estim) { cost_estim_min = cost_estim; better = s; } } std::vector<PriorityVec> centers; centers.reserve(search_task_num_); size_t num_updates(0); size_t num_total_updates(0); size_t num_loop(0); bool found(false); bool abort(false); #pragma omp parallel { std::vector<GridmapUpdate> updates; // Reserve buffer using example search diff list updates.reserve( search_task_num_ * model->searchGrids(ss_normalized[0].v_, ss_normalized, e).size() / omp_get_num_threads()); std::vector<Vec> dont; dont.reserve(search_task_num_); while (true) { #pragma omp barrier #pragma omp single { const size_t num_search_queue = open_.size(); num_loop++; // Fetch tasks to be paralellized centers.clear(); for (size_t i = 0; i < search_task_num_;) { if (open_.size() == 0) break; PriorityVec center(open_.top()); open_.pop(); if (center.v_ == e || center.p_ - center.p_raw_ < cost_leave) { e = center.v_; found = true; break; } centers.emplace_back(std::move(center)); ++i; } const auto tnow = boost::chrono::high_resolution_clock::now(); if (boost::chrono::duration<float>(tnow - ts).count() >= progress_interval) { std::list<Vec> path_tmp; ts = tnow; findPath(ss_normalized, better, path_tmp); const SearchStats stats = { .num_loop = num_loop, .num_search_queue = num_search_queue, .num_prev_updates = num_updates, .num_total_updates = num_total_updates, }; if (!cb_progress(path_tmp, stats)) { abort = true; } } num_updates = 0; } if (centers.size() < 1 || found || abort) break; updates.clear(); dont.clear(); #pragma omp for schedule(static) for (auto it = centers.cbegin(); it < centers.cend(); ++it) { const Vec p = it->v_; const float c = it->p_raw_; const float c_estim = it->p_; const float gp = g[p]; if (c > gp) continue; if (c_estim - c < cost_estim_min) { cost_estim_min = c_estim - c; better = p; } const std::vector<Vec> search_list = model->searchGrids(p, ss_normalized, e); bool updated(false); for (auto it = search_list.cbegin(); it < search_list.cend(); ++it) { Vec next = p + *it; next.cycleUnsigned(g.size()); if (next.isExceeded(g.size())) continue; if (g[next] < gp) { // Skip as this search task has no chance to find better way. continue; } const float cost_estim = model->costEstim(next, e); if (cost_estim < 0 || cost_estim == std::numeric_limits<float>::max()) continue; const float cost = model->cost(p, next, ss_normalized, e); if (cost < 0 || cost == std::numeric_limits<float>::max()) continue; const float cost_next = c + cost; if (g[next] > cost_next) { updated = true; updates.emplace_back(p, next, cost_next + cost_estim, cost_next); } } if (!updated) dont.push_back(p); } #pragma omp barrier #pragma omp critical { for (const GridmapUpdate& u : updates) { if (g[u.getPos()] > u.getCost()) { g[u.getPos()] = u.getCost(); parents_[u.getPos()] = u.getParentPos(); open_.push(std::move(u.getPriorityVec())); if (queue_size_limit_ > 0 && open_.size() > queue_size_limit_) open_.pop_back(); } } for (const Vec& p : dont) { g[p] = -1; } const size_t n = updates.size(); num_updates += n; num_total_updates += n; } // omp critical } } // omp parallel if (!found) { // No fesible path if (return_best) { findPath(ss_normalized, better, path); } return false; } return findPath(ss_normalized, e, path); } bool findPath(const std::vector<VecWithCost>& ss, const Vec& e, std::list<Vec>& path) const { std::unordered_map<Vec, Vec, Vec> parents = parents_; Vec n = e; while (true) { path.push_front(n); bool found(false); for (const VecWithCost& s : ss) { if (n == s.v_) { found = true; break; } } if (found) break; if (parents.find(n) == parents.end()) return false; const Vec child = n; n = parents[child]; parents.erase(child); } return true; } Gridmap<float> g_; std::unordered_map<Vec, Vec, Vec> parents_; reservable_priority_queue<PriorityVec> open_; size_t queue_size_limit_; size_t search_task_num_; }; } // namespace planner_cspace #endif // PLANNER_CSPACE_GRID_ASTAR_H
test.c
#include <stdio.h> #include <unistd.h> #include "omp.h" int main() { #pragma omp parallel { printf("Hello Thread!\n"); printf("Thread %d of %d\n", omp_get_thread_num(), omp_get_num_threads()); } write(0, "Hello, Kernel!\n", 15); printf("Hello World!\n"); return 0; }
Parser.h
//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Parser interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_PARSER_H #define LLVM_CLANG_PARSE_PARSER_H #include "clang/AST/Availability.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/OperatorPrecedence.h" #include "clang/Basic/Specifiers.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/Sema.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Frontend/OpenMP/OMPContext.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SaveAndRestore.h" #include <memory> #include <stack> namespace clang { class PragmaHandler; class Scope; class BalancedDelimiterTracker; class CorrectionCandidateCallback; class DeclGroupRef; class DiagnosticBuilder; struct LoopHint; class Parser; class ParsingDeclRAIIObject; class ParsingDeclSpec; class ParsingDeclarator; class ParsingFieldDeclarator; class ColonProtectionRAIIObject; class InMessageExpressionRAIIObject; class PoisonSEHIdentifiersRAIIObject; class OMPClause; class ObjCTypeParamList; struct OMPTraitProperty; struct OMPTraitSelector; struct OMPTraitSet; class OMPTraitInfo; /// Parser - This implements a parser for the C family of languages. After /// parsing units of the grammar, productions are invoked to handle whatever has /// been read. /// class Parser : public CodeCompletionHandler { friend class ColonProtectionRAIIObject; friend class ParsingOpenMPDirectiveRAII; friend class InMessageExpressionRAIIObject; friend class PoisonSEHIdentifiersRAIIObject; friend class ObjCDeclContextSwitch; friend class ParenBraceBracketBalancer; friend class BalancedDelimiterTracker; Preprocessor &PP; /// Tok - The current token we are peeking ahead. All parsing methods assume /// that this is valid. Token Tok; // PrevTokLocation - The location of the token we previously // consumed. This token is used for diagnostics where we expected to // see a token following another token (e.g., the ';' at the end of // a statement). SourceLocation PrevTokLocation; /// Tracks an expected type for the current token when parsing an expression. /// Used by code completion for ranking. PreferredTypeBuilder PreferredType; unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0; unsigned short MisplacedModuleBeginCount = 0; /// Actions - These are the callbacks we invoke as we parse various constructs /// in the file. Sema &Actions; DiagnosticsEngine &Diags; /// ScopeCache - Cache scopes to reduce malloc traffic. enum { ScopeCacheSize = 16 }; unsigned NumCachedScopes; Scope *ScopeCache[ScopeCacheSize]; /// Identifiers used for SEH handling in Borland. These are only /// allowed in particular circumstances // __except block IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_GetExceptionCode; // __except filter expression IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_GetExceptionInfo; // __finally IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination, *Ident_AbnormalTermination; /// Contextual keywords for Microsoft extensions. IdentifierInfo *Ident__except; mutable IdentifierInfo *Ident_sealed; mutable IdentifierInfo *Ident_abstract; /// Ident_super - IdentifierInfo for "super", to support fast /// comparison. IdentifierInfo *Ident_super; /// Ident_vector, Ident_bool, Ident_Bool - cached IdentifierInfos for "vector" /// and "bool" fast comparison. Only present if AltiVec or ZVector are /// enabled. IdentifierInfo *Ident_vector; IdentifierInfo *Ident_bool; IdentifierInfo *Ident_Bool; /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison. /// Only present if AltiVec enabled. IdentifierInfo *Ident_pixel; /// Objective-C contextual keywords. IdentifierInfo *Ident_instancetype; /// Identifier for "introduced". IdentifierInfo *Ident_introduced; /// Identifier for "deprecated". IdentifierInfo *Ident_deprecated; /// Identifier for "obsoleted". IdentifierInfo *Ident_obsoleted; /// Identifier for "unavailable". IdentifierInfo *Ident_unavailable; /// Identifier for "message". IdentifierInfo *Ident_message; /// Identifier for "strict". IdentifierInfo *Ident_strict; /// Identifier for "replacement". IdentifierInfo *Ident_replacement; /// Identifiers used by the 'external_source_symbol' attribute. IdentifierInfo *Ident_language, *Ident_defined_in, *Ident_generated_declaration; /// C++11 contextual keywords. mutable IdentifierInfo *Ident_final; mutable IdentifierInfo *Ident_GNU_final; mutable IdentifierInfo *Ident_override; // C++2a contextual keywords. mutable IdentifierInfo *Ident_import; mutable IdentifierInfo *Ident_module; // C++ type trait keywords that can be reverted to identifiers and still be // used as type traits. llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits; std::unique_ptr<PragmaHandler> AlignHandler; std::unique_ptr<PragmaHandler> GCCVisibilityHandler; std::unique_ptr<PragmaHandler> OptionsHandler; std::unique_ptr<PragmaHandler> PackHandler; std::unique_ptr<PragmaHandler> MSStructHandler; std::unique_ptr<PragmaHandler> UnusedHandler; std::unique_ptr<PragmaHandler> WeakHandler; std::unique_ptr<PragmaHandler> RedefineExtnameHandler; std::unique_ptr<PragmaHandler> FPContractHandler; std::unique_ptr<PragmaHandler> OpenCLExtensionHandler; std::unique_ptr<PragmaHandler> OpenMPHandler; std::unique_ptr<PragmaHandler> PCSectionHandler; std::unique_ptr<PragmaHandler> MSCommentHandler; std::unique_ptr<PragmaHandler> MSDetectMismatchHandler; std::unique_ptr<PragmaHandler> FloatControlHandler; std::unique_ptr<PragmaHandler> MSPointersToMembers; std::unique_ptr<PragmaHandler> MSVtorDisp; std::unique_ptr<PragmaHandler> MSInitSeg; std::unique_ptr<PragmaHandler> MSDataSeg; std::unique_ptr<PragmaHandler> MSBSSSeg; std::unique_ptr<PragmaHandler> MSConstSeg; std::unique_ptr<PragmaHandler> MSCodeSeg; std::unique_ptr<PragmaHandler> MSSection; std::unique_ptr<PragmaHandler> MSRuntimeChecks; std::unique_ptr<PragmaHandler> MSIntrinsic; std::unique_ptr<PragmaHandler> MSOptimize; std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler; std::unique_ptr<PragmaHandler> OptimizeHandler; std::unique_ptr<PragmaHandler> LoopHintHandler; std::unique_ptr<PragmaHandler> UnrollHintHandler; std::unique_ptr<PragmaHandler> NoUnrollHintHandler; std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> FPHandler; std::unique_ptr<PragmaHandler> STDCFenvAccessHandler; std::unique_ptr<PragmaHandler> STDCFenvRoundHandler; std::unique_ptr<PragmaHandler> STDCCXLIMITHandler; std::unique_ptr<PragmaHandler> STDCUnknownHandler; std::unique_ptr<PragmaHandler> AttributePragmaHandler; std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler; std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler; std::unique_ptr<CommentHandler> CommentSemaHandler; /// Whether the '>' token acts as an operator or not. This will be /// true except when we are parsing an expression within a C++ /// template argument list, where the '>' closes the template /// argument list. bool GreaterThanIsOperator; /// ColonIsSacred - When this is false, we aggressively try to recover from /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not /// safe in case statements and a few other things. This is managed by the /// ColonProtectionRAIIObject RAII object. bool ColonIsSacred; /// Parsing OpenMP directive mode. bool OpenMPDirectiveParsing = false; /// When true, we are directly inside an Objective-C message /// send expression. /// /// This is managed by the \c InMessageExpressionRAIIObject class, and /// should not be set directly. bool InMessageExpression; /// Gets set to true after calling ProduceSignatureHelp, it is for a /// workaround to make sure ProduceSignatureHelp is only called at the deepest /// function call. bool CalledSignatureHelp = false; /// The "depth" of the template parameters currently being parsed. unsigned TemplateParameterDepth; /// Current kind of OpenMP clause OpenMPClauseKind OMPClauseKind = llvm::omp::OMPC_unknown; /// RAII class that manages the template parameter depth. class TemplateParameterDepthRAII { unsigned &Depth; unsigned AddedLevels; public: explicit TemplateParameterDepthRAII(unsigned &Depth) : Depth(Depth), AddedLevels(0) {} ~TemplateParameterDepthRAII() { Depth -= AddedLevels; } void operator++() { ++Depth; ++AddedLevels; } void addDepth(unsigned D) { Depth += D; AddedLevels += D; } void setAddedDepth(unsigned D) { Depth = Depth - AddedLevels + D; AddedLevels = D; } unsigned getDepth() const { return Depth; } unsigned getOriginalDepth() const { return Depth - AddedLevels; } }; /// Factory object for creating ParsedAttr objects. AttributeFactory AttrFactory; /// Gathers and cleans up TemplateIdAnnotations when parsing of a /// top-level declaration is finished. SmallVector<TemplateIdAnnotation *, 16> TemplateIds; void MaybeDestroyTemplateIds() { if (!TemplateIds.empty() && (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens())) DestroyTemplateIds(); } void DestroyTemplateIds(); /// RAII object to destroy TemplateIdAnnotations where possible, from a /// likely-good position during parsing. struct DestroyTemplateIdAnnotationsRAIIObj { Parser &Self; DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {} ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); } }; /// Identifiers which have been declared within a tentative parse. SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers; /// Tracker for '<' tokens that might have been intended to be treated as an /// angle bracket instead of a less-than comparison. /// /// This happens when the user intends to form a template-id, but typoes the /// template-name or forgets a 'template' keyword for a dependent template /// name. /// /// We track these locations from the point where we see a '<' with a /// name-like expression on its left until we see a '>' or '>>' that might /// match it. struct AngleBracketTracker { /// Flags used to rank candidate template names when there is more than one /// '<' in a scope. enum Priority : unsigned short { /// A non-dependent name that is a potential typo for a template name. PotentialTypo = 0x0, /// A dependent name that might instantiate to a template-name. DependentName = 0x2, /// A space appears before the '<' token. SpaceBeforeLess = 0x0, /// No space before the '<' token NoSpaceBeforeLess = 0x1, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName) }; struct Loc { Expr *TemplateName; SourceLocation LessLoc; AngleBracketTracker::Priority Priority; unsigned short ParenCount, BracketCount, BraceCount; bool isActive(Parser &P) const { return P.ParenCount == ParenCount && P.BracketCount == BracketCount && P.BraceCount == BraceCount; } bool isActiveOrNested(Parser &P) const { return isActive(P) || P.ParenCount > ParenCount || P.BracketCount > BracketCount || P.BraceCount > BraceCount; } }; SmallVector<Loc, 8> Locs; /// Add an expression that might have been intended to be a template name. /// In the case of ambiguity, we arbitrarily select the innermost such /// expression, for example in 'foo < bar < baz', 'bar' is the current /// candidate. No attempt is made to track that 'foo' is also a candidate /// for the case where we see a second suspicious '>' token. void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc, Priority Prio) { if (!Locs.empty() && Locs.back().isActive(P)) { if (Locs.back().Priority <= Prio) { Locs.back().TemplateName = TemplateName; Locs.back().LessLoc = LessLoc; Locs.back().Priority = Prio; } } else { Locs.push_back({TemplateName, LessLoc, Prio, P.ParenCount, P.BracketCount, P.BraceCount}); } } /// Mark the current potential missing template location as having been /// handled (this happens if we pass a "corresponding" '>' or '>>' token /// or leave a bracket scope). void clear(Parser &P) { while (!Locs.empty() && Locs.back().isActiveOrNested(P)) Locs.pop_back(); } /// Get the current enclosing expression that might hve been intended to be /// a template name. Loc *getCurrent(Parser &P) { if (!Locs.empty() && Locs.back().isActive(P)) return &Locs.back(); return nullptr; } }; AngleBracketTracker AngleBrackets; IdentifierInfo *getSEHExceptKeyword(); /// True if we are within an Objective-C container while parsing C-like decls. /// /// This is necessary because Sema thinks we have left the container /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will /// be NULL. bool ParsingInObjCContainer; /// Whether to skip parsing of function bodies. /// /// This option can be used, for example, to speed up searches for /// declarations/definitions when indexing. bool SkipFunctionBodies; /// The location of the expression statement that is being parsed right now. /// Used to determine if an expression that is being parsed is a statement or /// just a regular sub-expression. SourceLocation ExprStatementTokLoc; /// Flags describing a context in which we're parsing a statement. enum class ParsedStmtContext { /// This context permits declarations in language modes where declarations /// are not statements. AllowDeclarationsInC = 0x1, /// This context permits standalone OpenMP directives. AllowStandaloneOpenMPDirectives = 0x2, /// This context is at the top level of a GNU statement expression. InStmtExpr = 0x4, /// The context of a regular substatement. SubStmt = 0, /// The context of a compound-statement. Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives, LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr) }; /// Act on an expression statement that might be the last statement in a /// GNU statement expression. Checks whether we are actually at the end of /// a statement expression and builds a suitable expression statement. StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx); public: Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies); ~Parser() override; const LangOptions &getLangOpts() const { return PP.getLangOpts(); } const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } Preprocessor &getPreprocessor() const { return PP; } Sema &getActions() const { return Actions; } AttributeFactory &getAttrFactory() { return AttrFactory; } const Token &getCurToken() const { return Tok; } Scope *getCurScope() const { return Actions.getCurScope(); } void incrementMSManglingNumber() const { return Actions.incrementMSManglingNumber(); } Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); } // Type forwarding. All of these are statically 'void*', but they may all be // different actual classes based on the actions in place. typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists; typedef Sema::FullExprArg FullExprArg; // Parsing methods. /// Initialize - Warm up the parser. /// void Initialize(); /// Parse the first top-level declaration in a translation unit. bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result); /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if /// the EOF was encountered. bool ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl = false); bool ParseTopLevelDecl() { DeclGroupPtrTy Result; return ParseTopLevelDecl(Result); } /// ConsumeToken - Consume the current 'peek token' and lex the next one. /// This does not work with special tokens: string literals, code completion, /// annotation tokens and balanced tokens must be handled using the specific /// consume methods. /// Returns the location of the consumed token. SourceLocation ConsumeToken() { assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } bool TryConsumeToken(tok::TokenKind Expected) { if (Tok.isNot(Expected)) return false; assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return true; } bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) { if (!TryConsumeToken(Expected)) return false; Loc = PrevTokLocation; return true; } /// ConsumeAnyToken - Dispatch to the right Consume* method based on the /// current token type. This should only be used in cases where the type of /// the token really isn't known, e.g. in error recovery. SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) { if (isTokenParen()) return ConsumeParen(); if (isTokenBracket()) return ConsumeBracket(); if (isTokenBrace()) return ConsumeBrace(); if (isTokenStringLiteral()) return ConsumeStringToken(); if (Tok.is(tok::code_completion)) return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken() : handleUnexpectedCodeCompletionToken(); if (Tok.isAnnotation()) return ConsumeAnnotationToken(); return ConsumeToken(); } SourceLocation getEndOfPreviousToken() { return PP.getLocForEndOfToken(PrevTokLocation); } /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds /// to the given nullability kind. IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) { return Actions.getNullabilityKeyword(nullability); } private: //===--------------------------------------------------------------------===// // Low-Level token peeking and consumption methods. // /// isTokenParen - Return true if the cur token is '(' or ')'. bool isTokenParen() const { return Tok.isOneOf(tok::l_paren, tok::r_paren); } /// isTokenBracket - Return true if the cur token is '[' or ']'. bool isTokenBracket() const { return Tok.isOneOf(tok::l_square, tok::r_square); } /// isTokenBrace - Return true if the cur token is '{' or '}'. bool isTokenBrace() const { return Tok.isOneOf(tok::l_brace, tok::r_brace); } /// isTokenStringLiteral - True if this token is a string-literal. bool isTokenStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } /// isTokenSpecial - True if this token requires special consumption methods. bool isTokenSpecial() const { return isTokenStringLiteral() || isTokenParen() || isTokenBracket() || isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation(); } /// Returns true if the current token is '=' or is a type of '='. /// For typos, give a fixit to '=' bool isTokenEqualOrEqualTypo(); /// Return the current token to the token stream and make the given /// token the current token. void UnconsumeToken(Token &Consumed) { Token Next = Tok; PP.EnterToken(Consumed, /*IsReinject*/true); PP.Lex(Tok); PP.EnterToken(Next, /*IsReinject*/true); } SourceLocation ConsumeAnnotationToken() { assert(Tok.isAnnotation() && "wrong consume method"); SourceLocation Loc = Tok.getLocation(); PrevTokLocation = Tok.getAnnotationEndLoc(); PP.Lex(Tok); return Loc; } /// ConsumeParen - This consume method keeps the paren count up-to-date. /// SourceLocation ConsumeParen() { assert(isTokenParen() && "wrong consume method"); if (Tok.getKind() == tok::l_paren) ++ParenCount; else if (ParenCount) { AngleBrackets.clear(*this); --ParenCount; // Don't let unbalanced )'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBracket - This consume method keeps the bracket count up-to-date. /// SourceLocation ConsumeBracket() { assert(isTokenBracket() && "wrong consume method"); if (Tok.getKind() == tok::l_square) ++BracketCount; else if (BracketCount) { AngleBrackets.clear(*this); --BracketCount; // Don't let unbalanced ]'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBrace - This consume method keeps the brace count up-to-date. /// SourceLocation ConsumeBrace() { assert(isTokenBrace() && "wrong consume method"); if (Tok.getKind() == tok::l_brace) ++BraceCount; else if (BraceCount) { AngleBrackets.clear(*this); --BraceCount; // Don't let unbalanced }'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeStringToken - Consume the current 'peek token', lexing a new one /// and returning the token kind. This method is specific to strings, as it /// handles string literal concatenation, as per C99 5.1.1.2, translation /// phase #6. SourceLocation ConsumeStringToken() { assert(isTokenStringLiteral() && "Should only consume string literals with this method"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// Consume the current code-completion token. /// /// This routine can be called to consume the code-completion token and /// continue processing in special cases where \c cutOffParsing() isn't /// desired, such as token caching or completion with lookahead. SourceLocation ConsumeCodeCompletionToken() { assert(Tok.is(tok::code_completion)); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } ///\ brief When we are consuming a code-completion token without having /// matched specific position in the grammar, provide code-completion results /// based on context. /// /// \returns the source location of the code-completion token. SourceLocation handleUnexpectedCodeCompletionToken(); /// Abruptly cut off parsing; mainly used when we have reached the /// code-completion point. void cutOffParsing() { if (PP.isCodeCompletionEnabled()) PP.setCodeCompletionReached(); // Cut off parsing by acting as if we reached the end-of-file. Tok.setKind(tok::eof); } /// Determine if we're at the end of the file or at a transition /// between modules. bool isEofOrEom() { tok::TokenKind Kind = Tok.getKind(); return Kind == tok::eof || Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include; } /// Checks if the \p Level is valid for use in a fold expression. bool isFoldOperator(prec::Level Level) const; /// Checks if the \p Kind is a valid operator for fold expressions. bool isFoldOperator(tok::TokenKind Kind) const; /// Initialize all pragma handlers. void initializePragmaHandlers(); /// Destroy and reset all pragma handlers. void resetPragmaHandlers(); /// Handle the annotation token produced for #pragma unused(...) void HandlePragmaUnused(); /// Handle the annotation token produced for /// #pragma GCC visibility... void HandlePragmaVisibility(); /// Handle the annotation token produced for /// #pragma pack... void HandlePragmaPack(); /// Handle the annotation token produced for /// #pragma ms_struct... void HandlePragmaMSStruct(); void HandlePragmaMSPointersToMembers(); void HandlePragmaMSVtorDisp(); void HandlePragmaMSPragma(); bool HandlePragmaMSSection(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSSegment(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSInitSeg(StringRef PragmaName, SourceLocation PragmaLocation); /// Handle the annotation token produced for /// #pragma align... void HandlePragmaAlign(); /// Handle the annotation token produced for /// #pragma clang __debug dump... void HandlePragmaDump(); /// Handle the annotation token produced for /// #pragma weak id... void HandlePragmaWeak(); /// Handle the annotation token produced for /// #pragma weak id = id... void HandlePragmaWeakAlias(); /// Handle the annotation token produced for /// #pragma redefine_extname... void HandlePragmaRedefineExtname(); /// Handle the annotation token produced for /// #pragma STDC FP_CONTRACT... void HandlePragmaFPContract(); /// Handle the annotation token produced for /// #pragma STDC FENV_ACCESS... void HandlePragmaFEnvAccess(); /// Handle the annotation token produced for /// #pragma STDC FENV_ROUND... void HandlePragmaFEnvRound(); /// Handle the annotation token produced for /// #pragma float_control void HandlePragmaFloatControl(); /// \brief Handle the annotation token produced for /// #pragma clang fp ... void HandlePragmaFP(); /// Handle the annotation token produced for /// #pragma OPENCL EXTENSION... void HandlePragmaOpenCLExtension(); /// Handle the annotation token produced for /// #pragma clang __debug captured StmtResult HandlePragmaCaptured(); /// Handle the annotation token produced for /// #pragma clang loop and #pragma unroll. bool HandlePragmaLoopHint(LoopHint &Hint); bool ParsePragmaAttributeSubjectMatchRuleSet( attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc); void HandlePragmaAttribute(); /// GetLookAheadToken - This peeks ahead N tokens and returns that token /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) /// returns the token after Tok, etc. /// /// Note that this differs from the Preprocessor's LookAhead method, because /// the Parser always has one token lexed that the preprocessor doesn't. /// const Token &GetLookAheadToken(unsigned N) { if (N == 0 || Tok.is(tok::eof)) return Tok; return PP.LookAhead(N-1); } public: /// NextToken - This peeks ahead one token and returns it without /// consuming it. const Token &NextToken() { return PP.LookAhead(0); } /// getTypeAnnotation - Read a parsed type out of an annotation token. static TypeResult getTypeAnnotation(const Token &Tok) { if (!Tok.getAnnotationValue()) return TypeError(); return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue()); } private: static void setTypeAnnotation(Token &Tok, TypeResult T) { assert((T.isInvalid() || T.get()) && "produced a valid-but-null type annotation?"); Tok.setAnnotationValue(T.isInvalid() ? nullptr : T.get().getAsOpaquePtr()); } static NamedDecl *getNonTypeAnnotation(const Token &Tok) { return static_cast<NamedDecl*>(Tok.getAnnotationValue()); } static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) { Tok.setAnnotationValue(ND); } static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) { return static_cast<IdentifierInfo*>(Tok.getAnnotationValue()); } static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) { Tok.setAnnotationValue(ND); } /// Read an already-translated primary expression out of an annotation /// token. static ExprResult getExprAnnotation(const Token &Tok) { return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue()); } /// Set the primary expression corresponding to the given annotation /// token. static void setExprAnnotation(Token &Tok, ExprResult ER) { Tok.setAnnotationValue(ER.getAsOpaquePointer()); } public: // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to // find a type name by attempting typo correction. bool TryAnnotateTypeOrScopeToken(); bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope); bool TryAnnotateCXXScopeToken(bool EnteringContext = false); bool MightBeCXXScopeToken() { return Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) || Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super); } bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) { return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext); } private: enum AnnotatedNameKind { /// Annotation has failed and emitted an error. ANK_Error, /// The identifier is a tentatively-declared name. ANK_TentativeDecl, /// The identifier is a template name. FIXME: Add an annotation for that. ANK_TemplateName, /// The identifier can't be resolved. ANK_Unresolved, /// Annotation was successful. ANK_Success }; AnnotatedNameKind TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr); /// Push a tok::annot_cxxscope token onto the token stream. void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation); /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens, /// replacing them with the non-context-sensitive keywords. This returns /// true if the token was replaced. bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid) { if (!getLangOpts().AltiVec && !getLangOpts().ZVector) return false; if (Tok.getIdentifierInfo() != Ident_vector && Tok.getIdentifierInfo() != Ident_bool && Tok.getIdentifierInfo() != Ident_Bool && (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel)) return false; return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid); } /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector /// identifier token, replacing it with the non-context-sensitive __vector. /// This returns true if the token was replaced. bool TryAltiVecVectorToken() { if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) || Tok.getIdentifierInfo() != Ident_vector) return false; return TryAltiVecVectorTokenOutOfLine(); } bool TryAltiVecVectorTokenOutOfLine(); bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid); /// Returns true if the current token is the identifier 'instancetype'. /// /// Should only be used in Objective-C language modes. bool isObjCInstancetype() { assert(getLangOpts().ObjC); if (Tok.isAnnotation()) return false; if (!Ident_instancetype) Ident_instancetype = PP.getIdentifierInfo("instancetype"); return Tok.getIdentifierInfo() == Ident_instancetype; } /// TryKeywordIdentFallback - For compatibility with system headers using /// keywords as identifiers, attempt to convert the current token to an /// identifier and optionally disable the keyword for the remainder of the /// translation unit. This returns false if the token was not replaced, /// otherwise emits a diagnostic and returns true. bool TryKeywordIdentFallback(bool DisableKeyword); /// Get the TemplateIdAnnotation from the token. TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok); /// TentativeParsingAction - An object that is used as a kind of "tentative /// parsing transaction". It gets instantiated to mark the token position and /// after the token consumption is done, Commit() or Revert() is called to /// either "commit the consumed tokens" or revert to the previously marked /// token position. Example: /// /// TentativeParsingAction TPA(*this); /// ConsumeToken(); /// .... /// TPA.Revert(); /// class TentativeParsingAction { Parser &P; PreferredTypeBuilder PrevPreferredType; Token PrevTok; size_t PrevTentativelyDeclaredIdentifierCount; unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount; bool isActive; public: explicit TentativeParsingAction(Parser &p) : P(p), PrevPreferredType(P.PreferredType) { PrevTok = P.Tok; PrevTentativelyDeclaredIdentifierCount = P.TentativelyDeclaredIdentifiers.size(); PrevParenCount = P.ParenCount; PrevBracketCount = P.BracketCount; PrevBraceCount = P.BraceCount; P.PP.EnableBacktrackAtThisPos(); isActive = true; } void Commit() { assert(isActive && "Parsing action was finished!"); P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.PP.CommitBacktrackedTokens(); isActive = false; } void Revert() { assert(isActive && "Parsing action was finished!"); P.PP.Backtrack(); P.PreferredType = PrevPreferredType; P.Tok = PrevTok; P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.ParenCount = PrevParenCount; P.BracketCount = PrevBracketCount; P.BraceCount = PrevBraceCount; isActive = false; } ~TentativeParsingAction() { assert(!isActive && "Forgot to call Commit or Revert!"); } }; /// A TentativeParsingAction that automatically reverts in its destructor. /// Useful for disambiguation parses that will always be reverted. class RevertingTentativeParsingAction : private Parser::TentativeParsingAction { public: RevertingTentativeParsingAction(Parser &P) : Parser::TentativeParsingAction(P) {} ~RevertingTentativeParsingAction() { Revert(); } }; class UnannotatedTentativeParsingAction; /// ObjCDeclContextSwitch - An object used to switch context from /// an objective-c decl context to its enclosing decl context and /// back. class ObjCDeclContextSwitch { Parser &P; Decl *DC; SaveAndRestore<bool> WithinObjCContainer; public: explicit ObjCDeclContextSwitch(Parser &p) : P(p), DC(p.getObjCDeclContext()), WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) { if (DC) P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC)); } ~ObjCDeclContextSwitch() { if (DC) P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC)); } }; /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the /// input. If so, it is consumed and false is returned. /// /// If a trivial punctuator misspelling is encountered, a FixIt error /// diagnostic is issued and false is returned after recovery. /// /// If the input is malformed, this emits the specified diagnostic and true is /// returned. bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag = diag::err_expected, StringRef DiagMsg = ""); /// The parser expects a semicolon and, if present, will consume it. /// /// If the next token is not a semicolon, this emits the specified diagnostic, /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior /// to the semicolon, consumes that extra token. bool ExpectAndConsumeSemi(unsigned DiagID); /// The kind of extra semi diagnostic to emit. enum ExtraSemiKind { OutsideFunction = 0, InsideStruct = 1, InstanceVariableList = 2, AfterMemberFunctionDefinition = 3 }; /// Consume any extra semi-colons until the end of the line. void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified); /// Return false if the next token is an identifier. An 'expected identifier' /// error is emitted otherwise. /// /// The parser tries to recover from the error by checking if the next token /// is a C++ keyword when parsing Objective-C++. Return false if the recovery /// was successful. bool expectIdentifier(); /// Kinds of compound pseudo-tokens formed by a sequence of two real tokens. enum class CompoundToken { /// A '(' '{' beginning a statement-expression. StmtExprBegin, /// A '}' ')' ending a statement-expression. StmtExprEnd, /// A '[' '[' beginning a C++11 or C2x attribute. AttrBegin, /// A ']' ']' ending a C++11 or C2x attribute. AttrEnd, /// A '::' '*' forming a C++ pointer-to-member declaration. MemberPtr, }; /// Check that a compound operator was written in a "sensible" way, and warn /// if not. void checkCompoundToken(SourceLocation FirstTokLoc, tok::TokenKind FirstTokKind, CompoundToken Op); public: //===--------------------------------------------------------------------===// // Scope manipulation /// ParseScope - Introduces a new scope for parsing. The kind of /// scope is determined by ScopeFlags. Objects of this type should /// be created on the stack to coincide with the position where the /// parser enters the new scope, and this object's constructor will /// create that new scope. Similarly, once the object is destroyed /// the parser will exit the scope. class ParseScope { Parser *Self; ParseScope(const ParseScope &) = delete; void operator=(const ParseScope &) = delete; public: // ParseScope - Construct a new object to manage a scope in the // parser Self where the new Scope is created with the flags // ScopeFlags, but only when we aren't about to enter a compound statement. ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true, bool BeforeCompoundStmt = false) : Self(Self) { if (EnteredScope && !BeforeCompoundStmt) Self->EnterScope(ScopeFlags); else { if (BeforeCompoundStmt) Self->incrementMSManglingNumber(); this->Self = nullptr; } } // Exit - Exit the scope associated with this object now, rather // than waiting until the object is destroyed. void Exit() { if (Self) { Self->ExitScope(); Self = nullptr; } } ~ParseScope() { Exit(); } }; /// Introduces zero or more scopes for parsing. The scopes will all be exited /// when the object is destroyed. class MultiParseScope { Parser &Self; unsigned NumScopes = 0; MultiParseScope(const MultiParseScope&) = delete; public: MultiParseScope(Parser &Self) : Self(Self) {} void Enter(unsigned ScopeFlags) { Self.EnterScope(ScopeFlags); ++NumScopes; } void Exit() { while (NumScopes) { Self.ExitScope(); --NumScopes; } } ~MultiParseScope() { Exit(); } }; /// EnterScope - Start a new scope. void EnterScope(unsigned ScopeFlags); /// ExitScope - Pop a scope off the scope stack. void ExitScope(); /// Re-enter the template scopes for a declaration that might be a template. unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D); private: /// RAII object used to modify the scope flags for the current scope. class ParseScopeFlags { Scope *CurScope; unsigned OldFlags; ParseScopeFlags(const ParseScopeFlags &) = delete; void operator=(const ParseScopeFlags &) = delete; public: ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true); ~ParseScopeFlags(); }; //===--------------------------------------------------------------------===// // Diagnostic Emission and Error recovery. public: DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); DiagnosticBuilder Diag(unsigned DiagID) { return Diag(Tok, DiagID); } private: void SuggestParentheses(SourceLocation Loc, unsigned DK, SourceRange ParenRange); void CheckNestedObjCContexts(SourceLocation AtLoc); public: /// Control flags for SkipUntil functions. enum SkipUntilFlags { StopAtSemi = 1 << 0, ///< Stop skipping at semicolon /// Stop skipping at specified token, but don't skip the token itself StopBeforeMatch = 1 << 1, StopAtCodeCompletion = 1 << 2 ///< Stop at code completion }; friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, SkipUntilFlags R) { return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) | static_cast<unsigned>(R)); } /// SkipUntil - Read tokens until we get to the specified token, then consume /// it (unless StopBeforeMatch is specified). Because we cannot guarantee /// that the token will ever occur, this skips to the next token, or to some /// likely good stopping point. If Flags has StopAtSemi flag, skipping will /// stop at a ';' character. Balances (), [], and {} delimiter tokens while /// skipping. /// /// If SkipUntil finds the specified token, it returns true, otherwise it /// returns false. bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { return SkipUntil(llvm::makeArrayRef(T), Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2}; return SkipUntil(TokArray, Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2, T3}; return SkipUntil(TokArray, Flags); } bool SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)); /// SkipMalformedDecl - Read tokens until we get to some likely good stopping /// point for skipping past a simple-declaration. void SkipMalformedDecl(); /// The location of the first statement inside an else that might /// have a missleading indentation. If there is no /// MisleadingIndentationChecker on an else active, this location is invalid. SourceLocation MisleadingIndentationElseLoc; private: //===--------------------------------------------------------------------===// // Lexing and parsing of C++ inline methods. struct ParsingClass; /// [class.mem]p1: "... the class is regarded as complete within /// - function bodies /// - default arguments /// - exception-specifications (TODO: C++0x) /// - and brace-or-equal-initializers for non-static data members /// (including such things in nested classes)." /// LateParsedDeclarations build the tree of those elements so they can /// be parsed after parsing the top-level class. class LateParsedDeclaration { public: virtual ~LateParsedDeclaration(); virtual void ParseLexedMethodDeclarations(); virtual void ParseLexedMemberInitializers(); virtual void ParseLexedMethodDefs(); virtual void ParseLexedAttributes(); virtual void ParseLexedPragmas(); }; /// Inner node of the LateParsedDeclaration tree that parses /// all its members recursively. class LateParsedClass : public LateParsedDeclaration { public: LateParsedClass(Parser *P, ParsingClass *C); ~LateParsedClass() override; void ParseLexedMethodDeclarations() override; void ParseLexedMemberInitializers() override; void ParseLexedMethodDefs() override; void ParseLexedAttributes() override; void ParseLexedPragmas() override; private: Parser *Self; ParsingClass *Class; }; /// Contains the lexed tokens of an attribute with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. /// FIXME: Perhaps we should change the name of LateParsedDeclaration to /// LateParsedTokens. struct LateParsedAttribute : public LateParsedDeclaration { Parser *Self; CachedTokens Toks; IdentifierInfo &AttrName; IdentifierInfo *MacroII = nullptr; SourceLocation AttrNameLoc; SmallVector<Decl*, 2> Decls; explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name, SourceLocation Loc) : Self(P), AttrName(Name), AttrNameLoc(Loc) {} void ParseLexedAttributes() override; void addDecl(Decl *D) { Decls.push_back(D); } }; /// Contains the lexed tokens of a pragma with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. class LateParsedPragma : public LateParsedDeclaration { Parser *Self = nullptr; AccessSpecifier AS = AS_none; CachedTokens Toks; public: explicit LateParsedPragma(Parser *P, AccessSpecifier AS) : Self(P), AS(AS) {} void takeToks(CachedTokens &Cached) { Toks.swap(Cached); } const CachedTokens &toks() const { return Toks; } AccessSpecifier getAccessSpecifier() const { return AS; } void ParseLexedPragmas() override; }; // A list of late-parsed attributes. Used by ParseGNUAttributes. class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> { public: LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { } bool parseSoon() { return ParseSoon; } private: bool ParseSoon; // Are we planning to parse these shortly after creation? }; /// Contains the lexed tokens of a member function definition /// which needs to be parsed at the end of the class declaration /// after parsing all other member declarations. struct LexedMethod : public LateParsedDeclaration { Parser *Self; Decl *D; CachedTokens Toks; explicit LexedMethod(Parser *P, Decl *MD) : Self(P), D(MD) {} void ParseLexedMethodDefs() override; }; /// LateParsedDefaultArgument - Keeps track of a parameter that may /// have a default argument that cannot be parsed yet because it /// occurs within a member function declaration inside the class /// (C++ [class.mem]p2). struct LateParsedDefaultArgument { explicit LateParsedDefaultArgument(Decl *P, std::unique_ptr<CachedTokens> Toks = nullptr) : Param(P), Toks(std::move(Toks)) { } /// Param - The parameter declaration for this parameter. Decl *Param; /// Toks - The sequence of tokens that comprises the default /// argument expression, not including the '=' or the terminating /// ')' or ','. This will be NULL for parameters that have no /// default argument. std::unique_ptr<CachedTokens> Toks; }; /// LateParsedMethodDeclaration - A method declaration inside a class that /// contains at least one entity whose parsing needs to be delayed /// until the class itself is completely-defined, such as a default /// argument (C++ [class.mem]p2). struct LateParsedMethodDeclaration : public LateParsedDeclaration { explicit LateParsedMethodDeclaration(Parser *P, Decl *M) : Self(P), Method(M), ExceptionSpecTokens(nullptr) {} void ParseLexedMethodDeclarations() override; Parser *Self; /// Method - The method declaration. Decl *Method; /// DefaultArgs - Contains the parameters of the function and /// their default arguments. At least one of the parameters will /// have a default argument, but all of the parameters of the /// method will be stored so that they can be reintroduced into /// scope at the appropriate times. SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; /// The set of tokens that make up an exception-specification that /// has not yet been parsed. CachedTokens *ExceptionSpecTokens; }; /// LateParsedMemberInitializer - An initializer for a non-static class data /// member whose parsing must to be delayed until the class is completely /// defined (C++11 [class.mem]p2). struct LateParsedMemberInitializer : public LateParsedDeclaration { LateParsedMemberInitializer(Parser *P, Decl *FD) : Self(P), Field(FD) { } void ParseLexedMemberInitializers() override; Parser *Self; /// Field - The field declaration. Decl *Field; /// CachedTokens - The sequence of tokens that comprises the initializer, /// including any leading '='. CachedTokens Toks; }; /// LateParsedDeclarationsContainer - During parsing of a top (non-nested) /// C++ class, its method declarations that contain parts that won't be /// parsed until after the definition is completed (C++ [class.mem]p2), /// the method declarations and possibly attached inline definitions /// will be stored here with the tokens that will be parsed to create those /// entities. typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer; /// Representation of a class that has been parsed, including /// any member function declarations or definitions that need to be /// parsed after the corresponding top-level class is complete. struct ParsingClass { ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : TopLevelClass(TopLevelClass), IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) {} /// Whether this is a "top-level" class, meaning that it is /// not nested within another class. bool TopLevelClass : 1; /// Whether this class is an __interface. bool IsInterface : 1; /// The class or class template whose definition we are parsing. Decl *TagOrTemplate; /// LateParsedDeclarations - Method declarations, inline definitions and /// nested classes that contain pieces whose parsing will be delayed until /// the top-level class is fully defined. LateParsedDeclarationsContainer LateParsedDeclarations; }; /// The stack of classes that is currently being /// parsed. Nested and local classes will be pushed onto this stack /// when they are parsed, and removed afterward. std::stack<ParsingClass *> ClassStack; ParsingClass &getCurrentClass() { assert(!ClassStack.empty() && "No lexed method stacks!"); return *ClassStack.top(); } /// RAII object used to manage the parsing of a class definition. class ParsingClassDefinition { Parser &P; bool Popped; Sema::ParsingClassState State; public: ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : P(P), Popped(false), State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) { } /// Pop this class of the stack. void Pop() { assert(!Popped && "Nested class has already been popped"); Popped = true; P.PopParsingClass(State); } ~ParsingClassDefinition() { if (!Popped) P.PopParsingClass(State); } }; /// Contains information about any template-specific /// information that has been parsed prior to parsing declaration /// specifiers. struct ParsedTemplateInfo { ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { } ParsedTemplateInfo(TemplateParameterLists *TemplateParams, bool isSpecialization, bool lastParameterListWasEmpty = false) : Kind(isSpecialization? ExplicitSpecialization : Template), TemplateParams(TemplateParams), LastParameterListWasEmpty(lastParameterListWasEmpty) { } explicit ParsedTemplateInfo(SourceLocation ExternLoc, SourceLocation TemplateLoc) : Kind(ExplicitInstantiation), TemplateParams(nullptr), ExternLoc(ExternLoc), TemplateLoc(TemplateLoc), LastParameterListWasEmpty(false){ } /// The kind of template we are parsing. enum { /// We are not parsing a template at all. NonTemplate = 0, /// We are parsing a template declaration. Template, /// We are parsing an explicit specialization. ExplicitSpecialization, /// We are parsing an explicit instantiation. ExplicitInstantiation } Kind; /// The template parameter lists, for template declarations /// and explicit specializations. TemplateParameterLists *TemplateParams; /// The location of the 'extern' keyword, if any, for an explicit /// instantiation SourceLocation ExternLoc; /// The location of the 'template' keyword, for an explicit /// instantiation. SourceLocation TemplateLoc; /// Whether the last template parameter list was empty. bool LastParameterListWasEmpty; SourceRange getSourceRange() const LLVM_READONLY; }; // In ParseCXXInlineMethods.cpp. struct ReenterTemplateScopeRAII; struct ReenterClassScopeRAII; void LexTemplateFunctionForLateParsing(CachedTokens &Toks); void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT); static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT); Sema::ParsingClassState PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface); void DeallocateParsedClasses(ParsingClass *Class); void PopParsingClass(Sema::ParsingClassState); enum CachedInitKind { CIK_DefaultArgument, CIK_DefaultInitializer }; NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS, ParsedAttributes &AccessAttrs, ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo, const VirtSpecifiers &VS, SourceLocation PureSpecLoc); void ParseCXXNonStaticMemberInitializer(Decl *VarD); void ParseLexedAttributes(ParsingClass &Class); void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, bool EnterScope, bool OnDefinition); void ParseLexedAttribute(LateParsedAttribute &LA, bool EnterScope, bool OnDefinition); void ParseLexedMethodDeclarations(ParsingClass &Class); void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM); void ParseLexedMethodDefs(ParsingClass &Class); void ParseLexedMethodDef(LexedMethod &LM); void ParseLexedMemberInitializers(ParsingClass &Class); void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI); void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod); void ParseLexedPragmas(ParsingClass &Class); void ParseLexedPragma(LateParsedPragma &LP); bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks); bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK); bool ConsumeAndStoreConditional(CachedTokens &Toks); bool ConsumeAndStoreUntil(tok::TokenKind T1, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true) { return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken); } bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true); //===--------------------------------------------------------------------===// // C99 6.9: External Definitions. DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr); bool isDeclarationAfterDeclarator(); bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator); DeclGroupPtrTy ParseDeclarationOrFunctionDefinition( ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none); DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, ParsingDeclSpec &DS, AccessSpecifier AS); void SkipFunctionBody(); Decl *ParseFunctionDefinition(ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), LateParsedAttrList *LateParsedAttrs = nullptr); void ParseKNRParamDeclarations(Declarator &D); // EndLoc is filled with the location of the last token of the simple-asm. ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc); ExprResult ParseAsmStringLiteral(bool ForAsmLabel); // Objective-C External Declarations void MaybeSkipAttributes(tok::ObjCKeywordKind Kind); DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs); DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, ParsedAttributes &prefixAttrs); class ObjCTypeParamListScope; ObjCTypeParamList *parseObjCTypeParamList(); ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs( ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc, SmallVectorImpl<IdentifierLocPair> &protocolIdents, SourceLocation &rAngleLoc, bool mayBeProtocolList = true); void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, BalancedDelimiterTracker &T, SmallVectorImpl<Decl *> &AllIvarDecls, bool RBraceMissing); void ParseObjCClassInstanceVariables(Decl *interfaceDecl, tok::ObjCKeywordKind visibility, SourceLocation atLoc); bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P, SmallVectorImpl<SourceLocation> &PLocs, bool WarnOnDeclarations, bool ForObjCContainer, SourceLocation &LAngleLoc, SourceLocation &EndProtoLoc, bool consumeLastToken); /// Parse the first angle-bracket-delimited clause for an /// Objective-C object or object pointer type, which may be either /// type arguments or protocol qualifiers. void parseObjCTypeArgsOrProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken, bool warnOnIncompleteProtocols); /// Parse either Objective-C type arguments or protocol qualifiers; if the /// former, also parse protocol qualifiers afterward. void parseObjCTypeArgsAndProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken); /// Parse a protocol qualifier type such as '<NSCopying>', which is /// an anachronistic way of writing 'id<NSCopying>'. TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc); /// Parse Objective-C type arguments and protocol qualifiers, extending the /// current type with the parsed result. TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc, ParsedType type, bool consumeLastToken, SourceLocation &endLoc); void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl); DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, ParsedAttributes &prefixAttrs); struct ObjCImplParsingDataRAII { Parser &P; Decl *Dcl; bool HasCFunction; typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer; LateParsedObjCMethodContainer LateParsedObjCMethods; ObjCImplParsingDataRAII(Parser &parser, Decl *D) : P(parser), Dcl(D), HasCFunction(false) { P.CurParsedObjCImpl = this; Finished = false; } ~ObjCImplParsingDataRAII(); void finish(SourceRange AtEnd); bool isFinished() const { return Finished; } private: bool Finished; }; ObjCImplParsingDataRAII *CurParsedObjCImpl; void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl); DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc, ParsedAttributes &Attrs); DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd); Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc); Decl *ParseObjCPropertySynthesize(SourceLocation atLoc); Decl *ParseObjCPropertyDynamic(SourceLocation atLoc); IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); // Definitions for Objective-c context sensitive keywords recognition. enum ObjCTypeQual { objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, objc_nonnull, objc_nullable, objc_null_unspecified, objc_NumQuals }; IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; bool isTokIdentifier_in() const; ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx, ParsedAttributes *ParamAttrs); Decl *ParseObjCMethodPrototype( tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition = true); Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition=true); void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); Decl *ParseObjCMethodDefinition(); public: //===--------------------------------------------------------------------===// // C99 6.5: Expressions. /// TypeCastState - State whether an expression is or may be a type cast. enum TypeCastState { NotTypeCast = 0, MaybeTypeCast, IsTypeCast }; ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpressionInExprEvalContext( TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseCaseExpression(SourceLocation CaseLoc); ExprResult ParseConstraintExpression(); ExprResult ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause); ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause); // Expr that doesn't include commas. ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, unsigned &NumLineToksConsumed, bool IsUnevaluated); ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); private: ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec); /// Control what ParseCastExpression will parse. enum CastParseKind { AnyCastExpr = 0, UnaryExprOnly, PrimaryExprOnly }; ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand, bool &NotCastExpr, TypeCastState isTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand = false, TypeCastState isTypeCast = NotTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); /// Returns true if the next token cannot start an expression. bool isNotExpressionStart(); /// Returns true if the next token would start a postfix-expression /// suffix. bool isPostfixExpressionSuffixStart() { tok::TokenKind K = Tok.getKind(); return (K == tok::l_square || K == tok::l_paren || K == tok::period || K == tok::arrow || K == tok::plusplus || K == tok::minusminus); } bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less); void checkPotentialAngleBracket(ExprResult &PotentialTemplateName); bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &, const Token &OpToken); bool checkPotentialAngleBracketDelimiter(const Token &OpToken) { if (auto *Info = AngleBrackets.getCurrent(*this)) return checkPotentialAngleBracketDelimiter(*Info, OpToken); return false; } ExprResult ParsePostfixExpressionSuffix(ExprResult LHS); ExprResult ParseUnaryExprOrTypeTraitExpression(); ExprResult ParseBuiltinPrimaryExpression(); ExprResult ParseSYCLUniqueStableNameExpression(); ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, bool &isCastExpr, ParsedType &CastTy, SourceRange &CastRange); typedef SmallVector<SourceLocation, 20> CommaLocsTy; /// ParseExpressionList - Used for C/C++ (argument-)expression-list. bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs, llvm::function_ref<void()> ExpressionStarts = llvm::function_ref<void()>()); /// ParseSimpleExpressionList - A simple comma-separated list of expressions, /// used for misc language extensions. bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs); /// ParenParseOption - Control what ParseParenExpression will parse. enum ParenParseOption { SimpleExpr, // Only parse '(' expression ')' FoldExpr, // Also allow fold-expression <anything> CompoundStmt, // Also allow '(' compound-statement ')' CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' CastExpr // Also allow '(' type-name ')' <anything> }; ExprResult ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, bool isTypeCast, ParsedType &CastTy, SourceLocation &RParenLoc); ExprResult ParseCXXAmbiguousParenExpression( ParenParseOption &ExprType, ParsedType &CastTy, BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt); ExprResult ParseCompoundLiteralExpression(ParsedType Ty, SourceLocation LParenLoc, SourceLocation RParenLoc); ExprResult ParseGenericSelectionExpression(); ExprResult ParseObjCBoolLiteral(); ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T); //===--------------------------------------------------------------------===// // C++ Expressions ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand, Token &Replacement); ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); bool areTokensAdjacent(const Token &A, const Token &B); void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr, bool EnteringContext, IdentifierInfo &II, CXXScopeSpec &SS); bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHasErrors, bool EnteringContext, bool *MayBePseudoDestructor = nullptr, bool IsTypename = false, IdentifierInfo **LastII = nullptr, bool OnlyNamespace = false, bool InUsingDeclaration = false); //===--------------------------------------------------------------------===// // C++11 5.1.2: Lambda expressions /// Result of tentatively parsing a lambda-introducer. enum class LambdaIntroducerTentativeParse { /// This appears to be a lambda-introducer, which has been fully parsed. Success, /// This is a lambda-introducer, but has not been fully parsed, and this /// function needs to be called again to parse it. Incomplete, /// This is definitely an Objective-C message send expression, rather than /// a lambda-introducer, attribute-specifier, or array designator. MessageSend, /// This is not a lambda-introducer. Invalid, }; // [...] () -> type {...} ExprResult ParseLambdaExpression(); ExprResult TryParseLambdaExpression(); bool ParseLambdaIntroducer(LambdaIntroducer &Intro, LambdaIntroducerTentativeParse *Tentative = nullptr); ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Casts ExprResult ParseCXXCasts(); /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast. ExprResult ParseBuiltinBitCast(); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Type Identification ExprResult ParseCXXTypeid(); //===--------------------------------------------------------------------===// // C++ : Microsoft __uuidof Expression ExprResult ParseCXXUuidof(); //===--------------------------------------------------------------------===// // C++ 5.2.4: C++ Pseudo-Destructor Expressions ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, ParsedType ObjectType); //===--------------------------------------------------------------------===// // C++ 9.3.2: C++ 'this' pointer ExprResult ParseCXXThis(); //===--------------------------------------------------------------------===// // C++ 15: C++ Throw Expression ExprResult ParseThrowExpression(); ExceptionSpecificationType tryParseExceptionSpecification( bool Delayed, SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &DynamicExceptions, SmallVectorImpl<SourceRange> &DynamicExceptionRanges, ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens); // EndLoc is filled with the location of the last token of the specification. ExceptionSpecificationType ParseDynamicExceptionSpecification( SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &Exceptions, SmallVectorImpl<SourceRange> &Ranges); //===--------------------------------------------------------------------===// // C++0x 8: Function declaration trailing-return-type TypeResult ParseTrailingReturnType(SourceRange &Range, bool MayBeFollowedByDirectInit); //===--------------------------------------------------------------------===// // C++ 2.13.5: C++ Boolean Literals ExprResult ParseCXXBoolLiteral(); //===--------------------------------------------------------------------===// // C++ 5.2.3: Explicit type conversion (functional notation) ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. /// This should only be called when the current token is known to be part of /// simple-type-specifier. void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); bool ParseCXXTypeSpecifierSeq(DeclSpec &DS); //===--------------------------------------------------------------------===// // C++ 5.3.4 and 5.3.5: C++ new and delete bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs, Declarator &D); void ParseDirectNewDeclarator(Declarator &D); ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); ExprResult ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start); //===--------------------------------------------------------------------===// // C++ if/switch/while/for condition expression. struct ForRangeInfo; Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc, Sema::ConditionKind CK, ForRangeInfo *FRI = nullptr, bool EnterForConditionScope = false); //===--------------------------------------------------------------------===// // C++ Coroutines ExprResult ParseCoyieldExpression(); //===--------------------------------------------------------------------===// // C++ Concepts ExprResult ParseRequiresExpression(); void ParseTrailingRequiresClause(Declarator &D); //===--------------------------------------------------------------------===// // C99 6.7.8: Initialization. /// ParseInitializer /// initializer: [C99 6.7.8] /// assignment-expression /// '{' ... ExprResult ParseInitializer() { if (Tok.isNot(tok::l_brace)) return ParseAssignmentExpression(); return ParseBraceInitializer(); } bool MayBeDesignationStart(); ExprResult ParseBraceInitializer(); struct DesignatorCompletionInfo { SmallVectorImpl<Expr *> &InitExprs; QualType PreferredBaseType; }; ExprResult ParseInitializerWithPotentialDesignator(DesignatorCompletionInfo); //===--------------------------------------------------------------------===// // clang Expressions ExprResult ParseBlockLiteralExpression(); // ^{...} //===--------------------------------------------------------------------===// // Objective-C Expressions ExprResult ParseObjCAtExpression(SourceLocation AtLocation); ExprResult ParseObjCStringLiteral(SourceLocation AtLoc); ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc); ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc); ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue); ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc); ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc); ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); bool isSimpleObjCMessageExpression(); ExprResult ParseObjCMessageExpression(); ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); ExprResult ParseAssignmentExprWithObjCMessageExprStart( SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr); //===--------------------------------------------------------------------===// // C99 6.8: Statements and Blocks. /// A SmallVector of statements, with stack size 32 (as that is the only one /// used.) typedef SmallVector<Stmt*, 32> StmtVector; /// A SmallVector of expressions, with stack size 12 (the maximum used.) typedef SmallVector<Expr*, 12> ExprVector; /// A SmallVector of types. typedef SmallVector<ParsedType, 12> TypeVector; StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr, ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt); StmtResult ParseStatementOrDeclaration( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc = nullptr); StmtResult ParseStatementOrDeclarationAfterAttributes( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); StmtResult ParseExprStatement(ParsedStmtContext StmtCtx); StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs, ParsedStmtContext StmtCtx); StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx, bool MissingCase = false, ExprResult Expr = ExprResult()); StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx); StmtResult ParseCompoundStatement(bool isStmtExpr = false); StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags); void ParseCompoundStatementLeadingPragmas(); bool ConsumeNullStmt(StmtVector &Stmts); StmtResult ParseCompoundStatementBody(bool isStmtExpr = false); bool ParseParenExprOrCondition(StmtResult *InitStmt, Sema::ConditionResult &CondResult, SourceLocation Loc, Sema::ConditionKind CK, SourceLocation *LParenLoc = nullptr, SourceLocation *RParenLoc = nullptr); StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc); StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc); StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc); StmtResult ParseDoStatement(); StmtResult ParseForStatement(SourceLocation *TrailingElseLoc); StmtResult ParseGotoStatement(); StmtResult ParseContinueStatement(); StmtResult ParseBreakStatement(); StmtResult ParseReturnStatement(); StmtResult ParseAsmStatement(bool &msAsm); StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc); StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); /// Describes the behavior that should be taken for an __if_exists /// block. enum IfExistsBehavior { /// Parse the block; this code is always used. IEB_Parse, /// Skip the block entirely; this code is never used. IEB_Skip, /// Parse the block as a dependent block, which may be used in /// some template instantiations but not others. IEB_Dependent }; /// Describes the condition of a Microsoft __if_exists or /// __if_not_exists block. struct IfExistsCondition { /// The location of the initial keyword. SourceLocation KeywordLoc; /// Whether this is an __if_exists block (rather than an /// __if_not_exists block). bool IsIfExists; /// Nested-name-specifier preceding the name. CXXScopeSpec SS; /// The name we're looking for. UnqualifiedId Name; /// The behavior of this __if_exists or __if_not_exists block /// should. IfExistsBehavior Behavior; }; bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result); void ParseMicrosoftIfExistsStatement(StmtVector &Stmts); void ParseMicrosoftIfExistsExternalDeclaration(); void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, ParsedAttributes &AccessAttrs, AccessSpecifier &CurAS); bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, bool &InitExprsOk); bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, SmallVectorImpl<Expr *> &Constraints, SmallVectorImpl<Expr *> &Exprs); //===--------------------------------------------------------------------===// // C++ 6: Statements and Blocks StmtResult ParseCXXTryBlock(); StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false); StmtResult ParseCXXCatchBlock(bool FnCatch = false); //===--------------------------------------------------------------------===// // MS: SEH Statements and Blocks StmtResult ParseSEHTryBlock(); StmtResult ParseSEHExceptBlock(SourceLocation Loc); StmtResult ParseSEHFinallyBlock(SourceLocation Loc); StmtResult ParseSEHLeaveStatement(); //===--------------------------------------------------------------------===// // Objective-C Statements StmtResult ParseObjCAtStatement(SourceLocation atLoc, ParsedStmtContext StmtCtx); StmtResult ParseObjCTryStmt(SourceLocation atLoc); StmtResult ParseObjCThrowStmt(SourceLocation atLoc); StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc); //===--------------------------------------------------------------------===// // C99 6.7: Declarations. /// A context for parsing declaration specifiers. TODO: flesh this /// out, there are other significant restrictions on specifiers than /// would be best implemented in the parser. enum class DeclSpecContext { DSC_normal, // normal context DSC_class, // class context, enables 'friend' DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list DSC_trailing, // C++11 trailing-type-specifier in a trailing return type DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration DSC_top_level, // top-level/namespace declaration context DSC_template_param, // template parameter context DSC_template_type_arg, // template type argument context DSC_objc_method_result, // ObjC method result context, enables 'instancetype' DSC_condition // condition declaration context }; /// Is this a context in which we are parsing just a type-specifier (or /// trailing-type-specifier)? static bool isTypeSpecifier(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: return false; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return true; } llvm_unreachable("Missing DeclSpecContext case"); } /// Whether a defining-type-specifier is permitted in a given context. enum class AllowDefiningTypeSpec { /// The grammar doesn't allow a defining-type-specifier here, and we must /// not parse one (eg, because a '{' could mean something else). No, /// The grammar doesn't allow a defining-type-specifier here, but we permit /// one for error recovery purposes. Sema will reject. NoButErrorRecovery, /// The grammar allows a defining-type-specifier here, even though it's /// always invalid. Sema will reject. YesButInvalid, /// The grammar allows a defining-type-specifier here, and one can be valid. Yes }; /// Is this a context in which we are parsing defining-type-specifiers (and /// so permit class and enum definitions in addition to non-defining class and /// enum elaborated-type-specifiers)? static AllowDefiningTypeSpec isDefiningTypeSpecifierContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_alias_declaration: case DeclSpecContext::DSC_objc_method_result: return AllowDefiningTypeSpec::Yes; case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_template_param: return AllowDefiningTypeSpec::YesButInvalid; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: return AllowDefiningTypeSpec::NoButErrorRecovery; case DeclSpecContext::DSC_trailing: return AllowDefiningTypeSpec::No; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which an opaque-enum-declaration can appear? static bool isOpaqueEnumDeclarationContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: return true; case DeclSpecContext::DSC_alias_declaration: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which we can perform class template argument /// deduction? static bool isClassTemplateDeductionContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_type_specifier: return true; case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Information on a C++0x for-range-initializer found while parsing a /// declaration which turns out to be a for-range-declaration. struct ForRangeInit { SourceLocation ColonLoc; ExprResult RangeExpr; bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); } }; struct ForRangeInfo : ForRangeInit { StmtResult LoopVar; }; DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, SourceLocation *DeclSpecStart = nullptr); DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, bool RequireSemi, ForRangeInit *FRI = nullptr, SourceLocation *DeclSpecStart = nullptr); bool MightBeDeclarator(DeclaratorContext Context); DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context, SourceLocation *DeclEnd = nullptr, ForRangeInit *FRI = nullptr); Decl *ParseDeclarationAfterDeclarator(Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); bool ParseAsmAttributesAfterDeclarator(Declarator &D); Decl *ParseDeclarationAfterDeclaratorAndAttributes( Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ForRangeInit *FRI = nullptr); Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope); Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope); /// When in code-completion, skip parsing of the function/method body /// unless the body contains the code-completion point. /// /// \returns true if the function body was skipped. bool trySkippingFunctionBody(); bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC, ParsedAttributesWithRange &Attrs); DeclSpecContext getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context); void ParseDeclarationSpecifiers( DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal, LateParsedAttrList *LateAttrs = nullptr); bool DiagnoseMissingSemiAfterTagDefinition( DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext, LateParsedAttrList *LateAttrs = nullptr); void ParseSpecifierQualifierList( DeclSpec &DS, AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal); void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, DeclaratorContext Context); void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC); void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl); void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType, RecordDecl *TagDecl); void ParseStructDeclaration( ParsingDeclSpec &DS, llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback); bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false); bool isTypeSpecifierQualifier(); /// isKnownToBeTypeSpecifier - Return true if we know that the specified token /// is definitely a type-specifier. Return false if it isn't part of a type /// specifier or if we're not sure. bool isKnownToBeTypeSpecifier(const Token &Tok) const; /// Return true if we know that we are definitely looking at a /// decl-specifier, and isn't part of an expression such as a function-style /// cast. Return false if it's no a decl-specifier, or we're not sure. bool isKnownToBeDeclarationSpecifier() { if (getLangOpts().CPlusPlus) return isCXXDeclarationSpecifier() == TPResult::True; return isDeclarationSpecifier(true); } /// isDeclarationStatement - Disambiguates between a declaration or an /// expression statement, when parsing function bodies. /// Returns true for declaration, false for expression. bool isDeclarationStatement() { if (getLangOpts().CPlusPlus) return isCXXDeclarationStatement(); return isDeclarationSpecifier(true); } /// isForInitDeclaration - Disambiguates between a declaration or an /// expression in the context of the C 'clause-1' or the C++ // 'for-init-statement' part of a 'for' statement. /// Returns true for declaration, false for expression. bool isForInitDeclaration() { if (getLangOpts().OpenMP) Actions.startOpenMPLoop(); if (getLangOpts().CPlusPlus) return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true); return isDeclarationSpecifier(true); } /// Determine whether this is a C++1z for-range-identifier. bool isForRangeIdentifier(); /// Determine whether we are currently at the start of an Objective-C /// class message that appears to be missing the open bracket '['. bool isStartOfObjCClassMessageMissingOpenBracket(); /// Starting with a scope specifier, identifier, or /// template-id that refers to the current class, determine whether /// this is a constructor declarator. bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false); /// Specifies the context in which type-id/expression /// disambiguation will occur. enum TentativeCXXTypeIdContext { TypeIdInParens, TypeIdUnambiguous, TypeIdAsTemplateArgument }; /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know /// whether the parens contain an expression or a type-id. /// Returns true for a type-id and false for an expression. bool isTypeIdInParens(bool &isAmbiguous) { if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdInParens, isAmbiguous); isAmbiguous = false; return isTypeSpecifierQualifier(); } bool isTypeIdInParens() { bool isAmbiguous; return isTypeIdInParens(isAmbiguous); } /// Checks if the current tokens form type-id or expression. /// It is similar to isTypeIdInParens but does not suppose that type-id /// is in parenthesis. bool isTypeIdUnambiguously() { bool IsAmbiguous; if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous); return isTypeSpecifierQualifier(); } /// isCXXDeclarationStatement - C++-specialized function that disambiguates /// between a declaration or an expression statement, when parsing function /// bodies. Returns true for declaration, false for expression. bool isCXXDeclarationStatement(); /// isCXXSimpleDeclaration - C++-specialized function that disambiguates /// between a simple-declaration or an expression-statement. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. /// Returns false if the statement is disambiguated as expression. bool isCXXSimpleDeclaration(bool AllowForRangeDecl); /// isCXXFunctionDeclarator - Disambiguates between a function declarator or /// a constructor-style initializer, when parsing declaration statements. /// Returns true for function declarator and false for constructor-style /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration /// might be a constructor-style initializer. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr); struct ConditionDeclarationOrInitStatementState; enum class ConditionOrInitStatement { Expression, ///< Disambiguated as an expression (either kind). ConditionDecl, ///< Disambiguated as the declaration form of condition. InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement. ForRangeDecl, ///< Disambiguated as a for-range declaration. Error ///< Can't be any of the above! }; /// Disambiguates between the different kinds of things that can happen /// after 'if (' or 'switch ('. This could be one of two different kinds of /// declaration (depending on whether there is a ';' later) or an expression. ConditionOrInitStatement isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt, bool CanBeForRangeDecl); bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous); bool isCXXTypeId(TentativeCXXTypeIdContext Context) { bool isAmbiguous; return isCXXTypeId(Context, isAmbiguous); } /// TPResult - Used as the result value for functions whose purpose is to /// disambiguate C++ constructs by "tentatively parsing" them. enum class TPResult { True, False, Ambiguous, Error }; /// Determine whether we could have an enum-base. /// /// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise /// only consider this to be an enum-base if the next token is a '{'. /// /// \return \c false if this cannot possibly be an enum base; \c true /// otherwise. bool isEnumBase(bool AllowSemi); /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a /// declaration specifier, TPResult::False if it is not, /// TPResult::Ambiguous if it could be either a decl-specifier or a /// function-style cast, and TPResult::Error if a parsing error was /// encountered. If it could be a braced C++11 function-style cast, returns /// BracedCastResult. /// Doesn't consume tokens. TPResult isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False, bool *InvalidAsDeclSpec = nullptr); /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or /// \c TPResult::Ambiguous, determine whether the decl-specifier would be /// a type-specifier other than a cv-qualifier. bool isCXXDeclarationSpecifierAType(); /// Determine whether the current token sequence might be /// '<' template-argument-list '>' /// rather than a less-than expression. TPResult isTemplateArgumentList(unsigned TokensToSkip); /// Determine whether an '(' after an 'explicit' keyword is part of a C++20 /// 'explicit(bool)' declaration, in earlier language modes where that is an /// extension. TPResult isExplicitBool(); /// Determine whether an identifier has been tentatively declared as a /// non-type. Such tentative declarations should not be found to name a type /// during a tentative parse, but also should not be annotated as a non-type. bool isTentativelyDeclared(IdentifierInfo *II); // "Tentative parsing" functions, used for disambiguation. If a parsing error // is encountered they will return TPResult::Error. // Returning TPResult::True/False indicates that the ambiguity was // resolved and tentative parsing may stop. TPResult::Ambiguous indicates // that more tentative parsing is necessary for disambiguation. // They all consume tokens, so backtracking should be used after calling them. TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl); TPResult TryParseTypeofSpecifier(); TPResult TryParseProtocolQualifiers(); TPResult TryParsePtrOperatorSeq(); TPResult TryParseOperatorId(); TPResult TryParseInitDeclaratorList(); TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true, bool mayHaveDirectInit = false); TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false); TPResult TryParseFunctionDeclarator(); TPResult TryParseBracketDeclarator(); TPResult TryConsumeDeclarationSpecifier(); /// Try to skip a possibly empty sequence of 'attribute-specifier's without /// full validation of the syntactic structure of attributes. bool TrySkipAttributes(); public: TypeResult ParseTypeName(SourceRange *Range = nullptr, DeclaratorContext Context = DeclaratorContext::TypeName, AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr, ParsedAttributes *Attrs = nullptr); private: void ParseBlockId(SourceLocation CaretLoc); /// Are [[]] attributes enabled? bool standardAttributesAllowed() const { const LangOptions &LO = getLangOpts(); return LO.DoubleSquareBracketAttributes; } // Check for the start of an attribute-specifier-seq in a context where an // attribute is not allowed. bool CheckProhibitedCXX11Attribute() { assert(Tok.is(tok::l_square)); if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square)) return false; return DiagnoseProhibitedCXX11Attribute(); } bool DiagnoseProhibitedCXX11Attribute(); void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation) { if (!standardAttributesAllowed()) return; if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) && Tok.isNot(tok::kw_alignas)) return; DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation); } void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation); void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs, DeclSpec &DS, Sema::TagUseKind TUK); // FixItLoc = possible correct location for the attributes void ProhibitAttributes(ParsedAttributesWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clear(); } void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clearListOnly(); } void DiagnoseProhibitedAttributes(const SourceRange &Range, SourceLocation FixItLoc); // Forbid C++11 and C2x attributes that appear on certain syntactic locations // which standard permits but we don't supported yet, for example, attributes // appertain to decl specifiers. void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs, unsigned DiagID, bool DiagnoseEmptyAttrs = false); /// Skip C++11 and C2x attributes and return the end location of the /// last one. /// \returns SourceLocation() if there are no attributes. SourceLocation SkipCXX11Attributes(); /// Diagnose and skip C++11 and C2x attributes that appear in syntactic /// locations where attributes are not allowed. void DiagnoseAndSkipCXX11Attributes(); /// Emit warnings for C++11 and C2x attributes that are in a position that /// clang accepts as an extension. void DiagnoseCXX11AttributeExtension(ParsedAttributesWithRange &Attrs); /// Parses syntax-generic attribute arguments for attributes which are /// known to the implementation, and adds them to the given ParsedAttributes /// list with the given attribute syntax. Returns the number of arguments /// parsed for the attribute. unsigned ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); enum ParseAttrKindMask { PAKM_GNU = 1 << 0, PAKM_Declspec = 1 << 1, PAKM_CXX11 = 1 << 2, }; /// \brief Parse attributes based on what syntaxes are desired, allowing for /// the order to vary. e.g. with PAKM_GNU | PAKM_Declspec: /// __attribute__((...)) __declspec(...) __attribute__((...))) /// Note that Microsoft attributes (spelled with single square brackets) are /// not supported by this because of parsing ambiguities with other /// constructs. /// /// There are some attribute parse orderings that should not be allowed in /// arbitrary order. e.g., /// /// [[]] __attribute__(()) int i; // OK /// __attribute__(()) [[]] int i; // Not OK /// /// Such situations should use the specific attribute parsing functionality. void ParseAttributes(unsigned WhichAttrKinds, ParsedAttributesWithRange &Attrs, SourceLocation *End = nullptr, LateParsedAttrList *LateAttrs = nullptr); void ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs, SourceLocation *End = nullptr, LateParsedAttrList *LateAttrs = nullptr) { ParsedAttributesWithRange AttrsWithRange(AttrFactory); ParseAttributes(WhichAttrKinds, AttrsWithRange, End, LateAttrs); Attrs.takeAllFrom(AttrsWithRange); } /// \brief Possibly parse attributes based on what syntaxes are desired, /// allowing for the order to vary. bool MaybeParseAttributes(unsigned WhichAttrKinds, ParsedAttributesWithRange &Attrs, SourceLocation *End = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec) || (standardAttributesAllowed() && isCXX11AttributeSpecifier())) { ParseAttributes(WhichAttrKinds, Attrs, End, LateAttrs); return true; } return false; } bool MaybeParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs, SourceLocation *End = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec) || (standardAttributesAllowed() && isCXX11AttributeSpecifier())) { ParseAttributes(WhichAttrKinds, Attrs, End, LateAttrs); return true; } return false; } void MaybeParseGNUAttributes(Declarator &D, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) { ParsedAttributes attrs(AttrFactory); SourceLocation endLoc; ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D); D.takeAttributes(attrs, endLoc); } } /// Parses GNU-style attributes and returns them without source range /// information. /// /// This API is discouraged. Use the version that takes a /// ParsedAttributesWithRange instead. bool MaybeParseGNUAttributes(ParsedAttributes &Attrs, SourceLocation *EndLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) { ParsedAttributesWithRange AttrsWithRange(AttrFactory); ParseGNUAttributes(Attrs, EndLoc, LateAttrs); Attrs.takeAllFrom(AttrsWithRange); return true; } return false; } bool MaybeParseGNUAttributes(ParsedAttributesWithRange &Attrs, SourceLocation *EndLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) { ParseGNUAttributes(Attrs, EndLoc, LateAttrs); return true; } return false; } /// Parses GNU-style attributes and returns them without source range /// information. /// /// This API is discouraged. Use the version that takes a /// ParsedAttributesWithRange instead. void ParseGNUAttributes(ParsedAttributes &Attrs, SourceLocation *EndLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr, Declarator *D = nullptr) { ParsedAttributesWithRange AttrsWithRange(AttrFactory); ParseGNUAttributes(AttrsWithRange, EndLoc, LateAttrs, D); Attrs.takeAllFrom(AttrsWithRange); } void ParseGNUAttributes(ParsedAttributesWithRange &Attrs, SourceLocation *EndLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr, Declarator *D = nullptr); void ParseGNUAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax, Declarator *D); IdentifierLoc *ParseIdentifierLoc(); unsigned ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ReplayOpenMPAttributeTokens(CachedTokens &OpenMPTokens) { // If parsing the attributes found an OpenMP directive, emit those tokens // to the parse stream now. if (!OpenMPTokens.empty()) { PP.EnterToken(Tok, /*IsReinject*/ true); PP.EnterTokenStream(OpenMPTokens, /*DisableMacroExpansion*/ true, /*IsReinject*/ true); ConsumeAnyToken(/*ConsumeCodeCompletionTok*/ true); } } void MaybeParseCXX11Attributes(Declarator &D) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrs(AttrFactory); SourceLocation endLoc; ParseCXX11Attributes(attrs, &endLoc); D.takeAttributes(attrs, endLoc); } } bool MaybeParseCXX11Attributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrsWithRange(AttrFactory); ParseCXX11Attributes(attrsWithRange, endLoc); attrs.takeAllFrom(attrsWithRange); return true; } return false; } bool MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *endLoc = nullptr, bool OuterMightBeMessageSend = false) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) { ParseCXX11Attributes(attrs, endLoc); return true; } return false; } void ParseOpenMPAttributeArgs(IdentifierInfo *AttrName, CachedTokens &OpenMPTokens); void ParseCXX11AttributeSpecifierInternal(ParsedAttributes &Attrs, CachedTokens &OpenMPTokens, SourceLocation *EndLoc = nullptr); void ParseCXX11AttributeSpecifier(ParsedAttributes &Attrs, SourceLocation *EndLoc = nullptr) { CachedTokens OpenMPTokens; ParseCXX11AttributeSpecifierInternal(Attrs, OpenMPTokens, EndLoc); ReplayOpenMPAttributeTokens(OpenMPTokens); } void ParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *EndLoc = nullptr); /// Parses a C++11 (or C2x)-style attribute argument list. Returns true /// if this results in adding an attribute to the ParsedAttributes list. bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, CachedTokens &OpenMPTokens); IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc); void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square)) ParseMicrosoftAttributes(attrs, endLoc); } void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs); void ParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr); bool MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr) { const auto &LO = getLangOpts(); if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec)) { ParseMicrosoftDeclSpecs(Attrs, End); return true; } return false; } void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr); bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs); void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs); void DiagnoseAndSkipExtendedMicrosoftTypeAttributes(); SourceLocation SkipExtendedMicrosoftTypeAttributes(); void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs); void ParseBorlandTypeAttributes(ParsedAttributes &attrs); void ParseOpenCLKernelAttributes(ParsedAttributes &attrs); void ParseOpenCLQualifiers(ParsedAttributes &Attrs); void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs); VersionTuple ParseVersionTuple(SourceRange &Range); void ParseAvailabilityAttribute(IdentifierInfo &Availability, SourceLocation AvailabilityLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); Optional<AvailabilitySpec> ParseAvailabilitySpec(); ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc); void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseSwiftNewTypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseAttributeWithTypeArg(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeofSpecifier(DeclSpec &DS); SourceLocation ParseDecltypeSpecifier(DeclSpec &DS); void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS, SourceLocation StartLoc, SourceLocation EndLoc); void ParseUnderlyingTypeSpecifier(DeclSpec &DS); void ParseAtomicSpecifier(DeclSpec &DS); ExprResult ParseAlignArgument(SourceLocation Start, SourceLocation &EllipsisLoc); void ParseAlignmentSpecifier(ParsedAttributes &Attrs, SourceLocation *endLoc = nullptr); ExprResult ParseExtIntegerArgument(); VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const; VirtSpecifiers::Specifier isCXX11VirtSpecifier() const { return isCXX11VirtSpecifier(Tok); } void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface, SourceLocation FriendLoc); bool isCXX11FinalKeyword() const; bool isClassCompatibleKeyword() const; /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to /// enter a new C++ declarator scope and exit it when the function is /// finished. class DeclaratorScopeObj { Parser &P; CXXScopeSpec &SS; bool EnteredScope; bool CreatedScope; public: DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {} void EnterDeclaratorScope() { assert(!EnteredScope && "Already entered the scope!"); assert(SS.isSet() && "C++ scope was not set!"); CreatedScope = true; P.EnterScope(0); // Not a decl scope. if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS)) EnteredScope = true; } ~DeclaratorScopeObj() { if (EnteredScope) { assert(SS.isSet() && "C++ scope was cleared ?"); P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS); } if (CreatedScope) P.ExitScope(); } }; /// ParseDeclarator - Parse and verify a newly-initialized declarator. void ParseDeclarator(Declarator &D); /// A function that parses a variant of direct-declarator. typedef void (Parser::*DirectDeclParseFunction)(Declarator&); void ParseDeclaratorInternal(Declarator &D, DirectDeclParseFunction DirectDeclParser); enum AttrRequirements { AR_NoAttributesParsed = 0, ///< No attributes are diagnosed. AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes. AR_GNUAttributesParsed = 1 << 1, AR_CXX11AttributesParsed = 1 << 2, AR_DeclspecAttributesParsed = 1 << 3, AR_AllAttributesParsed = AR_GNUAttributesParsed | AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed, AR_VendorAttributesParsed = AR_GNUAttributesParsed | AR_DeclspecAttributesParsed }; void ParseTypeQualifierListOpt( DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed, bool AtomicAllowed = true, bool IdentifierRequired = false, Optional<llvm::function_ref<void()>> CodeCompletionHandler = None); void ParseDirectDeclarator(Declarator &D); void ParseDecompositionDeclarator(Declarator &D); void ParseParenDeclarator(Declarator &D); void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker, bool IsAmbiguous, bool RequiresArg = false); void InitCXXThisScopeForDeclaratorIfRelevant( const Declarator &D, const DeclSpec &DS, llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope); bool ParseRefQualifier(bool &RefQualifierIsLValueRef, SourceLocation &RefQualifierLoc); bool isFunctionDeclaratorIdentifierList(); void ParseFunctionDeclaratorIdentifierList( Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo); void ParseParameterDeclarationClause( DeclaratorContext DeclaratorContext, ParsedAttributes &attrs, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, SourceLocation &EllipsisLoc); void ParseBracketDeclarator(Declarator &D); void ParseMisplacedBracketDeclarator(Declarator &D); //===--------------------------------------------------------------------===// // C++ 7: Declarations [dcl.dcl] /// The kind of attribute specifier we have found. enum CXX11AttributeKind { /// This is not an attribute specifier. CAK_NotAttributeSpecifier, /// This should be treated as an attribute-specifier. CAK_AttributeSpecifier, /// The next tokens are '[[', but this is not an attribute-specifier. This /// is ill-formed by C++11 [dcl.attr.grammar]p6. CAK_InvalidAttributeSpecifier }; CXX11AttributeKind isCXX11AttributeSpecifier(bool Disambiguate = false, bool OuterMightBeMessageSend = false); void DiagnoseUnexpectedNamespace(NamedDecl *Context); DeclGroupPtrTy ParseNamespace(DeclaratorContext Context, SourceLocation &DeclEnd, SourceLocation InlineLoc = SourceLocation()); struct InnerNamespaceInfo { SourceLocation NamespaceLoc; SourceLocation InlineLoc; SourceLocation IdentLoc; IdentifierInfo *Ident; }; using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>; void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs, unsigned int index, SourceLocation &InlineLoc, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker); Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context); Decl *ParseExportDeclaration(); DeclGroupPtrTy ParseUsingDirectiveOrDeclaration( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs); Decl *ParseUsingDirective(DeclaratorContext Context, SourceLocation UsingLoc, SourceLocation &DeclEnd, ParsedAttributes &attrs); struct UsingDeclarator { SourceLocation TypenameLoc; CXXScopeSpec SS; UnqualifiedId Name; SourceLocation EllipsisLoc; void clear() { TypenameLoc = EllipsisLoc = SourceLocation(); SS.clear(); Name.clear(); } }; bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D); DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, SourceLocation &DeclEnd, ParsedAttributesWithRange &Attrs, AccessSpecifier AS = AS_none); Decl *ParseAliasDeclarationAfterDeclarator( const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS, ParsedAttributes &Attrs, Decl **OwnedType = nullptr); Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd); Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // C++ 9: classes [class] and C structs/unions. bool isValidAfterTypeSpecifier(bool CouldBeBitfield); void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, bool EnteringContext, DeclSpecContext DSC, ParsedAttributesWithRange &Attributes); void SkipCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, unsigned TagType, Decl *TagDecl); void ParseCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, ParsedAttributesWithRange &Attrs, unsigned TagType, Decl *TagDecl); ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction, SourceLocation &EqualLoc); bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize, LateParsedAttrList &LateAttrs); void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D, VirtSpecifiers &VS); DeclGroupPtrTy ParseCXXClassMemberDeclaration( AccessSpecifier AS, ParsedAttributes &Attr, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ParsingDeclRAIIObject *DiagsFromTParams = nullptr); DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas( AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs, DeclSpec::TST TagType, Decl *Tag); void ParseConstructorInitializer(Decl *ConstructorDecl); MemInitResult ParseMemInitializer(Decl *ConstructorDecl); void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, Decl *ThisDecl); //===--------------------------------------------------------------------===// // C++ 10: Derived classes [class.derived] TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc, SourceLocation &EndLocation); void ParseBaseClause(Decl *ClassDecl); BaseResult ParseBaseSpecifier(Decl *ClassDecl); AccessSpecifier getAccessSpecifierIfPresent() const; bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId); bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Result); //===--------------------------------------------------------------------===// // OpenMP: Directives and clauses. /// Parse clauses for '#pragma omp declare simd'. DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse a property kind into \p TIProperty for the selector set \p Set and /// selector \p Selector. void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty, llvm::omp::TraitSet Set, llvm::omp::TraitSelector Selector, llvm::StringMap<SourceLocation> &Seen); /// Parse a selector kind into \p TISelector for the selector set \p Set. void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &Seen); /// Parse a selector set kind into \p TISet. void parseOMPTraitSetKind(OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &Seen); /// Parses an OpenMP context property. void parseOMPContextProperty(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &Seen); /// Parses an OpenMP context selector. void parseOMPContextSelector(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &SeenSelectors); /// Parses an OpenMP context selector set. void parseOMPContextSelectorSet(OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &SeenSets); /// Parses OpenMP context selectors. bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI); /// Parse a `match` clause for an '#pragma omp declare variant'. Return true /// if there was an error. bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI, OMPTraitInfo *ParentTI); /// Parse clauses for '#pragma omp declare variant'. void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse 'omp [begin] assume[s]' directive. void ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind, SourceLocation Loc); /// Parse 'omp end assumes' directive. void ParseOpenMPEndAssumesDirective(SourceLocation Loc); /// Parse clauses for '#pragma omp [begin] declare target'. void ParseOMPDeclareTargetClauses(Sema::DeclareTargetContextInfo &DTCI); /// Parse '#pragma omp end declare target'. void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind, OpenMPDirectiveKind EndDKind, SourceLocation Loc); /// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if /// it is not the current token. void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind); /// Check the \p FoundKind against the \p ExpectedKind, if not issue an error /// that the "end" matching the "begin" directive of kind \p BeginKind was not /// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd /// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`. void parseOMPEndDirective(OpenMPDirectiveKind BeginKind, OpenMPDirectiveKind ExpectedKind, OpenMPDirectiveKind FoundKind, SourceLocation MatchingLoc, SourceLocation FoundLoc, bool SkipUntilOpenMPEnd); /// Parses declarative OpenMP directives. DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl( AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, bool Delayed = false, DeclSpec::TST TagType = DeclSpec::TST_unspecified, Decl *TagDecl = nullptr); /// Parse 'omp declare reduction' construct. DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS); /// Parses initializer for provided omp_priv declaration inside the reduction /// initializer. void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm); /// Parses 'omp declare mapper' directive. DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS); /// Parses variable declaration in 'omp declare mapper' directive. TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range, DeclarationName &Name, AccessSpecifier AS = AS_none); /// Tries to parse cast part of OpenMP array shaping operation: /// '[' expression ']' { '[' expression ']' } ')'. bool tryParseOpenMPArrayShapingCastPart(); /// Parses simple list of variables. /// /// \param Kind Kind of the directive. /// \param Callback Callback function to be called for the list elements. /// \param AllowScopeSpecifier true, if the variables can have fully /// qualified names. /// bool ParseOpenMPSimpleVarList( OpenMPDirectiveKind Kind, const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> & Callback, bool AllowScopeSpecifier); /// Parses declarative or executable directive. /// /// \param StmtCtx The context in which we're parsing the directive. StmtResult ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx); /// Parses clause of kind \a CKind for directive of a kind \a Kind. /// /// \param DKind Kind of current directive. /// \param CKind Kind of current clause. /// \param FirstClause true, if this is the first clause of a kind \a CKind /// in current directive. /// OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, bool FirstClause); /// Parses clause with a single expression of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses simple clause of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause with a single expression and an additional argument /// of a kind \a Kind. /// /// \param DKind Directive kind. /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); /// Parses the 'sizes' clause of a '#pragma omp tile' directive. OMPClause *ParseOpenMPSizesClause(); /// Parses clause without any additional arguments. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false); /// Parses clause with the list of variables of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); /// Parses and creates OpenMP 5.0 iterators expression: /// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier = /// <range-specification> }+ ')' ExprResult ParseOpenMPIteratorsExpr(); /// Parses allocators and traits in the context of the uses_allocator clause. /// Expected format: /// '(' { <allocator> [ '(' <allocator_traits> ')' ] }+ ')' OMPClause *ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind); /// Parses clause with an interop variable of kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. // OMPClause *ParseOpenMPInteropClause(OpenMPClauseKind Kind, bool ParseOnly); public: /// Parses simple expression in parens for single-expression clauses of OpenMP /// constructs. /// \param RLoc Returned location of right paren. ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc, bool IsAddressOfOperand = false); /// Data used for parsing list of variables in OpenMP clauses. struct OpenMPVarListDataTy { Expr *DepModOrTailExpr = nullptr; SourceLocation ColonLoc; SourceLocation RLoc; CXXScopeSpec ReductionOrMapperIdScopeSpec; DeclarationNameInfo ReductionOrMapperId; int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or ///< lastprivate clause. SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> MapTypeModifiers; SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers> MapTypeModifiersLoc; SmallVector<OpenMPMotionModifierKind, NumberOfOMPMotionModifiers> MotionModifiers; SmallVector<SourceLocation, NumberOfOMPMotionModifiers> MotionModifiersLoc; bool IsMapTypeImplicit = false; SourceLocation ExtraModifierLoc; }; /// Parses clauses with list. bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl<Expr *> &Vars, OpenMPVarListDataTy &Data); bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result); /// Parses the mapper modifier in map, to, and from clauses. bool parseMapperModifier(OpenMPVarListDataTy &Data); /// Parses map-type-modifiers in map clause. /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) bool parseMapTypeModifiers(OpenMPVarListDataTy &Data); private: //===--------------------------------------------------------------------===// // C++ 14: Templates [temp] // C++ 14.1: Template Parameters [temp.param] Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS); Decl *ParseSingleDeclarationAfterTemplate( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); bool ParseTemplateParameters(MultiParseScope &TemplateScopes, unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams, SourceLocation &LAngleLoc, SourceLocation &RAngleLoc); bool ParseTemplateParameterList(unsigned Depth, SmallVectorImpl<NamedDecl*> &TemplateParams); TPResult isStartOfTemplateTypeParameter(); NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); bool isTypeConstraintAnnotation(); bool TryAnnotateTypeConstraint(); void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc, SourceLocation CorrectLoc, bool AlreadyHasEllipsis, bool IdentifierHasName); void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc, Declarator &D); // C++ 14.3: Template arguments [temp.arg] typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList; bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc, SourceLocation &RAngleLoc, bool ConsumeLastToken, bool ObjCGenericList); bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken, SourceLocation &LAngleLoc, TemplateArgList &TemplateArgs, SourceLocation &RAngleLoc); bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &TemplateName, bool AllowTypeAnnotation = true, bool TypeConstraint = false); void AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS, bool IsClassName = false); bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs); ParsedTemplateArgument ParseTemplateTemplateArgument(); ParsedTemplateArgument ParseTemplateArgument(); Decl *ParseExplicitInstantiation(DeclaratorContext Context, SourceLocation ExternLoc, SourceLocation TemplateLoc, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); // C++2a: Template, concept definition [temp] Decl * ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // Modules DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl); Decl *ParseModuleImport(SourceLocation AtLoc); bool parseMisplacedModuleImport(); bool tryParseMisplacedModuleImport() { tok::TokenKind Kind = Tok.getKind(); if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include) return parseMisplacedModuleImport(); return false; } bool ParseModuleName( SourceLocation UseLoc, SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, bool IsImport); //===--------------------------------------------------------------------===// // C++11/G++: Type Traits [Type-Traits.html in the GCC manual] ExprResult ParseTypeTrait(); //===--------------------------------------------------------------------===// // Embarcadero: Arary and Expression Traits ExprResult ParseArrayTypeTrait(); ExprResult ParseExpressionTrait(); //===--------------------------------------------------------------------===// // Preprocessor code-completion pass-through void CodeCompleteDirective(bool InConditional) override; void CodeCompleteInConditionalExclusion() override; void CodeCompleteMacroName(bool IsDefinition) override; void CodeCompletePreprocessorExpression() override; void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex) override; void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override; void CodeCompleteNaturalLanguage() override; class GNUAsmQualifiers { unsigned Qualifiers = AQ_unspecified; public: enum AQ { AQ_unspecified = 0, AQ_volatile = 1, AQ_inline = 2, AQ_goto = 4, }; static const char *getQualifierName(AQ Qualifier); bool setAsmQualifier(AQ Qualifier); inline bool isVolatile() const { return Qualifiers & AQ_volatile; }; inline bool isInline() const { return Qualifiers & AQ_inline; }; inline bool isGoto() const { return Qualifiers & AQ_goto; } }; bool isGCCAsmStatement(const Token &TokAfterAsm) const; bool isGNUAsmQualifier(const Token &TokAfterAsm) const; GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const; bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ); }; } // end namespace clang #endif
GB_unaryop__minv_int64_uint32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_int64_uint32 // op(A') function: GB_tran__minv_int64_uint32 // C type: int64_t // A type: uint32_t // cast: int64_t cij = (int64_t) aij // unaryop: cij = GB_IMINV_SIGNED (aij, 64) #define GB_ATYPE \ uint32_t #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IMINV_SIGNED (x, 64) ; // casting #define GB_CASTING(z, x) \ int64_t z = (int64_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_INT64 || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_int64_uint32 ( int64_t *restrict Cx, const uint32_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_int64_uint32 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
core_zgemm.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> c d s * **/ #include <plasma_core_blas.h> #include "plasma_types.h" #include "core_lapack.h" /***************************************************************************//** * * @ingroup core_gemm * * Performs one of the matrix-matrix operations * * \f[ C = \alpha [op( A )\times op( B )] + \beta C, \f] * * where op( X ) is one of: * \f[ op( X ) = X, \f] * \f[ op( X ) = X^T, \f] * \f[ op( X ) = X^H, \f] * * alpha and beta are scalars, and A, B and C are matrices, with op( A ) * an m-by-k matrix, op( B ) a k-by-n matrix and C an m-by-n matrix. * ******************************************************************************* * * @param[in] transa * - PlasmaNoTrans: A is not transposed, * - PlasmaTrans: A is transposed, * - PlasmaConjTrans: A is conjugate transposed. * * @param[in] transb * - PlasmaNoTrans: B is not transposed, * - PlasmaTrans: B is transposed, * - PlasmaConjTrans: B is conjugate transposed. * * @param[in] m * The number of rows of the matrix op( A ) and of the matrix C. * m >= 0. * * @param[in] n * The number of columns of the matrix op( B ) and of the matrix C. * n >= 0. * * @param[in] k * The number of columns of the matrix op( A ) and the number of rows * of the matrix op( B ). k >= 0. * * @param[in] alpha * The scalar alpha. * * @param[in] A * An lda-by-ka matrix, where ka is k when transa = PlasmaNoTrans, * and is m otherwise. * * @param[in] lda * The leading dimension of the array A. * When transa = PlasmaNoTrans, lda >= max(1,m), * otherwise, lda >= max(1,k). * * @param[in] B * An ldb-by-kb matrix, where kb is n when transb = PlasmaNoTrans, * and is k otherwise. * * @param[in] ldb * The leading dimension of the array B. * When transb = PlasmaNoTrans, ldb >= max(1,k), * otherwise, ldb >= max(1,n). * * @param[in] beta * The scalar beta. * * @param[in,out] C * An ldc-by-n matrix. On exit, the array is overwritten by the m-by-n * matrix ( alpha*op( A )*op( B ) + beta*C ). * * @param[in] ldc * The leading dimension of the array C. ldc >= max(1,m). * ******************************************************************************/ __attribute__((weak)) void plasma_core_zgemm(plasma_enum_t transa, plasma_enum_t transb, int m, int n, int k, plasma_complex64_t alpha, const plasma_complex64_t *A, int lda, const plasma_complex64_t *B, int ldb, plasma_complex64_t beta, plasma_complex64_t *C, int ldc) { cblas_zgemm(CblasColMajor, (CBLAS_TRANSPOSE)transa, (CBLAS_TRANSPOSE)transb, m, n, k, CBLAS_SADDR(alpha), A, lda, B, ldb, CBLAS_SADDR(beta), C, ldc); } /******************************************************************************/ void plasma_core_omp_zgemm( plasma_enum_t transa, plasma_enum_t transb, int m, int n, int k, plasma_complex64_t alpha, const plasma_complex64_t *A, int lda, const plasma_complex64_t *B, int ldb, plasma_complex64_t beta, plasma_complex64_t *C, int ldc, plasma_sequence_t *sequence, plasma_request_t *request) { int ak; if (transa == PlasmaNoTrans) ak = k; else ak = m; int bk; if (transb == PlasmaNoTrans) bk = n; else bk = k; #pragma omp task depend(in:A[0:lda*ak]) \ depend(in:B[0:ldb*bk]) \ depend(inout:C[0:ldc*n]) { if (sequence->status == PlasmaSuccess) plasma_core_zgemm(transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc); } }
7248.c
/* POLYBENCH/GPU-OPENMP * * This file is a part of the Polybench/GPU-OpenMP suite * * Contact: * William Killian <killian@udel.edu> * * Copyright 2013, The University of Delaware */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4000. */ #include "3mm.h" /* Array initialization. */ static void init_array(int ni, int nj, int nk, int nl, int nm, DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk), DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj), DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm), DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nk; j++) A[i][j] = ((DATA_TYPE) i*j) / ni; for (i = 0; i < nk; i++) for (j = 0; j < nj; j++) B[i][j] = ((DATA_TYPE) i*(j+1)) / nj; for (i = 0; i < nj; i++) for (j = 0; j < nm; j++) C[i][j] = ((DATA_TYPE) i*(j+3)) / nl; for (i = 0; i < nm; i++) for (j = 0; j < nl; j++) D[i][j] = ((DATA_TYPE) i*(j+2)) / nk; } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int ni, int nl, DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nl; j++) { fprintf (stderr, DATA_PRINTF_MODIFIER, G[i][j]); if ((i * ni + j) % 20 == 0) fprintf (stderr, "\n"); } fprintf (stderr, "\n"); } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_3mm(int ni, int nj, int nk, int nl, int nm, DATA_TYPE POLYBENCH_2D(E,NI,NJ,ni,nj), DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk), DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj), DATA_TYPE POLYBENCH_2D(F,NJ,NL,nj,nl), DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm), DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl), DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl)) { int i, j, k; #pragma scop #pragma omp parallel private (i, j, k) num_threads(#P11) { /* E := A*B */ #pragma omp for (i = 0; i < _PB_NI; i++) { for (j = 0; j < _PB_NJ; j++) { E[i][j] = 0; for (k = 0; k < _PB_NK; ++k) E[i][j] += A[i][k] * B[k][j]; } } /* F := C*D */ #pragma omp for (i = 0; i < _PB_NJ; i++) { for (j = 0; j < _PB_NL; j++) { F[i][j] = 0; for (k = 0; k < _PB_NM; ++k) F[i][j] += C[i][k] * D[k][j]; } } /* G := E*F */ #pragma omp for (i = 0; i < _PB_NI; i++) { for (j = 0; j < _PB_NL; j++) { G[i][j] = 0; for (k = 0; k < _PB_NJ; ++k) G[i][j] += E[i][k] * F[k][j]; } } } #pragma endscop } int main(int argc, char** argv) { /* Retrieve problem size. */ int ni = NI; int nj = NJ; int nk = NK; int nl = NL; int nm = NM; /* Variable declaration/allocation. */ POLYBENCH_2D_ARRAY_DECL(E, DATA_TYPE, NI, NJ, ni, nj); POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NK, ni, nk); POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NK, NJ, nk, nj); POLYBENCH_2D_ARRAY_DECL(F, DATA_TYPE, NJ, NL, nj, nl); POLYBENCH_2D_ARRAY_DECL(C, DATA_TYPE, NJ, NM, nj, nm); POLYBENCH_2D_ARRAY_DECL(D, DATA_TYPE, NM, NL, nm, nl); POLYBENCH_2D_ARRAY_DECL(G, DATA_TYPE, NI, NL, ni, nl); /* Initialize array(s). */ init_array (ni, nj, nk, nl, nm, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B), POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(D)); /* Start timer. */ polybench_start_instruments; /* Run kernel. */ kernel_3mm (ni, nj, nk, nl, nm, POLYBENCH_ARRAY(E), POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B), POLYBENCH_ARRAY(F), POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(D), POLYBENCH_ARRAY(G)); /* Stop and print timer. */ polybench_stop_instruments; polybench_print_instruments; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ polybench_prevent_dce(print_array(ni, nl, POLYBENCH_ARRAY(G))); /* Be clean. */ POLYBENCH_FREE_ARRAY(E); POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(B); POLYBENCH_FREE_ARRAY(F); POLYBENCH_FREE_ARRAY(C); POLYBENCH_FREE_ARRAY(D); POLYBENCH_FREE_ARRAY(G); return 0; }
re_comp.h
/*! * This file is part of GPBoost a C++ library for combining * boosting with Gaussian process and mixed effects models * * Copyright (c) 2020 Fabio Sigrist. All rights reserved. * * Licensed under the Apache License Version 2.0. See LICENSE file in the project root for license information. */ #ifndef GPB_RE_COMP_H_ #define GPB_RE_COMP_H_ #include <GPBoost/type_defs.h> #include <GPBoost/cov_fcts.h> #include <GPBoost/GP_utils.h> #include <memory> #include <mutex> #include <vector> #include <type_traits> #include <random> #include <LightGBM/utils/log.h> using LightGBM::Log; namespace GPBoost { /*! * \brief This class models the random effects components * * Some details: * 1. The template parameter <T_mat> can be either <den_mat_t> or <sp_mat_t> */ template<typename T_mat> class RECompBase { public: /*! \brief Virtual destructor */ virtual ~RECompBase() {}; /*! * \brief Create and adds the matrix Z_ * Note: this is currently only used when changing the likelihood in the re_model */ virtual void AddZ() = 0; /*! * \brief Drop the matrix Z_ * Note: this is currently only used when changing the likelihood in the re_model */ virtual void DropZ() = 0; /*! * \brief Function that sets the covariance parameters * \param pars Vector with covariance parameters */ virtual void SetCovPars(const vec_t& pars) = 0; /*! * \brief Transform the covariance parameters * \param sigma2 Marginal variance * \param pars Vector with covariance parameters on orignal scale * \param[out] pars_trans Transformed covariance parameters */ virtual void TransformCovPars(const double sigma2, const vec_t& pars, vec_t& pars_trans) = 0; /*! * \brief Back-transform the covariance parameters to the original scale * \param sigma2 Marginal variance * \param pars Vector with covariance parameters * \param[out] pars_orig Back-transformed, original covariance parameters */ virtual void TransformBackCovPars(const double sigma2, const vec_t& pars, vec_t& pars_orig) = 0; /*! * \brief Find "reasonable" default values for the intial values of the covariance parameters (on transformed scale) * \param sigma2 Marginal variance * \param[out] pars Vector with covariance parameters */ virtual void FindInitCovPar(vec_t& pars) const = 0; /*! * \brief Virtual function that calculates Sigma (not needed for grouped REs, at unique locations for GPs) */ virtual void CalcSigma() = 0; /*! * \brief Virtual function that calculates the covariance matrix Z*Sigma*Z^T * \return Covariance matrix Z*Sigma*Z^T of this component * Note that since sigma_ is saved (since it is used in GetZSigmaZt and GetZSigmaZtGrad) we return a pointer and do not write on an input paramter in order to avoid copying */ virtual std::shared_ptr<T_mat> GetZSigmaZt() const = 0; /*! * \brief Virtual function that calculates the derivatives of the covariance matrix Z*Sigma*Z^T * \param ind_par Index for parameter * \param transf_scale If true, the derivative is taken on the transformed scale otherwise on the original scale. Default = true * \param nugget_var Nugget effect variance parameter sigma^2 (used only if transf_scale = false to transform back) * \return Derivative of covariance matrix Z*Sigma*Z^T with respect to the parameter number ind_par */ virtual std::shared_ptr<T_mat> GetZSigmaZtGrad(int ind_par = 0, bool transf_scale = true, double = 1.) const = 0; /*! * \brief Virtual function that returns the matrix Z * \return A pointer to the matrix Z */ virtual sp_mat_t* GetZ() = 0; /*! * \brief This is only used for the class RECompGP and not for other derived classes. It is here in order that the base class can have this as a virtual method and no conversion needs to be made in the Vecchia approximation calculation (slightly a hack) */ virtual void CalcSigmaAndSigmaGrad(const den_mat_t& dist, den_mat_t& cov_mat, den_mat_t& cov_grad_1, den_mat_t& cov_grad_2, bool calc_gradient = false, bool transf_scale = true, double = 1.) const = 0; /*! * \brief Virtual function that returns the number of unique random effects * \return Number of unique random effects */ virtual data_size_t GetNumUniqueREs() const = 0; /*! * \brief Returns number of covariance parameters * \return Number of covariance parameters */ int NumCovPar() const { return(num_cov_par_); } /*! * \brief Calculate and add unconditional predictive variances * \param[out] pred_uncond_var Array of unconditional predictive variances to which the variance of this component is added * \param num_data_pred Number of prediction points * \param rand_coef_data_pred Covariate data for varying coefficients */ void AddPredUncondVar(double* pred_uncond_var, int num_data_pred, const double* const rand_coef_data_pred = nullptr) const { if (this->is_rand_coef_) { #pragma omp for schedule(static) for (int i = 0; i < num_data_pred; ++i) { pred_uncond_var[i] += this->cov_pars_[0] * rand_coef_data_pred[i] * rand_coef_data_pred[i]; } } else { #pragma omp for schedule(static) for (int i = 0; i < num_data_pred; ++i) { pred_uncond_var[i] += this->cov_pars_[0]; } } } protected: /*! \brief Number of data points */ data_size_t num_data_; /*! \brief Number of parameters */ int num_cov_par_; /*! \brief Incidence matrix Z */ sp_mat_t Z_; /*! \brief Indicates whether the random effect component has a (non-identity) incidence matrix Z */ bool has_Z_; /*! \brief Covariate data for varying coefficients */ std::vector<double> rand_coef_data_; /*! \brief true if this is a random coefficient */ bool is_rand_coef_; /*! \brief Covariance parameters (on transformed scale, but not logarithmic) */ vec_t cov_pars_; /*! \brief Indices that indicate to which random effect every data point is related (random_effects_indices_of_data_[i] is the random effect for observation number i) */ std::vector<data_size_t> random_effects_indices_of_data_; template<typename T_mat_aux, typename T_chol_aux> friend class REModelTemplate; }; /*! * \brief Class for the grouped random effect components * * Some details: */ template<typename T_mat> class RECompGroup : public RECompBase<T_mat> { public: /*! \brief Constructor */ RECompGroup(); /*! * \brief Constructor without random coefficient data * \param group_data Group data: factorial variable between 1 and the number of different groups * \param calculateZZt If true, the matrix Z*Z^T is calculated and saved (not needed if Woodbury identity is used) * \param save_Z If true, the matrix Z_ is constructed and saved */ RECompGroup(std::vector<re_group_t>& group_data, bool calculateZZt, bool save_Z) { this->has_Z_ = save_Z; this->num_data_ = (data_size_t)group_data.size(); this->is_rand_coef_ = false; this->num_cov_par_ = 1; num_group_ = 0; std::map<re_group_t, int> map_group_label_index; for (const auto& el : group_data) { if (map_group_label_index.find(el) == map_group_label_index.end()) { map_group_label_index.insert({ el, num_group_ }); num_group_ += 1; } } this->random_effects_indices_of_data_ = std::vector<data_size_t>(this->num_data_); #pragma omp parallel for schedule(static) for (int i = 0; i < this->num_data_; ++i) { this->random_effects_indices_of_data_[i] = map_group_label_index[group_data[i]]; } if(save_Z){ CreateZ();// Create incidence matrix Z } has_ZZt_ = calculateZZt; if (has_ZZt_) { ConstructZZt<T_mat>(); } map_group_label_index_ = std::make_shared<std::map<re_group_t, int>>(map_group_label_index); } /*! * \brief Constructor for random coefficient effects * \param group_data Reference to group data of random intercept corresponding to this effect * \param num_group Number of groups / levels * \param rand_coef_data Covariate data for varying coefficients * \param calculateZZt If true, the matrix Z*Z^T is calculated and saved (not needed if Woodbury identity is used) */ RECompGroup(const data_size_t* random_effects_indices_of_data, const data_size_t num_data, std::shared_ptr<std::map<re_group_t, int>> map_group_label_index, data_size_t num_group, std::vector<double>& rand_coef_data, bool calculateZZt) { this->num_data_ = num_data; num_group_ = num_group; //group_data_ = group_data; map_group_label_index_ = map_group_label_index; this->rand_coef_data_ = rand_coef_data; this->is_rand_coef_ = true; this->num_cov_par_ = 1; this->Z_.resize(this->num_data_, num_group_); std::vector<Triplet_t> triplets(this->num_data_); #pragma omp parallel for schedule(static) for (int i = 0; i < this->num_data_; ++i) { triplets[i] = Triplet_t(i, random_effects_indices_of_data[i], this->rand_coef_data_[i]); } this->Z_.setFromTriplets(triplets.begin(), triplets.end()); //// Alternative version: inserting elements directly (see constructor above) //for (int i = 0; i < this->num_data_; ++i) { // this->Z_.insert(i, (*map_group_label_index_)[(*group_data_)[i]]) = this->rand_coef_data_[i]; //} this->has_Z_ = true; has_ZZt_ = calculateZZt; if (has_ZZt_) { ConstructZZt<T_mat>(); } } /*! \brief Destructor */ ~RECompGroup() { } /*! * \brief Create and adds the matrix Z_ * Note: this is currently only used when changing the likelihood in the re_model */ void AddZ() override { CHECK(!this->is_rand_coef_);//not intended for random coefficient models if (!this->has_Z_) { CreateZ(); if (has_ZZt_) { ConstructZZt<T_mat>(); } } } /*! * \brief Drop the matrix Z_ * Note: this is currently only used when changing the likelihood in the re_model */ void DropZ() override { CHECK(!this->is_rand_coef_);//not intended for random coefficient models if (this->has_Z_) { this->Z_.resize(0, 0); this->has_Z_ = false; if (has_ZZt_) { ConstructZZt<T_mat>(); } } } /*! * \brief Create the matrix Z_ */ void CreateZ() { CHECK(!this->is_rand_coef_);//not intended for random coefficient models this->Z_.resize(this->num_data_, num_group_); std::vector<Triplet_t> triplets(this->num_data_); #pragma omp parallel for schedule(static) for (int i = 0; i < this->num_data_; ++i) { triplets[i] = Triplet_t(i, this->random_effects_indices_of_data_[i], 1); } this->Z_.setFromTriplets(triplets.begin(), triplets.end()); // Alternative version: inserting elements directly // Note: compared to using triples, this is much slower when group_data is not ordered (e.g. [1,2,3,1,2,3]), otherwise if group_data is ordered (e.g. [1,1,2,2,3,3]) there is no big difference ////this->Z_.reserve(Eigen::VectorXi::Constant(this->num_data_, 1));//don't use this, it makes things much slower //for (int i = 0; i < this->num_data_; ++i) { // this->Z_.insert(i, this->random_effects_indices_of_data_[i]) = 1.; //} } /*! * \brief Function that sets the covariance parameters * \param pars Vector of length 1 with variance of the grouped random effect */ void SetCovPars(const vec_t& pars) override { CHECK((int)pars.size() == 1); this->cov_pars_ = pars; } /*! * \brief Transform the covariance parameters * \param sigma2 Marginal variance * \param pars Vector of length 1 with variance of the grouped random effect * \param[out] pars_trans Transformed covariance parameters */ void TransformCovPars(const double sigma2, const vec_t& pars, vec_t& pars_trans) override { pars_trans = pars / sigma2; } /*! * \brief Back-transform the covariance parameters to the original scale * \param sigma2 Marginal variance * \param pars Vector of length 1 with variance of the grouped random effect * \param[out] pars_orig Back-transformed, original covariance parameters */ void TransformBackCovPars(const double sigma2, const vec_t& pars, vec_t& pars_orig) override { pars_orig = sigma2 * pars; } /*! * \brief Find "reasonable" default values for the intial values of the covariance parameters (on transformed scale) * \param sigma2 Marginal variance * \param[out] pars Vector of length 1 with variance of the grouped random effect */ void FindInitCovPar(vec_t& pars) const override {//TODO: find better initial estimates (as e.g. the variance of the group means) pars[0] = 1; } /*! * \brief Calculate covariance matrix Sigma (not needed for grouped REs) */ void CalcSigma() override { } /*! * \brief Calculate covariance matrix Z*Sigma*Z^T * \param pars Vector of length 1 with covariance parameter sigma_j for grouped RE component number j * \return Covariance matrix Z*Sigma*Z^T of this component */ std::shared_ptr<T_mat> GetZSigmaZt() const override { if (this->cov_pars_.size() == 0) { Log::REFatal("Covariance parameters are not specified. Call 'SetCovPars' first."); } if (this->ZZt_.cols() == 0) { Log::REFatal("Matrix ZZt_ not defined"); } return(std::make_shared<T_mat>(this->cov_pars_[0] * ZZt_)); } /*! * \brief Calculate derivative of covariance matrix Z*Sigma*Z^T with respect to the parameter * \param ind_par Index for parameter (0=variance, 1=inverse range) * \param transf_scale If true, the derivative is taken on the transformed scale otherwise on the original scale. Default = true * \param nugget_var Nugget effect variance parameter sigma^2 (not use here) * \return Derivative of covariance matrix Z*Sigma*Z^T with respect to the parameter number ind_par */ std::shared_ptr<T_mat> GetZSigmaZtGrad(int ind_par, bool transf_scale = true, double = 1.) const override { if (this->cov_pars_.size() == 0) { Log::REFatal("Covariance parameters are not specified. Call 'SetCovPars' first."); } if (this->ZZt_.cols() == 0) { Log::REFatal("Matrix ZZt_ not defined"); } if (ind_par != 0) { Log::REFatal("No covariance parameter for index number %d", ind_par); } double cm = transf_scale ? this->cov_pars_[0] : 1.; return(std::make_shared<T_mat>(cm * ZZt_)); } /*! * \brief Function that returns the matrix Z * \return A pointer to the matrix Z */ sp_mat_t* GetZ() override { CHECK(this->has_Z_); return(&(this->Z_)); } /*! * \brief Calculate and add covariance matrices from this component for prediction * \param group_data_pred Group data for predictions * \param[out] cross_cov Cross covariance between prediction and observation points * \param[out] uncond_pred_cov Unconditional covariance for prediction points (used only if predict_cov_mat==true) * \param predict_cov_mat If true, all matrices are calculated. If false only Ztilde*Sigma*Z^T required for the conditional mean is calculated * \param dont_add_but_overwrite If true, the matrices are not added but overwritten. If false, the matrices are added to cross_cov and uncond_pred_cov * \param data_duplicates_dropped_for_prediction If true, duplicate groups in group_data (of training data) are dropped for creating prediction matrices (they are added again in re_model_template) * \param rand_coef_data_pred Covariate data for varying coefficients (can be nullptr if this is not a random coefficient) */ void AddPredCovMatrices(const std::vector<re_group_t>& group_data_pred, T_mat& cross_cov, T_mat& uncond_pred_cov, bool predict_cov_mat, bool dont_add_but_overwrite, bool data_duplicates_dropped_for_prediction, double* rand_coef_data_pred) { int num_data_pred = (int)group_data_pred.size(); if (data_duplicates_dropped_for_prediction) { T_mat ZtildeZT(num_data_pred, num_group_); ZtildeZT.setZero(); for (int i = 0; i < num_data_pred; ++i) { if (map_group_label_index_->find(group_data_pred[i]) != map_group_label_index_->end()) {//Group level 'group_data_pred[i]' exists in observed data ZtildeZT.coeffRef(i, (*map_group_label_index_)[group_data_pred[i]]) = 1.; } } if (dont_add_but_overwrite) { cross_cov = this->cov_pars_[0] * ZtildeZT; } else { cross_cov += this->cov_pars_[0] * ZtildeZT; } if (predict_cov_mat) { T_mat ZstarZstarT(num_data_pred, num_data_pred); ZstarZstarT.setZero(); T_mat ZtildeZtildeT(num_data_pred, num_data_pred); ZtildeZtildeT.setZero(); for (int i = 0; i < num_data_pred; ++i) { if (map_group_label_index_->find(group_data_pred[i]) == map_group_label_index_->end()) { ZstarZstarT.coeffRef(i, i) = 1.; } else { ZtildeZtildeT.coeffRef(i, i) = 1.; } } uncond_pred_cov += (this->cov_pars_[0] * ZtildeZtildeT); uncond_pred_cov += (this->cov_pars_[0] * ZstarZstarT); }//end predict_cov_mat }//end data_duplicates_dropped_for_prediction else if (this->has_Z_) { //Note: Ztilde relates existing random effects to predictionsand Zstar relates new / unobserved random effects to predictions sp_mat_t Ztilde(num_data_pred, num_group_); Ztilde.setZero(); for (int i = 0; i < num_data_pred; ++i) { if (map_group_label_index_->find(group_data_pred[i]) != map_group_label_index_->end()) {//Group level 'group_data_pred[i]' exists in observed data if (this->is_rand_coef_) { Ztilde.insert(i, (*map_group_label_index_)[group_data_pred[i]]) = rand_coef_data_pred[i]; } else { Ztilde.insert(i, (*map_group_label_index_)[group_data_pred[i]]) = 1.; } } } if (dont_add_but_overwrite) { CalculateZ1Z2T<T_mat>(Ztilde, this->Z_, cross_cov); cross_cov *= this->cov_pars_[0]; } else { T_mat ZtildeZT; CalculateZ1Z2T<T_mat>(Ztilde, this->Z_, ZtildeZT); cross_cov += (this->cov_pars_[0] * ZtildeZT); } if (predict_cov_mat) { //Count number of new group levels (i.e. group levels not in observed data) int num_group_pred_new = 0; std::map<re_group_t, int> map_group_label_index_pred_new; //Keys: Group labels, values: index number (integer value) for every label for (auto& el : group_data_pred) { if (map_group_label_index_->find(el) == map_group_label_index_->end()) { if (map_group_label_index_pred_new.find(el) == map_group_label_index_pred_new.end()) { map_group_label_index_pred_new.insert({ el, num_group_pred_new }); num_group_pred_new += 1; } } } sp_mat_t Zstar; Zstar.resize(num_data_pred, num_group_pred_new); Zstar.setZero(); for (int i = 0; i < num_data_pred; ++i) { if (map_group_label_index_->find(group_data_pred[i]) == map_group_label_index_->end()) { if (this->is_rand_coef_) { Zstar.insert(i, map_group_label_index_pred_new[group_data_pred[i]]) = rand_coef_data_pred[i]; } else { Zstar.insert(i, map_group_label_index_pred_new[group_data_pred[i]]) = 1.; } } } T_mat ZtildeZtildeT; CalculateZ1Z2T<T_mat>(Ztilde, Ztilde, ZtildeZtildeT); uncond_pred_cov += (this->cov_pars_[0] * ZtildeZtildeT); T_mat ZstarZstarT; CalculateZ1Z2T<T_mat>(Zstar, Zstar, ZstarZstarT); uncond_pred_cov += (this->cov_pars_[0] * ZstarZstarT); }//end predict_cov_mat }//end this->has_Z_ else { Log::REFatal("Need to have either 'Z_' or enable 'data_duplicates_dropped_for_prediction' for calling 'AddPredCovMatrices'"); } } // Ignore this. This is not used for this class (it is only used for the class RECompGP). It is here in order that the base class can have this as a virtual method and no conversion needs to be made in the Vecchia approximation calculation (slightly a hack) void CalcSigmaAndSigmaGrad(const den_mat_t&, den_mat_t&, den_mat_t&, den_mat_t&, bool = false, bool = true, double = 1.) const override { } data_size_t GetNumUniqueREs() const override { return(num_group_); } private: /*! \brief Number of groups */ data_size_t num_group_; /*! \brief Keys: Group labels, values: index number (integer value) for every group level. I.e., maps string labels to numbers */ std::shared_ptr<std::map<re_group_t, int>> map_group_label_index_; /*! \brief Matrix Z*Z^T */ T_mat ZZt_; /*! \brief Indicates whether component has a matrix ZZt_ */ bool has_ZZt_; /*! \brief Constructs the matrix ZZt_ if sparse matrices are used */ template <class T3, typename std::enable_if< std::is_same<sp_mat_t, T3>::value>::type * = nullptr > void ConstructZZt() { if (this->has_Z_) { ZZt_ = this->Z_ * this->Z_.transpose(); } else { ZZt_ = T_mat(num_group_, num_group_); ZZt_.setIdentity(); //Note: If has_Z_==false, ZZt_ is only used for making predictiosn of new independet clusters when only_one_grouped_RE_calculations_on_RE_scale_==true } } /*! \brief Constructs the matrix ZZt_ if dense matrices are used */ template <class T3, typename std::enable_if< std::is_same<den_mat_t, T3>::value>::type * = nullptr > void ConstructZZt() { if (this->has_Z_) { ZZt_ = den_mat_t(this->Z_ * this->Z_.transpose()); } else { ZZt_ = T_mat(num_group_, num_group_); ZZt_.setIdentity(); //Note: If has_Z_==false, ZZt_ is only used for making predictiosn of new independet clusters when only_one_grouped_RE_calculations_on_RE_scale_==true } } /*! * \brief Calculates the matrix Z1*Z2^T if sparse matrices are used * \param Z1 Matrix * \param Z2 Matrix * \param[out] Z1Z2T Matrix Z1*Z2^T */ template <class T3, typename std::enable_if< std::is_same<sp_mat_t, T3>::value>::type * = nullptr > void CalculateZ1Z2T(sp_mat_t& Z1, sp_mat_t& Z2, T3& Z1Z2T) { Z1Z2T = Z1 * Z2.transpose(); } /*! * \brief Calculates the matrix Z1*Z2^T if sparse matrices are used * \param Z1 Matrix * \param Z2 Matrix * \param[out] Z1Z2T Matrix Z1*Z2^T */ template <class T3, typename std::enable_if< std::is_same<den_mat_t, T3>::value>::type * = nullptr > void CalculateZ1Z2T(sp_mat_t& Z1, sp_mat_t& Z2, T3& Z1Z2T) { Z1Z2T = den_mat_t(Z1 * Z2.transpose()); } template<typename T_mat_aux, typename T_chol_aux> friend class REModelTemplate; }; /*! * \brief Class for the Gaussian process components * * Some details: * ... */ template<typename T_mat> class RECompGP : public RECompBase<T_mat> { public: /*! \brief Constructor */ RECompGP(); /*! * \brief Constructor for Gaussian process * \param coords Coordinates (features) for Gaussian process * \param cov_fct Type of covariance function * \param shape Shape parameter of covariance function (=smoothness parameter for Matern covariance, irrelevant for some covariance functions such as the exponential or Gaussian) * \param save_dist_use_Z_for_duplicates If true, distances are calculated and saved here, and an incidendce matrix Z_ is used for duplicate locations. * save_dist_use_Z_for_duplicates = false is used for the Vecchia approximation which saves the required distances in the REModel (REModelTemplate) * \param save_random_effects_indices_of_data_and_no_Z If true a vector random_effects_indices_of_data_, which relates random effects b to samples Zb, is used (the matrix Z_ is then not constructed) * save_random_effects_indices_of_data_and_no_Z = true is currently only used when doing calculations on the random effects scale b and not on the "data scale" Zb for non-Gaussian data * This option can only be selected when save_dist_use_Z_for_duplicates = true */ RECompGP(const den_mat_t& coords, string_t cov_fct, double shape, bool save_dist_use_Z_for_duplicates, bool save_random_effects_indices_of_data_and_no_Z) { if (save_random_effects_indices_of_data_and_no_Z && !save_dist_use_Z_for_duplicates) { Log::REFatal("'save_dist_use_Z_for_duplicates' cannot be 'false' when 'save_random_effects_indices_of_data_and_no_Z' is 'true'"); } this->num_data_ = (data_size_t)coords.rows(); this->is_rand_coef_ = false; this->has_Z_ = false; this->num_cov_par_ = 2; cov_function_ = std::unique_ptr<CovFunction<T_mat>>(new CovFunction<T_mat>(cov_fct, shape)); if (save_dist_use_Z_for_duplicates) { std::vector<int> uniques;//unique points std::vector<int> unique_idx;//used for constructing incidence matrix Z_ if there are duplicates DetermineUniqueDuplicateCoords(coords, this->num_data_, uniques, unique_idx); if ((data_size_t)uniques.size() == this->num_data_) {//no multiple observations at the same locations -> no incidence matrix needed coords_ = coords; } else {//there are multiple observations at the same locations coords_ = coords(uniques, Eigen::all); } num_random_effects_ = (data_size_t)coords_.rows(); if (save_random_effects_indices_of_data_and_no_Z) {// create random_effects_indices_of_data_ this->random_effects_indices_of_data_ = std::vector<data_size_t>(this->num_data_); #pragma omp for schedule(static) for (int i = 0; i < this->num_data_; ++i) { this->random_effects_indices_of_data_[i] = unique_idx[i]; } this->has_Z_ = false; } else if (num_random_effects_ != this->num_data_) {// create incidence matrix Z_ this->Z_.resize(this->num_data_, num_random_effects_); this->Z_.setZero(); for (int i = 0; i < this->num_data_; ++i) { this->Z_.insert(i, unique_idx[i]) = 1.; } this->has_Z_ = true; } //Calculate distances den_mat_t dist; CalculateDistances(coords_, dist); dist_ = std::make_shared<den_mat_t>(dist); dist_saved_ = true; }//end save_dist_use_Z_for_duplicates else {//this option is used for the Vecchia approximation coords_ = coords; dist_saved_ = false; num_random_effects_ = (data_size_t)coords_.rows(); } coord_saved_ = true; } /*! * \brief Constructor for random coefficient Gaussian processes * \param dist Pointer to distance matrix of corresponding base intercept GP * \param base_effect_has_Z Indicate whether the corresponding base GP has an incidence matrix Z or not * \param Z Pointer to incidence matrix Z of corresponding base intercept GP * \param rand_coef_data Covariate data for random coefficient * \param cov_fct Type of covariance function * \param shape Shape parameter of covariance function (=smoothness parameter for Matern covariance, irrelevant for some covariance functions such as the exponential or Gaussian) */ RECompGP(std::shared_ptr<den_mat_t> dist, bool base_effect_has_Z, sp_mat_t* Z, const std::vector<double>& rand_coef_data, string_t cov_fct, double shape) { this->num_data_ = (data_size_t)rand_coef_data.size(); dist_ = dist; dist_saved_ = true; this->rand_coef_data_ = rand_coef_data; this->is_rand_coef_ = true; this->has_Z_ = true; this->num_cov_par_ = 2; cov_function_ = std::unique_ptr<CovFunction<T_mat>>(new CovFunction<T_mat>(cov_fct, shape)); sp_mat_t coef_W(this->num_data_, this->num_data_); for (int i = 0; i < this->num_data_; ++i) { coef_W.insert(i, i) = this->rand_coef_data_[i]; } if (base_effect_has_Z) {//"Base" intercept GP has a (non-identity) incidence matrix (i.e., there are multiple observations at the same locations) this->Z_ = coef_W * *Z; } else { this->Z_ = coef_W; } coord_saved_ = false; num_random_effects_ = (data_size_t)this->Z_.cols(); } /*! * \brief Constructor for random coefficient Gaussian process when multiple locations are not modelled using an incidence matrix. * This is used for the Vecchia approximation. * \param rand_coef_data Covariate data for random coefficient * \param cov_fct Type of covariance function * \param shape Shape parameter of covariance function (=smoothness parameter for Matern covariance, irrelevant for some covariance functions such as the exponential or Gaussian) */ RECompGP(const std::vector<double>& rand_coef_data, string_t cov_fct, double shape) { this->rand_coef_data_ = rand_coef_data; this->is_rand_coef_ = true; this->num_data_ = (data_size_t)rand_coef_data.size(); this->has_Z_ = true; this->num_cov_par_ = 2; cov_function_ = std::unique_ptr<CovFunction<T_mat>>(new CovFunction<T_mat>(cov_fct, shape)); dist_saved_ = false; coord_saved_ = false; this->Z_ = sp_mat_t(this->num_data_, this->num_data_); for (int i = 0; i < this->num_data_; ++i) { this->Z_.insert(i, i) = this->rand_coef_data_[i]; } num_random_effects_ = this->num_data_; } /*! \brief Destructor */ ~RECompGP() { } /*! * \brief Create and adds the matrix Z_ * Note: this is currently only used when changing the likelihood in the re_model */ void AddZ() override { CHECK(!this->is_rand_coef_);//not intended for random coefficient models if (!this->has_Z_) { if (num_random_effects_ != this->num_data_) {// create incidence matrix Z_ CHECK((data_size_t)(this->random_effects_indices_of_data_.size()) == this->num_data_); this->Z_.resize(this->num_data_, num_random_effects_); this->Z_.setZero(); for (int i = 0; i < this->num_data_; ++i) { this->Z_.insert(i, this->random_effects_indices_of_data_[i]) = 1.; } this->has_Z_ = true; } } } /*! * \brief Drop the matrix Z_ * Note: this is currently only used when changing the likelihood in the re_model */ void DropZ() override { CHECK(!this->is_rand_coef_);//not intended for random coefficient models if (this->has_Z_) { this->random_effects_indices_of_data_ = std::vector<data_size_t>(this->num_data_); for (int k = 0; k < this->Z_.outerSize(); ++k) { for (sp_mat_t::InnerIterator it(this->Z_, k); it; ++it) { this->random_effects_indices_of_data_[(int)it.row()] = (data_size_t)it.col(); } } this->has_Z_ = false; this->Z_.resize(0, 0); } } /*! * \brief Function that sets the covariance parameters * \param pars Vector of length 2 with covariance parameters (variance and inverse range) */ void SetCovPars(const vec_t& pars) override { CHECK((int)pars.size() == 2); this->cov_pars_ = pars; } /*! * \brief Transform the covariance parameters * \param sigma2 Marginal variance * \param pars Vector with covariance parameters on orignal scale * \param[out] pars_trans Transformed covariance parameters */ void TransformCovPars(const double sigma2, const vec_t& pars, vec_t& pars_trans) override { cov_function_->TransformCovPars(sigma2, pars, pars_trans); } /*! * \brief Function that sets the covariance parameters * \param sigma2 Marginal variance * \param pars Vector with covariance parameters * \param[out] pars_orig Back-transformed, original covariance parameters */ void TransformBackCovPars(const double sigma2, const vec_t& pars, vec_t& pars_orig) override { cov_function_->TransformBackCovPars(sigma2, pars, pars_orig); } /*! * \brief Find "reasonable" default values for the intial values of the covariance parameters (on transformed scale) * \param sigma2 Marginal variance * \param[out] pars Vector with covariance parameters */ void FindInitCovPar(vec_t& pars) const override { if (!dist_saved_ && !coord_saved_) { Log::REFatal("Cannot determine initial covariance parameters if neither distances nor coordinates are given"); } pars[0] = 1; double mean_dist = 0; if (!dist_saved_) {//Calculate distances (of a Bootstrap sample) in case they have not been calculated (for the Vecchia approximation) int num_coord = (int)coords_.rows(); den_mat_t dist; int num_data = (num_coord > 1000) ? 1000 : num_coord;//limit to maximally 1000 to save computational time if (num_data < num_coord) { std::mt19937 gen(0); //Standard mersenne_twister_engine seeded with 0 std::uniform_int_distribution<> dis(0, num_coord - 1); std::vector<int> sample_ind(num_data); for (int i = 0; i < num_data; ++i) { sample_ind[i] = dis(gen); } CalculateDistances(coords_(sample_ind, Eigen::all), dist); } else { CalculateDistances(coords_, dist); } for (int i = 0; i < (num_data - 1); ++i) { for (int j = i + 1; j < num_data; ++j) { mean_dist += dist(i, j); } } mean_dist /= (num_data * (num_data - 1) / 2.); } else { int num_coord = (int)(*dist_).rows(); for (int i = 0; i < (num_coord - 1); ++i) { for (int j = i + 1; j < num_coord; ++j) { mean_dist += (*dist_)(i, j); } } mean_dist /= (num_coord * (num_coord - 1) / 2.); } //Set the range parameter such that the correlation is down to 0.05 at the mean distance if (cov_function_->cov_fct_type_ == "exponential" || cov_function_->cov_fct_type_ == "matern") {//TODO: find better intial values for matern covariance for shape = 1.5 and shape = 2.5 pars[1] = 3. / mean_dist;//pars[1] = 1/range } else if (cov_function_->cov_fct_type_ == "gaussian") { pars[1] = 3. / std::pow(mean_dist, 2.);//pars[1] = 1/range^2 } else if (cov_function_->cov_fct_type_ == "powered_exponential") { pars[1] = 3. / std::pow(mean_dist, cov_function_->shape_);//pars[1] = 1/range^shape } else { Log::REFatal("Finding initial values for covariance paramters for covariance of type '%s' is not supported.", cov_function_->cov_fct_type_.c_str()); } } /*! * \brief Calculate covariance matrix at unique locations */ void CalcSigma() override { if (this->cov_pars_.size() == 0) { Log::REFatal("Covariance parameters are not specified. Call 'SetCovPars' first."); } (*cov_function_).template GetCovMat<T_mat>(*dist_, this->cov_pars_, sigma_); //cov_function_->GetCovMat<T_mat>(*dist_, this->cov_pars_, sigma_);//does not work for mingw compiler, thus use code above sigma_defined_ = true; } /*! * \brief Calculate covariance matrix * \return Covariance matrix Z*Sigma*Z^T of this component */ std::shared_ptr<T_mat> GetZSigmaZt() const override { if (!sigma_defined_) { Log::REFatal("Sigma has not been calculated"); } if (this->is_rand_coef_ || this->has_Z_) { return(std::make_shared<T_mat>(this->Z_ * sigma_ * this->Z_.transpose())); } else { return(std::make_shared<T_mat>(sigma_)); } } /*! * \brief Calculate covariance matrix and gradients with respect to covariance parameters (used for Vecchia approx.) * \param dist Distance matrix * \param[out] cov_mat Covariance matrix Z*Sigma*Z^T * \param[out] cov_grad_1 Gradient of covariance matrix with respect to marginal variance parameter * \param[out] cov_grad_2 Gradient of covariance matrix with respect to range parameter * \param calc_gradient If true, gradients are also calculated, otherwise not * \param transf_scale If true, the derivative are calculated on the transformed scale otherwise on the original scale. Default = true * \param nugget_var Nugget effect variance parameter sigma^2 (used only if transf_scale = false to transform back) */ void CalcSigmaAndSigmaGrad(const den_mat_t& dist, den_mat_t& cov_mat, den_mat_t& cov_grad_1, den_mat_t& cov_grad_2, bool calc_gradient = false, bool transf_scale = true, double nugget_var = 1.) const override { if (this->cov_pars_.size() == 0) { Log::REFatal("Covariance parameters are not specified. Call 'SetCovPars' first."); } (*cov_function_).template GetCovMat<den_mat_t>(dist, this->cov_pars_, cov_mat); if (calc_gradient) { //gradient wrt to variance parameter cov_grad_1 = cov_mat; if (!transf_scale) { cov_grad_1 /= this->cov_pars_[0]; } //gradient wrt to range parameter (*cov_function_).template GetCovMatGradRange<den_mat_t>(dist, cov_mat, this->cov_pars_, cov_grad_2, transf_scale, nugget_var); } if (!transf_scale) { cov_mat *= nugget_var;//transform back to original scale } } /*! * \brief Calculate derivatives of covariance matrix with respect to the parameters * \param ind_par Index for parameter (0=variance, 1=inverse range) * \param transf_scale If true, the derivative is taken on the transformed scale otherwise on the original scale. Default = true * \param nugget_var Nugget effect variance parameter sigma^2 (used only if transf_scale = false to transform back) * \return Derivative of covariance matrix Z*Sigma*Z^T with respect to the parameter number ind_par */ std::shared_ptr<T_mat> GetZSigmaZtGrad(int ind_par, bool transf_scale = true, double nugget_var = 1.) const override { if (!sigma_defined_) { Log::REFatal("Sigma has not been calculated"); } if (ind_par != 0 && ind_par != 1) { Log::REFatal("No covariance parameter for index number %d", ind_par); } if (ind_par == 0) {//variance if (transf_scale) { return(GetZSigmaZt()); } else { double correct = 1. / this->cov_pars_[0];//divide sigma_ by cov_pars_[0] if (this->is_rand_coef_ || this->has_Z_) { return(std::make_shared<T_mat>(correct * this->Z_ * sigma_ * this->Z_.transpose())); } else { return(std::make_shared<T_mat>(correct * sigma_)); } } } else {//inverse range (ind_par == 1) T_mat Z_sigma_grad_Zt; if (this->has_Z_) { T_mat sigma_grad; (*cov_function_).template GetCovMatGradRange<T_mat>(*dist_, sigma_, this->cov_pars_, sigma_grad, transf_scale, nugget_var); Z_sigma_grad_Zt = this->Z_ * sigma_grad * this->Z_.transpose(); } else { (*cov_function_).template GetCovMatGradRange<T_mat>(*dist_, sigma_, this->cov_pars_, Z_sigma_grad_Zt, transf_scale, nugget_var); } return(std::make_shared<T_mat>(Z_sigma_grad_Zt)); } } /*! * \brief Function that returns the matrix Z * \return A pointer to the matrix Z */ sp_mat_t* GetZ() override { if (!this->has_Z_) { Log::REFatal("Gaussian process has no matrix Z"); } return(&(this->Z_)); } /*! * \brief Calculate and add covariance matrices from this component for prediction * \param coords Coordinates for observed data * \param coords_pred Coordinates for predictions * \param[out] cross_cov Cross covariance between prediction and observation points * \param[out] uncond_pred_cov Unconditional covariance for prediction points (used only if predict_cov_mat==true) * \param predict_cov_mat If true, all matrices are calculated. If false only Ztilde*Sigma*Z^T required for the conditional mean is calculated * \param dont_add_but_overwrite If true, the matrices are not added but overwritten * \param rand_coef_data_pred Covariate data for varying coefficients (can be nullptr if this is not a random coefficient) */ void AddPredCovMatrices(const den_mat_t& coords, const den_mat_t& coords_pred, T_mat& cross_cov, T_mat& uncond_pred_cov, bool predict_cov_mat, bool dont_add_but_overwrite, double* rand_coef_data_pred) { int num_data_pred = (int)coords_pred.rows(); std::vector<int> uniques_pred;//unique points std::vector<int> unique_idx_pred;//used for constructing incidence matrix Z_ if there are duplicates DetermineUniqueDuplicateCoords(coords_pred, num_data_pred, uniques_pred, unique_idx_pred); bool has_duplicates = (int)uniques_pred.size() != num_data_pred; bool has_Zstar = has_duplicates || this->is_rand_coef_; sp_mat_t Zstar; den_mat_t coords_pred_unique; //Create matrix Zstar if (has_Zstar) { // Note: Ztilde relates existing random effects to predictions and Zstar relates new / unobserved random effects to predictions Zstar = sp_mat_t(num_data_pred, uniques_pred.size()); Zstar.setZero(); } if (has_duplicates) {//Only keep unique coordinates if there are multiple observations with the same coordinates coords_pred_unique = coords_pred(uniques_pred, Eigen::all); } if (has_Zstar) { for (int i = 0; i < num_data_pred; ++i) { if (this->is_rand_coef_) { Zstar.insert(i, unique_idx_pred[i]) = rand_coef_data_pred[i]; } else { Zstar.insert(i, unique_idx_pred[i]) = 1.; } } } //Calculate cross distances between "existing" and "new" points den_mat_t cross_dist((int)uniques_pred.size(), coords.rows()); cross_dist.setZero(); for (int i = 0; i < coords.rows(); ++i) { for (int j = 0; j < (int)uniques_pred.size(); ++j) { if (has_duplicates) { cross_dist(j, i) = (coords.row(i) - coords_pred_unique.row(j)).lpNorm<2>(); } else { cross_dist(j, i) = (coords.row(i) - coords_pred.row(j)).lpNorm<2>(); } } } T_mat ZstarSigmatildeTZT; if (has_Zstar || this->has_Z_) { T_mat Sigmatilde; (*cov_function_).template GetCovMat<T_mat>(cross_dist, this->cov_pars_, Sigmatilde); if (has_Zstar && this->has_Z_) { ZstarSigmatildeTZT = Zstar * Sigmatilde * this->Z_.transpose(); } else if (has_Zstar && !(this->has_Z_)){ ZstarSigmatildeTZT = Zstar * Sigmatilde; } else if (!has_Zstar && this->has_Z_) { ZstarSigmatildeTZT = Sigmatilde * this->Z_.transpose(); } }//end has_Zstar || this->has_Z_ else { //no Zstar and no Z_ (*cov_function_).template GetCovMat<T_mat>(cross_dist, this->cov_pars_, ZstarSigmatildeTZT); } if (dont_add_but_overwrite) { cross_cov = ZstarSigmatildeTZT; } else { cross_cov += ZstarSigmatildeTZT; } if (predict_cov_mat) { den_mat_t dist; CalculateDistances(coords_pred, dist); T_mat ZstarSigmastarZstarT; if (has_Zstar) { T_mat Sigmastar; (*cov_function_).template GetCovMat<T_mat>(dist, this->cov_pars_, Sigmastar); ZstarSigmastarZstarT = Zstar * Sigmastar * Zstar.transpose(); } else { (*cov_function_).template GetCovMat<T_mat>(dist, this->cov_pars_, ZstarSigmastarZstarT); } uncond_pred_cov += ZstarSigmastarZstarT; } } data_size_t GetNumUniqueREs() const override { return(num_random_effects_); } private: /*! \brief Coordinates (=features) */ den_mat_t coords_; /*! \brief Distance matrix (between unique coordinates in coords_) */ std::shared_ptr<den_mat_t> dist_; /*! \brief If true, the distancess among all observations are calculated and saved here (false for Vecchia approximation) */ bool dist_saved_ = true; /*! \brief If true, the coordinates are saved (false for random coefficients GPs) */ bool coord_saved_ = true; /*! \brief Covariance function */ std::unique_ptr<CovFunction<T_mat>> cov_function_; /*! \brief Covariance matrix (for a certain choice of covariance paramters). This is saved for re-use at two locations in the code: GetZSigmaZt and GetZSigmaZtGrad) */ T_mat sigma_; /*! \brief Indicates whether sigma_ has been defined or not */ bool sigma_defined_ = false; /*! \brief Number of random effects (usually, number of unique random effects except for the Vecchia approximation where unique locations are not separately modelled) */ data_size_t num_random_effects_; template<typename T_mat_aux, typename T_chol_aux> friend class REModelTemplate; }; } // namespace GPBoost #endif // GPB_RE_COMP_H_
covariance.c
/** * covariance.c: This file was adapted from PolyBench/GPU 1.0 test * suite to run on GPU with OpenMP 4.0 pragmas and OpenCL driver. * * http://www.cse.ohio-state.edu/~pouchet/software/polybench/GPU * * Contacts: Marcio M Pereira <mpereira@ic.unicamp.br> * Rafael Cardoso F Sousa <rafael.cardoso@students.ic.unicamp.br> * Luís Felipe Mattos <ra107822@students.ic.unicamp.br> */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <assert.h> #include <unistd.h> #include <sys/time.h> #include <omp.h> #include "../../common/polybenchUtilFuncts.h" //define the error threshold for the results "not matching" #define PERCENT_DIFF_ERROR_THRESHOLD 2.0 #define GPU 1 /* Problem size */ #define M 2048 #define N 2048 #define sqrt_of_array_cell(x,j) sqrt(x[j]) #define FLOAT_N 3214212.01 #define EPS 0.005 /* Can switch DATA_TYPE between float and double */ typedef float DATA_TYPE; void init_arrays(DATA_TYPE* data) { int i, j; for (i = 1; i < (M+1); i++) { for (j = 1; j < (N+1); j++) { data[i*(N+1) + j] = ((DATA_TYPE) i*j) / M; } } } void compareResults(DATA_TYPE* symmat, DATA_TYPE* symmat_outputFromGpu) { int i,j,fail; fail = 0; for (i=1; i < (M+1); i++) { for (j=1; j < (N+1); j++) { if (percentDiff(symmat[i*(N+1) + j], symmat_outputFromGpu[i*(N+1) + j]) > PERCENT_DIFF_ERROR_THRESHOLD) { fail++; } } } printf(">>\n Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f%s: %d\n", PERCENT_DIFF_ERROR_THRESHOLD, "%", fail); } void covariance(DATA_TYPE* data, DATA_TYPE* symmat, DATA_TYPE* mean) { int i, j, j1,j2; /* Determine mean of column vectors of input data matrix */ for (j = 1; j < (M+1); j++) { mean[j] = 0.0; for (i = 1; i < (N+1); i++) { mean[j] += data[i*(M+1) + j]; } mean[j] /= FLOAT_N; } /* Center the column vectors. */ for (i = 1; i < (N+1); i++) { for (j = 1; j < (M+1); j++) { data[i*(M+1) + j] -= mean[j]; } } /* Calculate the m * m covariance matrix. */ for (j1 = 1; j1 < (M+1); j1++) { for (j2 = j1; j2 < (M+1); j2++) { symmat[j1*(M+1) + j2] = 0.0; for (i = 1; i < N+1; i++) { symmat[j1*(M+1) + j2] += data[i*(M+1) + j1] * data[i*(M+1) + j2]; } symmat[j2*(M+1) + j1] = symmat[j1*(M+1) + j2]; } } } void covariance_OMP(DATA_TYPE* data, DATA_TYPE* symmat, DATA_TYPE* mean) { int i, j, j1,j2; /* Determine mean of column vectors of input data matrix */ #pragma omp target device (GPU) map(to: data[:(M+1)*(N+1)]) map(from: mean[:(M+1)]) #pragma omp parallel for for (j = 1; j < (M+1); j++) { mean[j] = 0.0; for (i = 1; i < (N+1); i++) { mean[j] += data[i*(M+1) + j]; } mean[j] /= FLOAT_N; } /* Center the column vectors. */ #pragma omp target map(to: mean[:(M+1)]) map(tofrom: data[:(M+1)*(N+1)]) #pragma omp parallel for collapse(2) for (i = 1; i < (N+1); i++) { for (j = 1; j < (M+1); j++) { data[i*(M+1) + j] -= mean[j]; } } /* Calculate the m * m covariance matrix. */ #pragma omp target map(to: data[:(M+1)*(M+1)]) map(from: symmat[:(M+1)*(N+1)]) #pragma omp parallel for schedule(dynamic,8) for (j1 = 1; j1 < (M+1); j1++) { for (j2 = j1; j2 < (M+1); j2++) { symmat[j1*(M+1) + j2] = 0.0; for (i = 1; i < N+1; i++) { symmat[j1*(M+1) + j2] += data[i*(M+1) + j1] * data[i*(M+1) + j2]; } symmat[j2*(M+1) + j1] = symmat[j1*(M+1) + j2]; } } } int main() { double t_start, t_end; DATA_TYPE* data; DATA_TYPE* symmat; DATA_TYPE* mean; DATA_TYPE* symmat_outputFromGpu; data = (DATA_TYPE*)malloc((M+1)*(N+1)*sizeof(DATA_TYPE)); symmat = (DATA_TYPE*)malloc((M+1)*(M+1)*sizeof(DATA_TYPE)); mean = (DATA_TYPE*)malloc((M+1)*sizeof(DATA_TYPE)); symmat_outputFromGpu = (DATA_TYPE*)malloc((M+1)*(M+1)*sizeof(DATA_TYPE)); fprintf(stdout, "<< Covariance Computation >>\n"); fprintf(stdout, "<< Size of data Matrix: 2048 * 2048 >>\n\n"); fprintf(stdout, "<< Determine mean of column vectors of input data matrix: >>\n"); fprintf(stdout, " for (j = 1; j <= 2048; j++) {\n"); fprintf(stdout, " mean[j] = 0.0; \n"); fprintf(stdout, " for (i = 1; i <= 2048; i++) \n"); fprintf(stdout, " mean[j] += data[i][j]; \n"); fprintf(stdout, " mean[j] /= 3214212.01; \n"); fprintf(stdout, " } \n"); fprintf(stdout, "<< Center the column vectors: >> \n"); fprintf(stdout, " for (i = 1; i <= 2048; ++i) \n"); fprintf(stdout, " for (j = 1; j <= 2048; ++j) \n"); fprintf(stdout, " data[i][j] -= mean[j];\n"); fprintf(stdout, "<< Calculate de 2048*2048 covariance matrix: >>\n"); fprintf(stdout, " for (j1 = 1; j1 <= 2048; j1++) \n"); fprintf(stdout, " for (j2 = j1; j2 <= 2048; j2++) {\n"); fprintf(stdout, " symmat[j1][j2] = 0.0; \n"); fprintf(stdout, " for (i = 1; i <= 2048; i++) \n"); fprintf(stdout, " symmat[j1][j2] += data[i][j1] * data[i][j2];\n"); fprintf(stdout, " symmat[j2][j1] = symmat[j1][j2];\n"); fprintf(stdout, " } \n\n"); fprintf(stdout, "<< Initializing data ... "); init_arrays(data); fprintf(stdout, ">>\n<< Start covariance computation on GPU... "); t_start = rtclock(); covariance_OMP(data, symmat_outputFromGpu, mean); t_end = rtclock(); fprintf(stdout, ">>\n GPU Runtime: %0.6lfs\n", t_end - t_start); init_arrays(data); fprintf(stdout, "\n<< Start covariance computation on CPU... "); t_start = rtclock(); covariance(data, symmat, mean); t_end = rtclock(); fprintf(stdout, ">>\n CPU Runtime: %0.6lfs\n", t_end - t_start); fprintf(stdout, "<< Comparing Results..."); compareResults(symmat, symmat_outputFromGpu); free(data); free(symmat); free(mean); free(symmat_outputFromGpu); return 0; }
GB_unaryop__ainv_int64_int8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__ainv_int64_int8 // op(A') function: GB_tran__ainv_int64_int8 // C type: int64_t // A type: int8_t // cast: int64_t cij = (int64_t) aij // unaryop: cij = -aij #define GB_ATYPE \ int8_t #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CASTING(z, aij) \ int64_t z = (int64_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_INT64 || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_int64_int8 ( int64_t *Cx, // Cx and Ax may be aliased int8_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__ainv_int64_int8 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
symmetrize.h
#ifndef __COOP_NAIVE_SYMMETRIZE_H__ #define __COOP_NAIVE_SYMMETRIZE_H__ static inline void symmetrize_naive(const int n, double *restrict x) { #pragma omp parallel for default(none) shared(x) schedule(dynamic, 1) if(n>OMP_MIN_SIZE) for (int j=0; j<n; j++) { const int nj = n*j; for (int i=j+1; i<n; i++) x[j + n*i] = x[i + nj]; } } #endif
rnn_impl.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2015 by Contributors * \file rnn_impl.h * \brief * \author Shu Zhang */ #ifndef MXNET_OPERATOR_RNN_IMPL_H_ #define MXNET_OPERATOR_RNN_IMPL_H_ #include <dmlc/logging.h> #include <dmlc/parameter.h> #include <mxnet/operator.h> #include <algorithm> #include <map> #include <vector> #include <string> #include <utility> #include "./math.h" #include "./math_functions-inl.h" #include "./operator_common.h" #include "./mshadow_op.h" #include "./linalg.h" namespace mxnet { namespace op { template<typename DType> inline DType sigmoid(DType x) { return 1.0f / (1.0f + exp(-x)); } template<typename DType> inline DType relu(DType x) { return x > 0.0f ? static_cast<float>(x) : 0.0f; } template<typename DType> void LstmForwardTrainingSingleLayer(DType* ws, DType* rs, bool state_outputs, bool bid, const index_t T, const index_t N, const index_t I, const int H, const Tensor<cpu, 2, DType> &x, const Tensor<cpu, 2, DType> &hx, const Tensor<cpu, 2, DType> &cx, const Tensor<cpu, 3, DType> &y, DType* w_ptr, DType* b_ptr, DType* hy_ptr, DType* cy_ptr) { using namespace mshadow; const Tensor<cpu, 2, DType> wx(w_ptr, Shape2(H * 4, I)); const Tensor<cpu, 2, DType> wh(w_ptr + I * H * 4, Shape2(H * 4, H)); const Tensor<cpu, 2, DType> bx(b_ptr, Shape2(4, H)); const Tensor<cpu, 2, DType> bh(b_ptr + H * 4, Shape2(4, H)); const Tensor<cpu, 2, DType> yx_flat(ws, Shape2(T * N, 4 * H)); const Tensor<cpu, 2, DType> yh_flat(ws + T * N * H * 4, Shape2(N, 4 * H)); const Tensor<cpu, 4, DType> yx(yx_flat.dptr_, Shape4(T, N, 4, H)); const Tensor<cpu, 3, DType> yh(yh_flat.dptr_, Shape3(N, 4, H)); Tensor<cpu, 2, DType> h(yh_flat.dptr_ + N * H * 4, Shape2(N, H)); DType *c_ptr = bid ? rs + T * N * H * 7 : rs; Tensor<cpu, 3, DType> c(c_ptr, Shape3(T, N, H)); Tensor<cpu, 4, DType> ifgo(c_ptr + T * N * H, Shape4(T, N, H, 4)); const int offset = bid ? H : 0; const DType alpha = 1.0; const DType beta = 0.0; const index_t cell_size = N * H; linalg_gemm(x, wx, yx_flat, alpha, beta, false, true); const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); for (index_t i = 0; i < T; ++i) { index_t t = bid ? T - 1 - i : i; linalg_gemm(i ? h : hx, wh, yh_flat, alpha, beta, false, true); #pragma omp parallel for num_threads(omp_threads) for (index_t jk = 0; jk < cell_size; ++jk) { index_t j = jk / H; index_t k = jk % H; DType it = sigmoid<DType>(yx[t][j][0][k] + yh[j][0][k] + bx[0][k] + bh[0][k]); DType ft = sigmoid<DType>(yx[t][j][1][k] + yh[j][1][k] + bx[1][k] + bh[1][k]); DType gt = tanh(yx[t][j][2][k] + yh[j][2][k] + bx[2][k] + bh[2][k]); DType ot = sigmoid<DType>(yx[t][j][3][k] + yh[j][3][k] + bx[3][k] + bh[3][k]); DType ct = (i ? c[i-1][j][k] : cx[j][k]) * ft + it * gt; DType ht = ot * tanh(ct); h[j][k] = ht; // reserve y[t][j][k + offset] = ht; c[i][j][k] = ct; ifgo[i][j][k][0] = it; ifgo[i][j][k][1] = ft; ifgo[i][j][k][2] = gt; ifgo[i][j][k][3] = ot; if (i == T - 1 && state_outputs) { hy_ptr[jk] = ht; cy_ptr[jk] = ct; } } } } template <typename DType> void LstmForwardTraining(DType* ws, DType* rs, bool state_outputs, const int L, const int D, const index_t T, const index_t N, const index_t I, const int H, DType* x_ptr, DType* hx_ptr, DType* cx_ptr, DType* w_ptr, DType* b_ptr, DType* y_ptr, DType* hy_ptr, DType* cy_ptr, const float dropout) { DType* dropout_random = rs; DType* rs2 = dropout_random + (L - 1) * D * T * N * H; const int total_layers = D * L; Tensor<cpu, 3, DType> hx(hx_ptr, Shape3(total_layers, N, H)); Tensor<cpu, 3, DType> cx(cx_ptr, Shape3(total_layers, N, H)); const index_t b_size = 2 * H * 4; const index_t r_size = D * T * N * H * 6; const index_t y_offset = T * N * H * 5; const index_t cell_size = N * H; unsigned int seed_ = 17 + rand() % 4096; // NOLINT(runtime/threadsafe_fn) int idx = 0; // state & cell state's idx; const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); for (int i = 0; i < L; ++i) { const index_t input_size = i ? H * D : I; const index_t w_size = (input_size + H) * H * 4; Tensor<cpu, 2, DType> x(x_ptr, Shape2(T * N, input_size)); Tensor<cpu, 3, DType> y(rs2 + y_offset, Shape3(T, N, H * D)); LstmForwardTrainingSingleLayer<DType>(ws, rs2, state_outputs, false, T, N, input_size, H, x, hx[idx], cx[idx], y, w_ptr, b_ptr, hy_ptr, cy_ptr); if (D == 2) { w_ptr += w_size; b_ptr += b_size; ++idx; if (state_outputs) { hy_ptr += cell_size; cy_ptr += cell_size; } LstmForwardTrainingSingleLayer<DType>(ws, rs2, state_outputs, true, T, N, input_size, H, x, hx[idx], cx[idx], y, w_ptr, b_ptr, hy_ptr, cy_ptr); } if (i != L - 1) { w_ptr += w_size; b_ptr += b_size; if (dropout > 0.0f) { #pragma omp parallel for num_threads(omp_threads) for (index_t j = 0; j < T * N * H * D; j++) { int rand_data = rand_r(&seed_); if (static_cast<float>(rand_data % 1000) < static_cast<float>(1000 * dropout)) { dropout_random[i * T * N * H * D + j] = 0; y.dptr_[j] = 0; } else { dropout_random[i * T * N * H * D + j] = 1.0f - dropout; y.dptr_[j] = y.dptr_[j] / (1.0f - dropout); } } } x_ptr = y.dptr_; rs2 += r_size; ++idx; if (state_outputs) { hy_ptr += cell_size; cy_ptr += cell_size; } } } #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < T * N * H * D; ++i) { y_ptr[i] = (rs2 + y_offset)[i]; } } template<typename DType> void LstmForwardInferenceSingleLayer(DType* ws, bool state_outputs, bool bid, const index_t T, const index_t N, const index_t I, const int H, const int P, const Tensor<cpu, 2, DType> &x, const Tensor<cpu, 2, DType> &hx, const Tensor<cpu, 2, DType> &cx, const Tensor<cpu, 3, DType> &y, DType* w_ptr, DType* b_ptr, DType* hy_ptr, DType* cy_ptr) { using namespace mshadow; const Tensor<cpu, 2, DType> wx(w_ptr, Shape2(H * 4, I)); const Tensor<cpu, 2, DType> wh(w_ptr + I * H * 4, Shape2(H * 4, (P ? P : H))); Tensor<cpu, 2, DType> whr(w_ptr, Shape2(1, 1)); if (P > 0) whr = Tensor<cpu, 2, DType>(wh.dptr_ + P * 4 * H, Shape2(P, H)); const Tensor<cpu, 2, DType> bx(b_ptr, Shape2(4, H)); const Tensor<cpu, 2, DType> bh(b_ptr + H * 4, Shape2(4, H)); Tensor<cpu, 2, DType> yx_flat(ws, Shape2(T * N, H * 4)); Tensor<cpu, 2, DType> yh_flat(ws + T * N * H * 4, Shape2(N, H * 4)); const Tensor<cpu, 4, DType> yx(yx_flat.dptr_, Shape4(T, N, 4, H)); const Tensor<cpu, 3, DType> yh(yh_flat.dptr_, Shape3(N, 4, H)); Tensor<cpu, 2, DType> h(yh_flat.dptr_ + N * H * 4, Shape2(N, H)); Tensor<cpu, 2, DType> c(h.dptr_ + N * H, Shape2(N, H)); Tensor<cpu, 2, DType> r(hy_ptr, Shape2(1, 1)); if (P > 0) r = Tensor<cpu, 2, DType>(hy_ptr, Shape2(N, P)); const int offset = bid ? H : 0; const int proj_offset = bid ? P : 0; const DType alpha = 1.0; const DType beta = 0.0; const index_t cell_size = N * H; linalg_gemm(x, wx, yx_flat, alpha, beta, false, true); const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); for (index_t i = 0; i < T; ++i) { index_t t = bid ? T - 1 - i : i; if (P > 0) { linalg_gemm(i ? r : hx, wh, yh_flat, alpha, beta, false, true); } else { linalg_gemm(i ? h : hx, wh, yh_flat, alpha, beta, false, true); } #pragma omp parallel for num_threads(omp_threads) for (index_t jk = 0; jk < cell_size; ++jk) { int j = jk / H; int k = jk % H; DType it = sigmoid<DType>(yx[t][j][0][k] + yh[j][0][k] + bx[0][k] + bh[0][k]); DType ft = sigmoid<DType>(yx[t][j][1][k] + yh[j][1][k] + bx[1][k] + bh[1][k]); DType gt = tanh(yx[t][j][2][k] + yh[j][2][k] + bx[2][k] + bh[2][k]); DType ot = sigmoid<DType>(yx[t][j][3][k] + yh[j][3][k] + bx[3][k] + bh[3][k]); DType ct = (i ? c[j][k] : cx[j][k]) * ft + it * gt; DType ht = ot * tanh(ct); if (P == 0) y[t][j][k + offset] = ht; if (i == T - 1 && state_outputs) { if (P == 0) hy_ptr[jk] = ht; cy_ptr[jk] = ct; } else { c[j][k] = ct; } h[j][k] = ht; } if (P > 0) { linalg_gemm(h, whr, r, alpha, beta, false, true); #pragma GCC diagnostic push #if __GNUC__ >= 8 #pragma GCC diagnostic ignored "-Wclass-memaccess" #endif #pragma omp parallel for num_threads(omp_threads) for (int j = 0; j < N; ++j) { std::memcpy(y[t][j].dptr_ + proj_offset, r[j].dptr_, P * sizeof(DType)); } #pragma GCC diagnostic pop } } } template <typename DType> void LstmForwardInference(DType* ws, bool state_outputs, const int L, const int D, const index_t T, const index_t N, const index_t I, const int H, const int P, DType* x_ptr, DType* hx_ptr, DType* cx_ptr, DType* w_ptr, DType* b_ptr, DType* y_ptr, DType* hy_ptr, DType* cy_ptr) { const int total_layers = D * L; Tensor<cpu, 3, DType> hx(hx_ptr, Shape3(total_layers, N, P ? P : H)); Tensor<cpu, 3, DType> cx(cx_ptr, Shape3(total_layers, N, H)); const index_t b_size = 2 * H * 4; const index_t cell_size = N * H; const index_t projection_size = (P ? P : H) * N; DType* y_tmp_ptr = ws + (T + 1) * cell_size * 4 + cell_size * 2; DType* y_cur_ptr = y_ptr; int idx = 0; // state & cell state's idx; bool flag = L % 2 ? false : true; for (int i = 0; i < L; ++i) { const index_t input_size = i ? (P ? P : H) * D : I; index_t w_size = (input_size + (P ? P : H)) * H * 4; if (P > 0) { w_size += P * H; } // If bidirectional, need space to save current layer output y. if (D == 2) { y_cur_ptr = flag ? y_tmp_ptr : y_ptr; flag = !flag; } Tensor<cpu, 2, DType> x(x_ptr, Shape2(T * N, input_size)); Tensor<cpu, 3, DType> y(y_cur_ptr, Shape3(T, N, (P ? P : H) * D)); LstmForwardInferenceSingleLayer<DType>(ws, state_outputs, false, T, N, input_size, H, P, x, hx[idx], cx[idx], y, w_ptr, b_ptr, hy_ptr, cy_ptr); // If bidirectional, then calculate the reverse direction's forward result. if (D == 2) { w_ptr += w_size; b_ptr += b_size; ++idx; if (state_outputs) { hy_ptr += projection_size; cy_ptr += cell_size; } LstmForwardInferenceSingleLayer<DType>(ws, state_outputs, true, T, N, input_size, H, P, x, hx[idx], cx[idx], y, w_ptr, b_ptr, hy_ptr, cy_ptr); } // Don't need to move pointer in the last layer. if (i != L - 1) { w_ptr += w_size; b_ptr += b_size; x_ptr = y_cur_ptr; ++idx; if (state_outputs) { hy_ptr += projection_size; cy_ptr += cell_size; } } } } template <typename DType> void LstmBackwardSingleLayer(DType* ws, DType* rs, DType* tmp_buf, bool bid, const index_t T, const index_t N, const index_t I, const int H, const Tensor<cpu, 2, DType> &x, const Tensor<cpu, 2, DType> &hx, const Tensor<cpu, 2, DType> &cx, const Tensor<cpu, 3, DType> &y, const Tensor<cpu, 3, DType> &dy, const Tensor<cpu, 2, DType> &dx, const Tensor<cpu, 2, DType> &dhx, const Tensor<cpu, 2, DType> &dcx, DType* dhy_ptr, DType* dcy_ptr, DType* w_ptr, DType* dw_ptr, DType* db_ptr, int req_data, int req_params, int req_state, int req_statecell) { using namespace mshadow; const Tensor<cpu, 2, DType> wx(w_ptr, Shape2(H * 4, I)); const Tensor<cpu, 2, DType> wh(w_ptr + I * H * 4, Shape2(H * 4, H)); Tensor<cpu, 2, DType> dwx(dw_ptr, Shape2(H * 4, I)); Tensor<cpu, 2, DType> dwh(dw_ptr + I * H * 4, Shape2(H * 4, H)); Tensor<cpu, 1, DType> dbx(db_ptr, Shape1(H * 4)); Tensor<cpu, 1, DType> dbh(dbx.dptr_ + H * 4, Shape1(H * 4)); DType *c_ptr = bid ? rs + T * N * H * 7 : rs; const Tensor<cpu, 3, DType> c(c_ptr, Shape3(T, N, H)); const Tensor<cpu, 4, DType> ifgo(c_ptr + T * N * H, Shape4(T, N, H, 4)); const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (req_params != kNullOp && req_params != kAddTo) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < H * 4 * H; ++i) { dwh.dptr_[i] = 0; } #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < 4 * H; ++i) { dbx.dptr_[i] = 0; dbh.dptr_[i] = 0; } } Tensor<cpu, 4, DType> difgo(ws, Shape4(T, N, 4, H)); Tensor<cpu, 2, DType> dh(ws + T * N * H * 4, Shape2(N, H)); Tensor<cpu, 2, DType> dc(dh.dptr_ + N * H, Shape2(N, H)); Tensor<cpu, 2, DType> htmp(dc.dptr_ + N * H, Shape2(N, H)); const int offset = bid ? H : 0; const DType alpha = 1.0; const DType beta0 = 0.0; const DType beta1 = 1.0; const DType beta2 = 2.0; const index_t cell_size = N * H; if (dhy_ptr != nullptr) { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < cell_size; ++i) { dh.dptr_[i] = dhy_ptr[i]; } } else { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < cell_size; ++i) { dh.dptr_[i] = 0; } } if (dcy_ptr != nullptr) { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < cell_size; ++i) { dc.dptr_[i] = dcy_ptr[i]; } } else { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < cell_size; ++i) { dc.dptr_[i] = 0; } } for (index_t i = T - 1; i >= 0; --i) { index_t t = bid ? T - 1 - i : i; index_t tnext = bid ? t + 1 : t - 1; const Tensor<cpu, 2, DType>& dhnext = i ? dh : dhx; const Tensor<cpu, 2, DType>& dcnext = i ? dc : dcx; const Tensor<cpu, 2, DType>& hnext = i ? htmp : hx; const Tensor<cpu, 2, DType>& cnext = i ? c[i - 1] : cx; #pragma omp parallel for num_threads(omp_threads) for (index_t jk = 0; jk < cell_size; ++jk) { index_t j = jk / H; index_t k = jk % H; DType tc = tanh(c[i][j][k]); DType it = ifgo[i][j][k][0]; DType ft = ifgo[i][j][k][1]; DType gt = ifgo[i][j][k][2]; DType ot = ifgo[i][j][k][3]; dh[j][k] += dy[t][j][k + offset]; dc[j][k] += dh[j][k] * ot * (1 - tc * tc); difgo[t][j][0][k] = dc[j][k] * gt * it * (1 - it); difgo[t][j][1][k] = dc[j][k] * cnext[j][k] * ft * (1 - ft); difgo[t][j][2][k] = dc[j][k] * it * (1 - gt * gt); difgo[t][j][3][k] = dh[j][k] * tc * ot * (1 - ot); if (req_statecell != kNullOp || i > 0) { dcnext[j][k] = dc[j][k] * ft; } if (i) { htmp[j][k] = y[tnext][j][k + offset]; } } Tensor<cpu, 2, DType> dyh(difgo[t].dptr_, Shape2(N, H * 4)); if (req_state != kNullOp || i > 0) { linalg_gemm(dyh, wh, dhnext, alpha, beta0, false, false); } if (req_params != kNullOp) { if (req_params != kAddTo) { linalg_gemm(dyh, hnext, dwh, alpha, beta1, true, false); } else { linalg_gemm(dyh, hnext, dwh, alpha, beta2, true, false); // generate dwx every time step for AddTo Tensor<cpu, 2, DType> x_t(x.dptr_ + i * N * I, Shape2(N, I)); Tensor<cpu, 2, DType> dyx_t(difgo.dptr_ + i * N * H * 4, Shape2(N, H * 4)); linalg_gemm(dyx_t, x_t, dwx, alpha, beta2, true, false); } } } Tensor<cpu, 2, DType> dyx(difgo.dptr_, Shape2(T * N, H * 4)); if (req_data != kNullOp) { linalg_gemm(dyx, wx, dx, alpha, bid ? beta1 : beta0, false, false); } if (req_params != kNullOp && req_params != kAddTo) { linalg_gemm(dyx, x, dwx, alpha, beta0, true, false); } const index_t row = T * N; const index_t col = H * 4; if (req_params != kNullOp) { if (req_params != kAddTo) { for (index_t i = 0; i < row; ++i) { #pragma omp parallel for num_threads(omp_threads) for (index_t j = 0; j < col; ++j) { dbx[j] += dyx[i][j]; dbh[j] = dbx[j]; } } } else { const Tensor<cpu, 2, DType> tmp_dbx(tmp_buf, Shape2(col, T)); const Tensor<cpu, 2, DType> tmp_dbh(tmp_buf + col * T, Shape2(col, T)); #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < col * T; ++i) { tmp_dbx.dptr_[i] = 0; tmp_dbh.dptr_[i] = 0; } for (index_t t = T - 1; t >= 0; --t) { #pragma omp parallel for num_threads(omp_threads) for (index_t j = 0; j < col; ++j) { for (index_t i = 0; i < N; ++i) { tmp_dbx[j][t] += dyx[t * N + i][j]; tmp_dbh[j][t] = tmp_dbx[j][t]; } } #pragma omp parallel for num_threads(omp_threads) for (index_t j = 0; j < col; ++j) { dbx[j] += tmp_dbx[j][t] + dbx[j]; dbh[j] += tmp_dbh[j][t] + dbh[j]; } } } } } template <typename DType> void LstmBackward(DType* ws, DType* rs, const int L, const int D, const index_t T, const index_t N, const index_t I, const int H, DType* x_ptr, DType* hx_ptr, DType* cx_ptr, DType* w_ptr, DType* y_ptr, DType* dy_ptr, DType* dhy_ptr, DType* dcy_ptr, DType* dx_ptr, DType* dhx_ptr, DType* dcx_ptr, DType* dw_ptr, DType* db_ptr, int req_data, int req_params, int req_state, int req_statecell, const float dropout) { DType* dropout_random = rs + (L - 1) * D * T * N * H; DType* rs2 = rs + (L - 1) * D * T * N * H; DType* tmp_buf = ws; DType* ws2 = tmp_buf + 8 * T * H; const int total_layers = D * L; Tensor<cpu, 3, DType> hx(hx_ptr, Shape3(total_layers, N, H)); Tensor<cpu, 3, DType> cx(cx_ptr, Shape3(total_layers, N, H)); Tensor<cpu, 3, DType> dhx(dhx_ptr, Shape3(total_layers, N, H)); Tensor<cpu, 3, DType> dcx(dcx_ptr, Shape3(total_layers, N, H)); const index_t b_size = 2 * H * 4; const index_t r_size = D * T * N * H * 6; const index_t y_offset = T * N * H * 5; const index_t w_size1 = (I + H) * H * 4; // first layer const index_t w_size2 = (D * H + H) * H * 4; // other layers const index_t cell_size = N * H; DType* dy_tmp_ptr = ws2 + T * cell_size * 4 + cell_size * 3; for (int i = L - 1; i >= 0; --i) { const index_t input_size = i ? H * D : I; const index_t w_size = i ? w_size2 : w_size1; int idx = i * D; DType* w_cur_ptr = i ? w_ptr + (w_size1 + (i - 1) * w_size2) * D : w_ptr; DType* dw_cur_ptr = i ? dw_ptr + (w_size1 + (i - 1) * w_size2) * D : dw_ptr; DType* db_cur_ptr = db_ptr + i * b_size * D; DType* rs_cur_ptr = rs2 + i * r_size; DType* dhy_cur_ptr = dhy_ptr ? dhy_ptr + i * cell_size * D : nullptr; DType* dcy_cur_ptr = dcy_ptr ? dcy_ptr + i * cell_size * D : nullptr; Tensor<cpu, 3, DType> y(rs_cur_ptr + y_offset, Shape3(T, N, H * D)); Tensor<cpu, 3, DType> dy(dy_ptr, Shape3(T, N, H * D)); Tensor<cpu, 2, DType> x(i ? y.dptr_ - r_size : x_ptr, Shape2(T * N, input_size)); Tensor<cpu, 2, DType> dx(i ? dy_tmp_ptr : dx_ptr, Shape2(T * N, input_size)); LstmBackwardSingleLayer<DType>(ws2, rs_cur_ptr, tmp_buf, false, T, N, input_size, H, x, hx[idx], cx[idx], y, dy, dx, dhx[idx], dcx[idx], dhy_cur_ptr, dcy_cur_ptr, w_cur_ptr, dw_cur_ptr, db_cur_ptr, req_data, req_params, req_state, req_statecell); if (D == 2) { w_cur_ptr += w_size; dw_cur_ptr += w_size; db_cur_ptr += b_size; ++idx; dhy_cur_ptr = dhy_ptr ? dhy_cur_ptr + cell_size : nullptr; dcy_cur_ptr = dcy_ptr ? dcy_cur_ptr + cell_size : nullptr; LstmBackwardSingleLayer<DType>(ws2, rs_cur_ptr, tmp_buf, true, T, N, input_size, H, x, hx[idx], cx[idx], y, dy, dx, dhx[idx], dcx[idx], dhy_cur_ptr, dcy_cur_ptr, w_cur_ptr, dw_cur_ptr, db_cur_ptr, req_data, req_params, req_state, req_statecell); } if (dropout > 0.0f && i > 0 && req_data != kNullOp) { dropout_random = dropout_random - T * N * D * H; const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); #pragma omp parallel for num_threads(omp_threads) for (index_t j = 0; j < T * N * D * H; j++) { if (dropout_random[j] == 0) { dx.dptr_[j] = 0; } else { dx.dptr_[j] = dx.dptr_[j] / (1.0f - dropout); } } } dy_ptr = dx.dptr_; } } template<typename DType> void GruForwardInferenceSingleLayer(DType* ws, DType* tmp_buf, bool state_outputs, const int D, const index_t T, const index_t N, const index_t I, const int H, const Tensor<cpu, 2, DType> &x, const Tensor<cpu, 2, DType> &hx, DType* wx_ptr, DType* wh_ptr, DType* bx_ptr, DType* bh_ptr, DType* y_ptr, DType* hy_ptr) { DType* ht = y_ptr; DType* ht_1 = y_ptr; DType* back_ht_1 = y_ptr + (T-1) * N * H * D + H; DType* back_ht = back_ht_1; DType* gemmC1 = ws; // [D, T, N, 3 * H] DType* gemmC2 = gemmC1 + D * T * N * 3 * H; // N * 3 * H DType* rt = gemmC2 + N * 3 * H; DType* zt = rt + N * H; DType* nt = zt + N * H; DType* back_wx_ptr = wx_ptr + I * 3 * H + H * 3 * H; DType* back_wh_ptr = wh_ptr + I * 3 * H + H * 3 * H; DType* back_bx_ptr = (bx_ptr != nullptr)? bx_ptr + 3 * H * 2 : nullptr; DType* back_bh_ptr = (bh_ptr != nullptr)? bh_ptr + 3 * H * 2: nullptr; DType* back_gemmC1 = gemmC1 + T * N * 3 * H; DType* gemmC1_t = gemmC1; const Tensor<cpu, 2, DType> wx(wx_ptr, Shape2(H * 3, I)); const Tensor<cpu, 2, DType> wh(wh_ptr, Shape2(H * 3, H)); const Tensor<cpu, 2, DType> bx(bx_ptr, Shape2(3, H)); const Tensor<cpu, 2, DType> bh(bh_ptr, Shape2(3, H)); const Tensor<cpu, 2, DType> back_wx(back_wx_ptr, Shape2(H * 3, I)); const Tensor<cpu, 2, DType> back_wh(back_wh_ptr, Shape2(H * 3, H)); const Tensor<cpu, 2, DType> back_bx(back_bx_ptr, Shape2(3, H)); const Tensor<cpu, 2, DType> back_bh(back_bh_ptr, Shape2(3, H)); const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (D == 1) { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; i++) for (int j = 0; j < H; j++) { y_ptr[i * H + j] = hx[i][j]; } } else { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; i++) for (int j = 0; j < H; j++) { y_ptr[i * D * H + j] = hx[i][j]; back_ht_1[i * D * H + j] = hx[N + i][j]; } } Tensor<cpu, 2, DType> dgemmC1(ws, Shape2(T * N, 3 * H)); Tensor<cpu, 2, DType> dgemmC2(gemmC2, Shape2(N, 3 * H)); Tensor<cpu, 2, DType> dback_gemmC1(back_gemmC1, Shape2(T * N, 3 * H)); // x * wx.T : [T * N, I] * [I, 3 * H] DType alpha = 1.0; DType beta = 0.0; linalg_gemm(x, wx, dgemmC1, alpha, beta, false, true); if (D == 2) { linalg_gemm(x, back_wx, dback_gemmC1, alpha, beta, false, true); } for (index_t t = 0; t < T; t++) { // perform the first direction, X * wx and H * wh for each step // ht-1 * wh, ht-1:[N, H] wh:[3 * H, H] Tensor<cpu, 2, DType> dht_1(ht_1, Shape2(N, D * H)); if (D == 1) { linalg_gemm(dht_1, wh, dgemmC2, alpha, beta, false, true); } else { Tensor<cpu, 3, DType> dht_1_tmp = Tensor<cpu, 3, DType>(reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); dht_1_tmp = reshape(dht_1.T(), Shape3(D, H, N)); linalg_gemm(dht_1_tmp[0], wh, dgemmC2, alpha, beta, true, true); } gemmC1_t = gemmC1 + t * N * 3 * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { index_t rtb = i * 3 * H; index_t ztb = i * 3 * H + H; index_t ntb = i * 3 * H + 2 * H; rt[i * H + j] = sigmoid(gemmC1_t[rtb + j] + gemmC2[rtb + j] + bx[0][j] + bh[0][j]); zt[i * H + j] = sigmoid(gemmC1_t[ztb + j] + gemmC2[ztb + j] + bx[1][j] + bh[1][j]); nt[i * H + j] = tanh(gemmC1_t[ntb + j] + bx[2][j] + rt[i * H + j] * (gemmC2[ntb + j] + bh[2][j])); ht[i * D * H + j] = (1-zt[i * H + j]) * nt[i * H + j] + zt[i * H + j] * ht_1[i * D * H + j]; } } ht_1 = ht; ht = ht + D * H * N; // perform the second direction if (D == 2) { gemmC1_t = back_gemmC1 + (T - 1 - t) * N * 3 * H; Tensor<cpu, 2, DType> dback_ht_1(back_ht_1 - H, Shape2(N, D * H)); Tensor<cpu, 3, DType> dback_ht_1_tmp = Tensor<cpu, 3, DType> (reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); dback_ht_1_tmp = reshape(dback_ht_1.T(), Shape3(D, H, N)); linalg_gemm(dback_ht_1_tmp[1], back_wh, dgemmC2, alpha, beta, true, true); #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { index_t rtb = i * 3 * H; index_t ztb = i * 3 * H + H; index_t ntb = i * 3 * H + 2 * H; rt[i * H + j] = sigmoid(gemmC1_t[rtb + j] + gemmC2[rtb + j] + back_bx[0][j] + back_bh[0][j]); zt[i * H + j] = sigmoid(gemmC1_t[ztb + j] + gemmC2[ztb + j] + back_bx[1][j]+ back_bh[1][j]); nt[i * H + j] = tanh(gemmC1_t[ntb + j] + back_bx[2][j] + rt[i * H + j] * (gemmC2[ntb + j] + back_bh[2][j])); back_ht[i * D * H + j] = (1 - zt[i * H + j]) * nt[i * H + j] + zt[i * H + j] * back_ht_1[i * D * H + j]; } } back_ht_1 = back_ht; back_ht = back_ht - D * H * N; } } // copy last state to hy, from(N, H * D) to (D, N, H) if (state_outputs) { if (D == 1) { DType* y_start = y_ptr + (T - 1) * N * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; i++) for (int j = 0; j < H; j++) { hy_ptr[i * H + j] = y_start[i * H + j]; } } else { DType* y_start = y_ptr + (T - 1) * N * H * D; DType* y_back_start = y_ptr + H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; i++) for (int j = 0; j < H; j++) { hy_ptr[i * H + j] = y_start[i * D * H + j]; hy_ptr[N * H + i * H + j] = y_back_start[i * D * H + j]; } } } } template <typename DType> void GruForwardInference(DType* ws, bool state_outputs, const int L, const int D, const index_t T, const index_t N, index_t I, const int H, DType* x_ptr, DType* hx_ptr, DType* w_ptr, DType* y_ptr, DType* hy_ptr) { DType* wx = w_ptr; DType* wh = wx + I * H * 3; DType* bx = wh + H * H * 3 + (D - 1) * (H * H * 3 + I * H * 3) + (L - 1) * ((D + 1) * H) * H * 3 * D; DType* bh = bx + H * 3; DType* y_tmp = ws; DType* y_l = x_ptr; DType* tmp_buf = y_tmp + D * T * N * H; DType* ws2 = y_tmp + D * T * N * H + D * H * N; DType* wx_l = wx; DType* wh_l = wh; DType* bx_l = bx; DType* bh_l = bh; Tensor<cpu, 3, DType> hx(hx_ptr, Shape3(D * L, N, H)); DType* hy_l = hy_ptr; for (int l = 0; l < L; l++) { Tensor<cpu, 2, DType> x_l(y_l, Shape2(T * N, I)); if ((L + l) % 2) { y_l = y_ptr; } else { y_l = y_tmp; } Tensor<cpu, 2, DType> hx_l = hx[D * l]; GruForwardInferenceSingleLayer<DType>(ws2, tmp_buf, state_outputs, D, T, N, I, H, x_l, hx_l, wx_l, wh_l, bx_l, bh_l, y_l, hy_l); hy_l = hy_l + D * N * H; bx_l = bx_l + 3 * H * D * 2; bh_l = bh_l + 3 * H * D * 2; wx_l = wx_l + I * H * 3 * D + H * H * 3 * D; if (l == 0) { I = D * H; } wh_l = wx_l + I * 3 * H; } } template<typename DType> void GruForwardTrainingSingleLayer(DType* ws, DType* tmp_buf, bool state_outputs, const int D, const index_t T, const index_t N, const index_t I, const int H, const Tensor<cpu, 2, DType> &x, const Tensor<cpu, 2, DType> &hx, DType* wx_ptr, DType* wh_ptr, DType* bx_ptr, DType* bh_ptr, DType* gateR, DType* gateZ, DType* gateN, DType* Mnh, DType* y_ptr, DType* hy_ptr) { DType* ht = y_ptr; DType* ht_1 = y_ptr; DType* back_ht_1 = y_ptr + (T - 1)* N * H * D + H; DType* back_ht = back_ht_1; DType* gemmC1 = ws; // [D, T, N, 3 * H] DType* gemmC2 = gemmC1 + D * T * N * 3 * H; // N * 3 * H DType* rt = gateR; DType* zt = gateZ; DType* nt = gateN; DType* back_wx_ptr = wx_ptr + I * 3 * H + H * 3 * H; DType* back_wh_ptr = wh_ptr + I * 3 * H + H * 3 * H; DType* back_bx_ptr = (bx_ptr != nullptr)? bx_ptr + 3 * H * 2 : nullptr; DType* back_bh_ptr = (bh_ptr != nullptr)? bh_ptr + 3 * H * 2 : nullptr; DType* back_gateR = gateR + T * N * H; DType* back_gateZ = gateZ + T * N * H; DType* back_gateN = gateN + T * N * H; DType* back_Mnh = Mnh + T * N * H; DType* back_gemmC1 = gemmC1 + T * N * 3 * H; DType* gemmC1_t = gemmC1; const Tensor<cpu, 2, DType> wx(wx_ptr, Shape2(H * 3, I)); const Tensor<cpu, 2, DType> wh(wh_ptr, Shape2(H * 3, H)); const Tensor<cpu, 2, DType> bx(bx_ptr, Shape2(3, H)); const Tensor<cpu, 2, DType> bh(bh_ptr, Shape2(3, H)); const Tensor<cpu, 2, DType> back_wx(back_wx_ptr, Shape2(H * 3, I)); const Tensor<cpu, 2, DType> back_wh(back_wh_ptr, Shape2(H * 3, H)); const Tensor<cpu, 2, DType> back_bx(back_bx_ptr, Shape2(3, H)); const Tensor<cpu, 2, DType> back_bh(back_bh_ptr, Shape2(3, H)); const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (D == 1) { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; i++) for (int j = 0; j < H; j++) { y_ptr[i * H + j] = hx[i][j]; } } else { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; i++) for (int j = 0; j < H; j++) { y_ptr[i * D * H + j] = hx[i][j]; back_ht_1[i * D * H + j] = hx[N + i][j]; } } Tensor<cpu, 2, DType> dgemmC1(ws, Shape2(T * N, 3 * H)); Tensor<cpu, 2, DType> dgemmC2(gemmC2, Shape2(N, 3 * H)); Tensor<cpu, 2, DType> dback_gemmC1(back_gemmC1, Shape2(T * N, 3 * H)); // x * wx.T : [T * N, I] * [I, 3 * H] DType alpha = 1.0; DType beta = 0.0; linalg_gemm(x, wx, dgemmC1, alpha, beta, false, true); if (D == 2) { linalg_gemm(x, back_wx, dback_gemmC1, alpha, beta, false, true); } for (index_t t = 0; t < T; t++) { // perform the first direction, X * wx and H * wh for each step // ht-1 * wh, ht-1:[N, H] wh:[3 * H, H] Tensor<cpu, 2, DType> dht_1(ht_1, Shape2(N, D * H)); if (D == 1) { linalg_gemm(dht_1, wh, dgemmC2, alpha, beta, false, true); } else { Tensor<cpu, 3, DType> dht_1_tmp = Tensor<cpu, 3, DType>(reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); dht_1_tmp = reshape(dht_1.T(), Shape3(D, H, N)); linalg_gemm(dht_1_tmp[0], wh, dgemmC2, alpha, beta, true, true); } rt = gateR + t * N * H; zt = gateZ + t * N * H; nt = gateN + t * N * H; gemmC1_t = gemmC1 + t * N * 3 * H; DType* Mnht = Mnh + t * N * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { index_t rtb = i * 3 * H; index_t ztb = i * 3 * H + H; index_t ntb = i * 3 * H + 2 * H; Mnht[i * H + j] = gemmC2[ntb + j] + bh[2][j]; rt[i * H + j] = sigmoid(gemmC1_t[rtb + j] + gemmC2[rtb + j] + bx[0][j] + bh[0][j]); zt[i * H + j] = sigmoid(gemmC1_t[ztb + j] + gemmC2[ztb + j] + bx[1][j] + bh[1][j]); nt[i * H + j] = tanh(gemmC1_t[ntb + j] + bx[2][j] + rt[i * H + j] * (gemmC2[ntb + j] + bh[2][j])); ht[i * D * H + j] = (1-zt[i * H + j]) * nt[i * H + j] + zt[i * H + j] * ht_1[i * D * H + j]; } } ht_1 = ht; ht = ht + D * H * N; // perform the second direction if (D == 2) { rt = back_gateR + (T - 1 - t) * N * H; zt = back_gateZ + (T - 1 - t) * N * H; nt = back_gateN + (T - 1 - t) * N * H; gemmC1_t = back_gemmC1 + (T - 1 - t) * N * 3 * H; Tensor<cpu, 2, DType> dback_ht_1(back_ht_1 - H, Shape2(N, D * H)); Tensor<cpu, 3, DType> dback_ht_1_tmp = Tensor<cpu, 3, DType> (reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); dback_ht_1_tmp = reshape(dback_ht_1.T(), Shape3(D, H, N)); linalg_gemm(dback_ht_1_tmp[1], back_wh, dgemmC2, alpha, beta, true, true); DType* back_Mnht = back_Mnh + (T - 1 - t) * N * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { index_t rtb = i * 3 * H; index_t ztb = i * 3 * H + H; index_t ntb = i * 3 * H + 2 * H; back_Mnht[i * H + j] = gemmC2[ntb + j] + back_bh[2][j]; rt[i * H + j] = sigmoid(gemmC1_t[rtb + j] + gemmC2[rtb + j] + back_bx[0][j] + back_bh[0][j]); zt[i * H + j] = sigmoid(gemmC1_t[ztb + j] + gemmC2[ztb + j] + back_bx[1][j] + back_bh[1][j]); nt[i * H + j] = tanh(gemmC1_t[ntb + j] + back_bx[2][j] + rt[i * H + j] * (gemmC2[ntb + j] + back_bh[2][j])); back_ht[i * D * H + j] = (1 - zt[i * H + j]) * nt[i * H + j] + zt[i * H + j] * back_ht_1[i * D * H + j]; } } back_ht_1 = back_ht; back_ht = back_ht - D * H * N; } } // copy last state to hy, from(N, H * D) to (D, N, H) if (state_outputs) { if (D == 1) { DType* y_start = y_ptr + (T - 1) * N * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; i++) for (int j = 0; j < H; j++) { hy_ptr[i * H + j] = y_start[i * H + j]; } } else { DType* y_start = y_ptr + (T - 1) * N * H * D; DType* y_back_start = y_ptr + H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; i++) for (int j = 0; j < H; j++) { hy_ptr[i * H + j] = y_start[i * D * H + j]; hy_ptr[N * H + i * H + j] = y_back_start[i * D * H + j]; } } } } template <typename DType> void GruForwardTraining(DType* ws, DType* rs, bool state_outputs, const int L, const int D, const index_t T, const index_t N, index_t I, const int H, DType* x_ptr, DType* hx_ptr, DType* w_ptr, DType* y_ptr, DType* hy_ptr, const float dropout) { DType* wx = w_ptr; DType* wh = wx + I * H * 3; DType* bx = wh + H * H * 3 + (D - 1) * (H * H * 3 + I * H * 3) + (L - 1) * ((D + 1) * H) * H * 3 * D; DType* bh = bx + H * 3; Tensor<cpu, 3, DType> hx(hx_ptr, Shape3(D * L, N, H)); DType* hy_l = hy_ptr; DType* gateR_l = rs; DType* gateZ_l = gateR_l + L * T * D * N * H; DType* gateN_l = gateZ_l + L * T * D * N * H; DType* y_l = gateN_l + L * T * D * N * H; DType* Mnh_l = y_l + L * T * N * H * D; DType* dropout_random = Mnh_l + L * D * T * N * H; DType* tmp_buf = dropout_random + (L - 1) * D * T * N * H; DType* ws2 = tmp_buf + D * N * H; DType* wx_l = wx; DType* wh_l = wh; DType* bx_l = bx; DType* bh_l = bh; DType* y_tmp = x_ptr; unsigned int seed_ = 17 + rand() % 4096; // NOLINT(runtime/threadsafe_fn) for (int l = 0; l < L; l++) { if (l != 0) { y_tmp = y_l; y_l = y_l + T * N * H * D; } if (dropout > 0.0f && l > 0) { const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < T * N * I; i++) { int rand_data = rand_r(&seed_); if (static_cast<float>(rand_data % 1000) < static_cast<float>(1000 * dropout)) { dropout_random[(l - 1) * T * N * I + i] = 0; y_tmp[i] = 0; } else { dropout_random[(l - 1) * T * N * I + i] = 1.0f - dropout; y_tmp[i] = y_tmp[i] / (1.0f - dropout); } } } Tensor<cpu, 2, DType> x_l(y_tmp, Shape2(T * N, I)); Tensor<cpu, 2, DType> hx_l = hx[D * l]; GruForwardTrainingSingleLayer<DType>(ws2, tmp_buf, state_outputs, D, T, N, I, H, x_l, hx_l, wx_l, wh_l, bx_l, bh_l, gateR_l, gateZ_l, gateN_l, Mnh_l, y_l, hy_l); gateR_l = gateR_l + T * D * N * H; gateZ_l = gateZ_l + T * D * N * H; gateN_l = gateN_l + T * D * N * H; Mnh_l = Mnh_l + T * D * N * H; hy_l = hy_l + D * N * H; bx_l = bx_l + 3 * H * D * 2; bh_l = bh_l + 3 * H * D * 2; wx_l = wx_l + I * H * 3 * D + H * H * 3 * D; if (l == 0) { I = D * H; } wh_l = wx_l + I * 3 * H; } const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < T * N * H * D; ++i) { y_ptr[i] = y_l[i]; } } template <typename DType> void GruBackwardSingleLayer(DType* ws, DType* tmp_buf, const int D, const index_t T, const index_t N, const index_t I, const int H, const Tensor<cpu, 2, DType> &x, const Tensor<cpu, 2, DType> &hx, DType* wx_ptr, DType* wh_ptr, DType* y_ptr, DType* dy_ptr, DType* dhy_ptr, DType* gateR, DType* gateZ, DType* gateN, DType* Mnh, DType* dx, DType* dhx, DType* dwx, DType* dwh, DType* dbx, DType* dbh, int req_data, int req_params, int req_state) { DType* dyt; DType* ht1; // [N, D, H] DType* rt; DType* zt; DType* nt; DType* dat; DType* dart; DType* dar = ws; // [T, N, 3 * H] DType* da = dar + T * N * 3 * H; // [T, N, 3 * H] DType* dht1 = da + T * N * 3 * H; // [D, N, H] DType* hx_ = dht1 + D * N * H; // [N, D, H] DType* Mnht = Mnh; DType* back_ht1; DType* back_dht1 = dht1 + N * H; // [N, H] DType* back_Mnht = Mnh + T * N * H; DType* back_gateR = gateR + T * N * H; DType* back_gateZ = gateZ + T * N * H; DType* back_gateN = gateN + T * N * H; DType* back_wx_ptr = wx_ptr + I * 3 * H + H * 3 * H; DType* back_wh_ptr = wh_ptr + I * 3 * H + H * 3 * H; DType* back_dwx = dwx + I * 3 * H + H * 3 * H; DType* back_dwh = dwh + I * 3 * H + H * 3 * H; DType* back_dbx = dbx + 3 * H * 2; DType* back_dbh = dbh + 3 * H * 2; DType alpha = 1.0; DType beta = 0.0; const Tensor<cpu, 2, DType> wx(wx_ptr, Shape2(H * 3, I)); const Tensor<cpu, 2, DType> wh(wh_ptr, Shape2(H * 3, H)); const Tensor<cpu, 2, DType> back_wx(back_wx_ptr, Shape2(H * 3, I)); const Tensor<cpu, 2, DType> back_wh(back_wh_ptr, Shape2(H * 3, H)); const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (req_params != kNullOp && req_params != kAddTo) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < D * H * 3 * H; ++i) { dwh[i] = 0; } #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < D * 3 * H; ++i) { dbx[i] = 0; dbh[i] = 0; } } #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N * H; ++i) { if (dhy_ptr) { dht1[i] = dhy_ptr[i]; } else { dht1[i] = 0; } } #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { hx_[i * D * H + j] = hx[i][j]; } } if (D == 2) { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N * H; ++i) { if (dhy_ptr) { back_dht1[i] = dhy_ptr[N * H + i]; } else { back_dht1[i] = 0; } } #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { hx_[i * D * H + H + j] = hx[N + i][j]; } } } for (index_t t = T - 1; t >= 0; --t) { if (t) { ht1 = y_ptr + (t - 1) * N * D * H; } else { ht1 = hx_; } // add dy[T, N, D, H] to dhy[D, N, H] dyt = dy_ptr + t * N * D * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { dht1[i * H + j] += dyt[i * D * H + j]; } } rt = gateR + t * N * H; zt = gateZ + t * N * H; nt = gateN + t * N * H; Mnht = Mnh + t * N * H; dat = da + t * N * 3 * H; dart = dar + t * N * 3 * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { int nid = i * 3 * H + 2 * H + j; int zid = i * 3 * H + H + j; int rid = i * 3 * H + j; int id = i * H + j; dat[nid] = dht1[id] * (1 - zt[id]) * (1 - nt[id] * nt[id]); dart[zid] = dat[zid] = dht1[id] * (ht1[i * D * H + j] - nt[id]) * zt[id] * (1 - zt[id]); dart[rid] = dat[rid] = dat[nid] * Mnht[id] * rt[id] * (1 - rt[id]); dart[nid] = dat[nid] * rt[id]; dht1[id] = dht1[id] * zt[id]; } } if (req_params != kNullOp) { alpha = 1.0; beta = 1.0; // dht1 = dart * wh [N, H] = [N, 3 * H] * [3 * H, H] Tensor<cpu, 2, DType> d_dht1(dht1, Shape2(N, H)); Tensor<cpu, 2, DType> d_dart(dart, Shape2(N, 3 * H)); linalg_gemm(d_dart, wh, d_dht1, alpha, beta, false, false); if (req_params == kAddTo) { beta = 2.0; // dwx = da.T * x [3 * H, I] = [3 * H, N] * [N, I] for AddTo Tensor<cpu, 2, DType> d_xt(x.dptr_ + t * N * I, Shape2(N, I)); Tensor<cpu, 2, DType> d_dat(dat, Shape2(N, 3 * H)); Tensor<cpu, 2, DType> d_dwx(dwx, Shape2(3 * H, I)); linalg_gemm(d_dat, d_xt, d_dwx, alpha, beta, true, false); } // dwh = dart.T * ht1 [3 * H, H] = [3 * H, N] * [N, H] Tensor<cpu, 2, DType> d_ht1(ht1, Shape2(N, D * H)); Tensor<cpu, 2, DType> d_dwh(dwh, Shape2(3 * H, H)); Tensor<cpu, 3, DType> d_ht1_tmp = Tensor<cpu, 3, DType> (reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); d_ht1_tmp = reshape(d_ht1.T(), Shape3(D, H, N)); linalg_gemm(d_dart, d_ht1_tmp[0], d_dwh, alpha, beta, true, true); } } if (req_params != kNullOp) { // dbx = e * da [1, 3 * H] = [1, N] * [N, 3 * H] if (req_params != kAddTo) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < 3 * H; ++i) { for (index_t j = 0; j < N * T; ++j) { dbx[i] += da[j * 3 * H + i]; dbh[i] += dar[j * 3 * H + i]; } } } else { const Tensor<cpu, 2, DType> tmp_dbx(tmp_buf + T * N * D * H, Shape2(H * 3, T)); const Tensor<cpu, 2, DType> tmp_dbh(tmp_buf + T * N * D * H + 3 * H * T, Shape2(H * 3, T)); #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < H * T * 3; ++i) { tmp_dbx.dptr_[i] = 0; tmp_dbh.dptr_[i] = 0; } for (index_t t = T - 1; t >= 0; --t) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < 3 * H; ++i) { for (index_t j = 0; j < N; ++j) { tmp_dbx[i][t] += da[t * N * 3 * H + j * 3 * H + i]; tmp_dbh[i][t] += dar[t * N * 3 * H + j * 3 * H + i]; } } #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < 3 * H; ++i) { dbx[i] += tmp_dbx[i][t] + dbx[i]; dbh[i] += tmp_dbh[i][t] + dbh[i]; } } } } alpha = 1.0; beta = 0.0; // dx = da * wx [T * N, I] = [T * N, 3 * H] * [3 * H, I] Tensor<cpu, 2, DType> d_da(da, Shape2(T * N, 3 * H)); if (req_data != kNullOp) { Tensor<cpu, 2, DType> d_dx(dx, Shape2(T * N, I)); linalg_gemm(d_da, wx, d_dx, alpha, beta, false, false); } // dwx = da.T * x [3 * H, I] = [3 * H, T * N] * [T * N, I] if (req_params != kNullOp && req_params != kAddTo) { Tensor<cpu, 2, DType> d_dwx(dwx, Shape2(3 * H, I)); linalg_gemm(d_da, x, d_dwx, alpha, beta, true, false); } if (D == 2) { for (index_t t = 0; t < T; ++t) { if (t == T-1) { back_ht1 = hx_; } else { back_ht1 = y_ptr + (t + 1) * N * D * H; } // add dy[T, N, D, H] to dhy[D, N, H] dyt = dy_ptr + t * N * D * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { back_dht1[i * H + j] += dyt[i * D * H + H + j]; } } rt = back_gateR + t * N * H; zt = back_gateZ + t * N * H; nt = back_gateN + t * N * H; back_Mnht = Mnh + (T + t) * N * H; dat = da + t * N * 3 * H; dart = dar + t * N * 3 * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { index_t nid = i * 3 * H + 2 * H + j; index_t zid = i * 3 * H + H + j; index_t rid = i * 3 * H + j; index_t id = i * H + j; dat[nid] = back_dht1[id] * (1 - zt[id]) * (1 - nt[id] * nt[id]); dart[zid] = dat[zid] = back_dht1[id] * (back_ht1[i * D * H + H + j] - nt[id]) * zt[id] * (1 - zt[id]); dart[rid] = dat[rid] = dat[nid] * back_Mnht[id] * rt[id] * (1 - rt[id]); dart[nid] = dat[nid] * rt[id]; back_dht1[id] = back_dht1[id] * zt[id]; } } if (req_params != kNullOp) { alpha = 1.0; beta = 1.0; // dht1 = da * wh [N, H] = [N, 3 * H] * [3 * H, H] Tensor<cpu, 2, DType> d_dart(dart, Shape2(N, 3 * H)); Tensor<cpu, 2, DType> d_back_dht1(back_dht1, Shape2(N, H)); linalg_gemm(d_dart, back_wh, d_back_dht1, alpha, beta, false, false); // dwh = da.T * ht1 [3 * H, H] = [3 * H, N] * [N, H] Tensor<cpu, 2, DType> d_back_dwh(back_dwh, Shape2(3 * H, H)); Tensor<cpu, 2, DType> d_back_ht1(back_ht1 + H, Shape2(N, D * H)); Tensor<cpu, 3, DType> d_back_ht1_tmp = Tensor<cpu, 3, DType> (reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); d_back_ht1_tmp = reshape(d_back_ht1.T(), Shape3(D, H, N)); if (req_params == kAddTo) { beta = 2.0; // dwx = da.T * x [3 * H, I] = [3 * H, N] * [N, I] for AddTo Tensor<cpu, 2, DType> d_xt(x.dptr_ + t * N * I, Shape2(N, I)); Tensor<cpu, 2, DType> d_dat(dat, Shape2(N, 3 * H)); Tensor<cpu, 2, DType> d_back_dwx(back_dwx, Shape2(3 * H, I)); linalg_gemm(d_dat, d_xt, d_back_dwx, alpha, beta, true, false); } linalg_gemm(d_dart, d_back_ht1_tmp[0], d_back_dwh, alpha, beta, true, true); } } if (req_params != kNullOp) { // dbx = e * da [1, 3 * H] = [1, N] * [N, 3 * H] if (req_params != kAddTo) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < 3 * H; ++i) { for (index_t j = 0; j < N * T; ++j) { back_dbx[i] += da[j * 3 * H + i]; back_dbh[i] += dar[j * 3 * H + i]; } } } else { const Tensor<cpu, 2, DType> tmp_dbx(tmp_buf + T * N * D * H, Shape2(H * 3, T)); const Tensor<cpu, 2, DType> tmp_dbh(tmp_buf + T * N * D * H + 3 * H * T, Shape2(H * 3, T)); #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < H * T * 3; ++i) { tmp_dbx.dptr_[i] = 0; tmp_dbh.dptr_[i] = 0; } for (index_t t = T - 1; t >= 0; --t) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < 3 * H; ++i) { for (index_t j = 0; j < N; ++j) { tmp_dbx[i][t] += da[t * N * 3 * H + j * 3 * H + i]; tmp_dbh[i][t] += dar[t * N * 3 * H + j * 3 * H + i]; } } #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < 3 * H; ++i) { back_dbx[i] += tmp_dbx[i][t] + back_dbx[i]; back_dbh[i] += tmp_dbh[i][t] + back_dbh[i]; } } } } alpha = 1.0; beta = 1.0; // dxt = da * wx [T * N, I] = [T * N, 3 * H] * [3 * H, I] Tensor<cpu, 2, DType> d_da2(da, Shape2(T * N, 3 * H)); if (req_data != kNullOp) { Tensor<cpu, 2, DType> d_dx(dx, Shape2(T * N, I)); linalg_gemm(d_da2, back_wx, d_dx, alpha, beta, false, false); } alpha = 1.0; beta = 0.0; // dwx = da.T * x [3 * H, I] = [3 * H, T * N] * [T * N, I] if (req_params != kNullOp && req_params != kAddTo) { Tensor<cpu, 2, DType> d_back_dwx(back_dwx, Shape2(3 * H, I)); linalg_gemm(d_da2, x, d_back_dwx, alpha, beta, true, false); } } if (req_state != kNullOp) { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N * H * D; ++i) { dhx[i] = dht1[i]; } } } template <typename DType> void GruBackward(DType* ws, DType* rs, const int L, const int D, const index_t T, const index_t N, index_t I, const int H, DType* x_ptr, DType* hx_ptr, DType* w_ptr, DType* dy_ptr, DType* dhy_ptr, DType* dx_ptr, DType* dhx_ptr, DType* dw_ptr, int req_data, int req_params, int req_state, const float dropout) { DType* wx = w_ptr; DType* dwx = dw_ptr; DType* dwh = dwx + I * H * 3; DType* dbx = dwh + H * H * 3 + (D - 1) * (H * H * 3 + I * H * 3) + (L - 1) * ((D + 1) * H) * H * 3 * D; DType* gateR_l = rs + (L - 1) * T * D * N * H; DType* gateZ_l = gateR_l + L * T * D * N * H; DType* gateN_l = gateZ_l + L * T * D * N * H; DType* y_l = gateN_l + L * T * D * N * H; DType* Mnh_l = y_l + L * T * N * H * D; DType* dropout_random = Mnh_l + L * D * T * N * H; DType* tmp_buf = dropout_random + (L - 1) * D * T * N * H; DType* dx_l = tmp_buf + T * N * D * H + 3 * H * T * 2; DType* ws2 = dx_l + T * N * D * H; DType* wx_l = (L == 1)? wx : wx + (L - 2) * D * (D + 1) * H * 3 * H + D * I * 3 * H + D * H * 3 * H; DType* wh_l = wx_l; if (L == 1) { wh_l = wh_l + I * H * 3; } else { wh_l = wh_l + (D * H) * H * 3; } DType* dhy_l = nullptr; if (dhy_ptr) dhy_l = dhy_ptr + (L - 1) * D * N * H; DType* dwx_l = (L == 1)? dwx : dwx + (L - 2) * D * (D + 1) * H * 3 * H + D * I * 3 * H + D * H * 3 * H; DType* dwh_l = nullptr; if (L == 1) { dwh_l = dwx_l + I * H * 3; } else { dwh_l = dwx_l + (D * H) * H * 3; } DType* dbx_l = dbx + (L - 1) * D * 3 * H * 2; DType* dbh_l = dbx_l + 3 * H; DType* dhx_l = dhx_ptr + (L - 1) * D * N * H; DType* dy_l = dy_ptr; Tensor<cpu, 3, DType> hx(hx_ptr, Shape3(L, D * N, H)); index_t inputsize = I; DType* y_tmp = y_l - T * N * H * D; const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); for (int l = L - 1; l >= 0; --l) { if (l == 0) { I = inputsize; y_tmp = x_ptr; dx_l = dx_ptr; } else { I = D * H; } Tensor<cpu, 2, DType> hx_l = hx[l]; Tensor<cpu, 2, DType> x_l(y_tmp, Shape2(T * N, I)); GruBackwardSingleLayer<DType>(ws2, tmp_buf, D, T, N, I, H, x_l, hx_l, wx_l, wh_l, y_l, dy_l, dhy_l, gateR_l, gateZ_l, gateN_l, Mnh_l, dx_l, dhx_l, dwx_l, dwh_l, dbx_l, dbh_l, req_data, req_params, req_state); if (dropout > 0.0f && l > 0 && req_data != kNullOp) { dropout_random = dropout_random - T * N * D * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < T * N * I; i++) { if (dropout_random[i] == 0) { dx_l[i] = 0; } else { dx_l[i] = dx_l[i] / (1.0f - dropout); } } } if (l > 0) { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < T * N * H * D; ++i) { dy_l[i] = dx_l[i]; } gateR_l = gateR_l - T * D * N * H; gateZ_l = gateZ_l - T * D * N * H; gateN_l = gateN_l - T * D * N * H; Mnh_l = Mnh_l - T * D * N * H; dhx_l = dhx_l - D * N * H; if (dhy_l) dhy_l = dhy_l - D * N * H; y_l = y_l - T * N * H * D; y_tmp = y_l; if (l == 1) { wx_l = wx_l - (inputsize + H) * H * 3 * D; wh_l = wx_l + inputsize * 3 * H; dwx_l = dwx_l - (inputsize + H) * H * 3 * D; dwh_l = dwx_l + inputsize * 3 * H; } else { wx_l = wx_l - (I + H) * H * 3 * D; wh_l = wx_l + I * 3 * H; dwx_l = dwx_l - (I + H) * H * 3 * D; dwh_l = dwx_l + I * 3 * H; } dbx_l = dbx_l - D * 3 * H * 2; dbh_l = dbx_l + 3 * H; } } } template<typename DType> void VanillaRNNForwardInferenceSingleLayer(DType* ws, DType* tmp_buf, bool state_outputs, const int D, const index_t T, const index_t N, const index_t I, const int H, const Tensor<cpu, 2, DType> &x, const Tensor<cpu, 2, DType> &hx, DType* wx_ptr, DType* wh_ptr, DType* bx_ptr, DType* bh_ptr, DType* y_ptr, DType* hy_ptr, int mode) { DType* ht = y_ptr; DType* ht_1 = y_ptr; DType* back_ht_1 = y_ptr + (T-1) * N * H * D + H; DType* back_ht = back_ht_1; DType* gemmC1 = ws; // [D, T, N, H] DType* gemmC2 = gemmC1 + D * T * N * H; // N * H DType* back_wx_ptr = wx_ptr + I * H + H * H; DType* back_wh_ptr = wh_ptr + I * H + H * H; DType* back_bx_ptr = (bx_ptr != nullptr)? bx_ptr + H * 2 : nullptr; DType* back_bh_ptr = (bh_ptr != nullptr)? bh_ptr + H * 2: nullptr; DType* back_gemmC1 = gemmC1 + T * N * H; DType* gemmC1_t = gemmC1; const Tensor<cpu, 2, DType> wx(wx_ptr, Shape2(H, I)); const Tensor<cpu, 2, DType> wh(wh_ptr, Shape2(H, H)); const Tensor<cpu, 2, DType> bx(bx_ptr, Shape2(1, H)); const Tensor<cpu, 2, DType> bh(bh_ptr, Shape2(1, H)); const Tensor<cpu, 2, DType> back_wx(back_wx_ptr, Shape2(H, I)); const Tensor<cpu, 2, DType> back_wh(back_wh_ptr, Shape2(H, H)); const Tensor<cpu, 2, DType> back_bx(back_bx_ptr, Shape2(1, H)); const Tensor<cpu, 2, DType> back_bh(back_bh_ptr, Shape2(1, H)); const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (D == 1) { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; i++) for (int j = 0; j < H; j++) { y_ptr[i * H + j] = hx[i][j]; } } else { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; i++) for (int j = 0; j < H; j++) { y_ptr[i * D * H + j] = hx[i][j]; back_ht_1[i * D * H + j] = hx[N + i][j]; } } Tensor<cpu, 2, DType> dgemmC1(ws, Shape2(T * N, H)); Tensor<cpu, 2, DType> dgemmC2(gemmC2, Shape2(N, H)); Tensor<cpu, 2, DType> dback_gemmC1(back_gemmC1, Shape2(T * N, H)); // x * wx.T : [T * N, I] * [I, H] DType alpha = 1.0; DType beta = 0.0; linalg_gemm(x, wx, dgemmC1, alpha, beta, false, true); if (D == 2) { linalg_gemm(x, back_wx, dback_gemmC1, alpha, beta, false, true); } for (index_t t = 0; t < T; t++) { // perform the first direction, X * wx and H * wh for each step // ht-1 * wh, ht-1:[N, H] wh:[H, H] Tensor<cpu, 2, DType> dht_1(ht_1, Shape2(N, D * H)); if (D == 1) { linalg_gemm(dht_1, wh, dgemmC2, alpha, beta, false, true); } else { Tensor<cpu, 3, DType> dht_1_tmp = Tensor<cpu, 3, DType>(reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); dht_1_tmp = reshape(dht_1.T(), Shape3(D, H, N)); linalg_gemm(dht_1_tmp[0], wh, dgemmC2, alpha, beta, true, true); } gemmC1_t = gemmC1 + t * N * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { index_t tb = i * H; if (mode == 1) { ht[i * D * H + j] = tanh(gemmC1_t[tb + j] + bx[0][j] + gemmC2[tb + j] + bh[0][j]); } else { ht[i * D * H + j] = relu(gemmC1_t[tb + j] + bx[0][j] + gemmC2[tb + j] + bh[0][j]); } } } ht_1 = ht; ht = ht + D * H * N; // perform the second direction if (D == 2) { gemmC1_t = back_gemmC1 + (T - 1 - t) * N * H; Tensor<cpu, 2, DType> dback_ht_1(back_ht_1 - H, Shape2(N, D * H)); Tensor<cpu, 3, DType> dback_ht_1_tmp = Tensor<cpu, 3, DType> (reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); dback_ht_1_tmp = reshape(dback_ht_1.T(), Shape3(D, H, N)); linalg_gemm(dback_ht_1_tmp[1], back_wh, dgemmC2, alpha, beta, true, true); #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { index_t tb = i * H; if (mode == 1) { back_ht[i * D * H + j] = tanh(gemmC1_t[tb + j] + back_bx[0][j] + gemmC2[tb + j] + back_bh[0][j]); } else { back_ht[i * D * H + j] = relu(gemmC1_t[tb + j] + back_bx[0][j] + gemmC2[tb + j] + back_bh[0][j]); } } } back_ht_1 = back_ht; back_ht = back_ht - D * H * N; } } // copy last state to hy, from(N, H * D) to (D, N, H) if (state_outputs) { if (D == 1) { DType* y_start = y_ptr + (T - 1) * N * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; i++) for (int j = 0; j < H; j++) { hy_ptr[i * H + j] = y_start[i * H + j]; } } else { DType* y_start = y_ptr + (T - 1) * N * H * D; DType* y_back_start = y_ptr + H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; i++) for (int j = 0; j < H; j++) { hy_ptr[i * H + j] = y_start[i * D * H + j]; hy_ptr[N * H + i * H + j] = y_back_start[i * D * H + j]; } } } } template <typename DType> void VanillaRNNForwardInference(DType* ws, bool state_outputs, const int L, const int D, const index_t T, const index_t N, index_t I, const int H, DType* x_ptr, DType* hx_ptr, DType* w_ptr, DType* y_ptr, DType* hy_ptr, int mode) { DType* wx = w_ptr; DType* wh = wx + I * H; DType* bx = wh + H * H + (D - 1) * (H * H + I * H) + (L - 1) * ((D + 1) * H) * H * D; DType* bh = bx + H; DType* y_tmp = ws; DType* y_l = x_ptr; DType* tmp_buf = y_tmp + D * T * N * H; DType* ws2 = y_tmp + D * T * N * H + D * H * N; DType* wx_l = wx; DType* wh_l = wh; DType* bx_l = bx; DType* bh_l = bh; Tensor<cpu, 3, DType> hx(hx_ptr, Shape3(D * L, N, H)); DType* hy_l = hy_ptr; for (int l = 0; l < L; l++) { Tensor<cpu, 2, DType> x_l(y_l, Shape2(T * N, I)); if ((L + l) % 2) { y_l = y_ptr; } else { y_l = y_tmp; } Tensor<cpu, 2, DType> hx_l = hx[D * l]; VanillaRNNForwardInferenceSingleLayer<DType>(ws2, tmp_buf, state_outputs, D, T, N, I, H, x_l, hx_l, wx_l, wh_l, bx_l, bh_l, y_l, hy_l, mode); hy_l = hy_l + D * N * H; bx_l = bx_l + H * D * 2; bh_l = bh_l + H * D * 2; wx_l = wx_l + I * H * D + H * H * D; if (l == 0) { I = D * H; } wh_l = wx_l + I * H; } } template<typename DType> void VanillaRNNForwardTrainingSingleLayer(DType* ws, DType* tmp_buf, bool state_outputs, const int D, const index_t T, const index_t N, const index_t I, const int H, const Tensor<cpu, 2, DType> &x, const Tensor<cpu, 2, DType> &hx, DType* wx_ptr, DType* wh_ptr, DType* bx_ptr, DType* bh_ptr, DType* gateN, DType* y_ptr, DType* hy_ptr, int mode) { DType* ht = y_ptr; DType* ht_1 = y_ptr; DType* back_ht_1 = y_ptr + (T - 1)* N * H * D + H; DType* back_ht = back_ht_1; DType* gemmC1 = ws; // [D, T, N, H] DType* gemmC2 = gemmC1 + D * T * N * H; // N * H DType* nt = gateN; DType* back_wx_ptr = wx_ptr + I * H + H * H; DType* back_wh_ptr = wh_ptr + I * H + H * H; DType* back_bx_ptr = (bx_ptr != nullptr)? bx_ptr + H * 2 : nullptr; DType* back_bh_ptr = (bh_ptr != nullptr)? bh_ptr + H * 2 : nullptr; DType* back_gateN = gateN + T * N * H; DType* back_gemmC1 = gemmC1 + T * N * H; DType* gemmC1_t = gemmC1; const Tensor<cpu, 2, DType> wx(wx_ptr, Shape2(H, I)); const Tensor<cpu, 2, DType> wh(wh_ptr, Shape2(H, H)); const Tensor<cpu, 2, DType> bx(bx_ptr, Shape2(1, H)); const Tensor<cpu, 2, DType> bh(bh_ptr, Shape2(1, H)); const Tensor<cpu, 2, DType> back_wx(back_wx_ptr, Shape2(H * 1, I)); const Tensor<cpu, 2, DType> back_wh(back_wh_ptr, Shape2(H * 1, H)); const Tensor<cpu, 2, DType> back_bx(back_bx_ptr, Shape2(1, H)); const Tensor<cpu, 2, DType> back_bh(back_bh_ptr, Shape2(1, H)); const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (D == 1) { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; i++) for (int j = 0; j < H; j++) { y_ptr[i * H + j] = hx[i][j]; } } else { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; i++) for (int j = 0; j < H; j++) { y_ptr[i * D * H + j] = hx[i][j]; back_ht_1[i * D * H + j] = hx[N + i][j]; } } Tensor<cpu, 2, DType> dgemmC1(ws, Shape2(T * N, H)); Tensor<cpu, 2, DType> dgemmC2(gemmC2, Shape2(N, H)); Tensor<cpu, 2, DType> dback_gemmC1(back_gemmC1, Shape2(T * N, H)); // x * wx.T : [T * N, I] * [I, H] DType alpha = 1.0; DType beta = 0.0; linalg_gemm(x, wx, dgemmC1, alpha, beta, false, true); if (D == 2) { linalg_gemm(x, back_wx, dback_gemmC1, alpha, beta, false, true); } for (index_t t = 0; t < T; t++) { // perform the first direction, X * wx and H * wh for each step // ht-1 * wh, ht-1:[N, H] wh:[H, H] Tensor<cpu, 2, DType> dht_1(ht_1, Shape2(N, D * H)); if (D == 1) { linalg_gemm(dht_1, wh, dgemmC2, alpha, beta, false, true); } else { Tensor<cpu, 3, DType> dht_1_tmp = Tensor<cpu, 3, DType>(reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); dht_1_tmp = reshape(dht_1.T(), Shape3(D, H, N)); linalg_gemm(dht_1_tmp[0], wh, dgemmC2, alpha, beta, true, true); } nt = gateN + t * N * H; gemmC1_t = gemmC1 + t * N * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { index_t tb = i * H; if (mode == 1) { nt[tb + j] = ht[i * D * H + j] = tanh(gemmC1_t[tb + j] + bx[0][j] + gemmC2[tb + j] + bh[0][j]); } else { nt[tb + j] = gemmC1_t[tb + j] + bx[0][j] + gemmC2[tb + j] + bh[0][j]; ht[i * D * H + j] = relu(nt[tb + j]); } } } ht_1 = ht; ht = ht + D * H * N; // perform the second direction if (D == 2) { nt = back_gateN + (T - 1 - t) * N * H; gemmC1_t = back_gemmC1 + (T - 1 - t) * N * H; Tensor<cpu, 2, DType> dback_ht_1(back_ht_1 - H, Shape2(N, D * H)); Tensor<cpu, 3, DType> dback_ht_1_tmp = Tensor<cpu, 3, DType> (reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); dback_ht_1_tmp = reshape(dback_ht_1.T(), Shape3(D, H, N)); linalg_gemm(dback_ht_1_tmp[1], back_wh, dgemmC2, alpha, beta, true, true); #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { index_t tb = i * H; if (mode == 1) { nt[tb + j] = back_ht[i * D * H + j] = tanh(gemmC1_t[tb + j] + back_bx[0][j] + gemmC2[tb + j] + back_bh[0][j]); } else { nt[tb + j] = gemmC1_t[tb + j] + back_bx[0][j] + gemmC2[tb + j] + back_bh[0][j]; back_ht[i * D * H + j] = relu(nt[tb + j]); } } } back_ht_1 = back_ht; back_ht = back_ht - D * H * N; } } // copy last state to hy, from(N, H * D) to (D, N, H) if (state_outputs) { if (D == 1) { DType* y_start = y_ptr + (T - 1) * N * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; i++) for (int j = 0; j < H; j++) { hy_ptr[i * H + j] = y_start[i * H + j]; } } else { DType* y_start = y_ptr + (T - 1) * N * H * D; DType* y_back_start = y_ptr + H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; i++) for (int j = 0; j < H; j++) { hy_ptr[i * H + j] = y_start[i * D * H + j]; hy_ptr[N * H + i * H + j] = y_back_start[i * D * H + j]; } } } } template <typename DType> void VanillaRNNForwardTraining(DType* ws, DType* rs, bool state_outputs, const int L, const int D, const index_t T, const index_t N, index_t I, const int H, DType* x_ptr, DType* hx_ptr, DType* w_ptr, DType* y_ptr, DType* hy_ptr, const float dropout, int mode) { DType* wx = w_ptr; DType* wh = wx + I * H; DType* bx = wh + H * H + (D - 1) * (H * H + I * H) + (L - 1) * ((D + 1) * H) * H * D; DType* bh = bx + H; Tensor<cpu, 3, DType> hx(hx_ptr, Shape3(D * L, N, H)); DType* hy_l = hy_ptr; DType* gateN_l = rs; DType* y_l = gateN_l + L * T * D * N * H; DType* dropout_random = y_l + L * D * T * N * H; DType* tmp_buf = dropout_random + (L - 1) * D * T * N * H; DType* ws2 = tmp_buf + D * N * H; DType* wx_l = wx; DType* wh_l = wh; DType* bx_l = bx; DType* bh_l = bh; DType* y_tmp = x_ptr; const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); unsigned int seed_ = 17 + rand() % 4096; // NOLINT(runtime/threadsafe_fn) for (int l = 0; l < L; l++) { if (l != 0) { y_tmp = y_l; y_l = y_l + T * N * H * D; } if (dropout > 0.0f && l > 0) { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < T * N * I; i++) { int rand_data = rand_r(&seed_); if (static_cast<float>(rand_data % 1000) < static_cast<float>(1000 * dropout)) { dropout_random[(l - 1) * T * N * I + i] = 0; y_tmp[i] = 0; } else { dropout_random[(l - 1) * T * N * I + i] = 1.0f - dropout; y_tmp[i] = y_tmp[i] / (1.0f - dropout); } } } Tensor<cpu, 2, DType> x_l(y_tmp, Shape2(T * N, I)); Tensor<cpu, 2, DType> hx_l = hx[D * l]; VanillaRNNForwardTrainingSingleLayer<DType>(ws2, tmp_buf, state_outputs, D, T, N, I, H, x_l, hx_l, wx_l, wh_l, bx_l, bh_l, gateN_l, y_l, hy_l, mode); gateN_l = gateN_l + T * D * N * H; hy_l = hy_l + D * N * H; bx_l = bx_l + H * D * 2; bh_l = bh_l + H * D * 2; wx_l = wx_l + I * H * D + H * H * D; if (l == 0) { I = D * H; } wh_l = wx_l + I * H; } #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < T * N * H * D; ++i) { y_ptr[i] = y_l[i]; } } template <typename DType> void VanillaRNNBackwardSingleLayer(DType* ws, DType* tmp_buf, const int D, const index_t T, const index_t N, const index_t I, const int H, const Tensor<cpu, 2, DType> &x, const Tensor<cpu, 2, DType> &hx, DType* wx_ptr, DType* wh_ptr, DType* y_ptr, DType* dy_ptr, DType* dhy_ptr, DType* gateN, DType* dx, DType* dhx, DType* dwx, DType* dwh, DType* dbx, DType* dbh, int req_data, int req_params, int req_state, int mode) { DType* dyt; DType* ht1; // [N, D, H] DType* dart; DType* nt; DType* dar = ws; // [T, N, H] DType* dht1 = dar + T * N * H; // [D, N, H] DType* hx_ = dht1 + D * N * H; // [N, D, H] DType* back_ht1; DType* back_dht1 = dht1 + N * H; // [N, H] DType* back_gateN = gateN + T * N * H; DType* back_wx_ptr = wx_ptr + I * H + H * H; DType* back_wh_ptr = wh_ptr + I * H + H * H; DType* back_dwx = dwx + I * H + H * H; DType* back_dwh = dwh + I * H + H * H; DType* back_dbx = dbx + H * 2; DType* back_dbh = dbh + H * 2; DType alpha = 1.0; DType beta = 0.0; const Tensor<cpu, 2, DType> wx(wx_ptr, Shape2(H, I)); const Tensor<cpu, 2, DType> wh(wh_ptr, Shape2(H, H)); const Tensor<cpu, 2, DType> back_wx(back_wx_ptr, Shape2(H, I)); const Tensor<cpu, 2, DType> back_wh(back_wh_ptr, Shape2(H, H)); const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (req_params != kNullOp && req_params != kAddTo) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < D * H * H; ++i) { dwh[i] = 0; } #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < D * H; ++i) { dbx[i] = 0; dbh[i] = 0; } } #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N * H; ++i) { if (dhy_ptr) { dht1[i] = dhy_ptr[i]; } else { dht1[i] = 0; } } #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { hx_[i * D * H + j] = hx[i][j]; } } if (D == 2) { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N * H; ++i) { if (dhy_ptr) { back_dht1[i] = dhy_ptr[N * H + i]; } else { back_dht1[i] = 0; } } #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { hx_[i * D * H + H + j] = hx[N + i][j]; } } } for (index_t t = T - 1; t >= 0; --t) { if (t) { ht1 = y_ptr + (t - 1) * N * D * H; } else { ht1 = hx_; } // add dy[T, N, D, H] to dhy[D, N, H] dyt = dy_ptr + t * N * D * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { dht1[i * H + j] += dyt[i * D * H + j]; } } nt = gateN + t * N * H; dart = dar + t * N * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { index_t id = i * H + j; if (mode == 1) { dart[id] = dht1[id] * (1 - nt[id] * nt[id]); } else { dart[id] = nt[id] > 0.0f ? static_cast<float>(dht1[id]) : 0.0f; } dht1[id] = 0; } } if (req_params != kNullOp) { alpha = 1.0; beta = 1.0; // dht1 = dart * wh [N, H] = [N, H] * [H, H] Tensor<cpu, 2, DType> d_dht1(dht1, Shape2(N, H)); Tensor<cpu, 2, DType> d_dart(dart, Shape2(N, H)); linalg_gemm(d_dart, wh, d_dht1, alpha, beta, false, false); if (req_params == kAddTo) { beta = 2.0; // dwx = da.T * x [H, I] = [H, N] * [N, I] for AddTo Tensor<cpu, 2, DType> d_xt(x.dptr_ + t * N * I, Shape2(N, I)); Tensor<cpu, 2, DType> d_dwx(dwx, Shape2(H, I)); linalg_gemm(d_dart, d_xt, d_dwx, alpha, beta, true, false); } // dwh = dart.T * ht1 [H, H] = [H, N] * [N, H] Tensor<cpu, 2, DType> d_ht1(ht1, Shape2(N, D * H)); Tensor<cpu, 2, DType> d_dwh(dwh, Shape2(H, H)); Tensor<cpu, 3, DType> d_ht1_tmp = Tensor<cpu, 3, DType> (reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); d_ht1_tmp = reshape(d_ht1.T(), Shape3(D, H, N)); linalg_gemm(d_dart, d_ht1_tmp[0], d_dwh, alpha, beta, true, true); } } if (req_params != kNullOp) { // dbx = e * da [1, H] = [1, N] * [N, H] if (req_params != kAddTo) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < H; ++i) { for (index_t j = 0; j < N * T; ++j) { dbx[i] += dar[j * H + i]; dbh[i] = dbx[i]; } } } else { const Tensor<cpu, 2, DType> tmp_dbx(tmp_buf + T * N * D * H, Shape2(H, T)); const Tensor<cpu, 2, DType> tmp_dbh(tmp_buf + T * N * D * H + H * T, Shape2(H, T)); #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < H * T; ++i) { tmp_dbx.dptr_[i] = 0; tmp_dbh.dptr_[i] = 0; } for (index_t t = T - 1; t >= 0; --t) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < H; ++i) { for (index_t j = 0; j < N; ++j) { tmp_dbx[i][t] += dar[t * N * H + j * H + i]; tmp_dbh[i][t] = tmp_dbx[i][t]; } } #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < H; ++i) { dbx[i] += tmp_dbx[i][t] + dbx[i]; dbh[i] = dbx[i]; } } } } alpha = 1.0; beta = 0.0; // dx = da * wx [T * N, I] = [T * N, H] * [H, I] Tensor<cpu, 2, DType> d_dar(dar, Shape2(T * N, H)); if (req_data != kNullOp) { Tensor<cpu, 2, DType> d_dx(dx, Shape2(T * N, I)); linalg_gemm(d_dar, wx, d_dx, alpha, beta, false, false); } // dwx = da.T * x [H, I] = [H, T * N] * [T * N, I] if (req_params != kNullOp && req_params != kAddTo) { Tensor<cpu, 2, DType> d_dwx(dwx, Shape2(H, I)); linalg_gemm(d_dar, x, d_dwx, alpha, beta, true, false); } if (D == 2) { for (index_t t = 0; t < T; ++t) { if (t == T-1) { back_ht1 = hx_; } else { back_ht1 = y_ptr + (t + 1) * N * D * H; } // add dy[T, N, D, H] to dhy[D, N, H] dyt = dy_ptr + t * N * D * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { back_dht1[i * H + j] += dyt[i * D * H + H + j]; } } nt = back_gateN + t * N * H; dart = dar + t * N * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N; ++i) { for (int j = 0; j < H; ++j) { index_t id = i * H + j; if (mode == 1) { dart[id] = back_dht1[id] * (1 - nt[id] * nt[id]); } else { dart[id] = nt[id] > 0.0f ? static_cast<float>(back_dht1[id]) : 0.0f; } back_dht1[id] = 0; } } if (req_params != kNullOp) { alpha = 1.0; beta = 1.0; // dht1 = da * wh [N, H] = [N, H] * [H, H] Tensor<cpu, 2, DType> d_dart(dart, Shape2(N, H)); Tensor<cpu, 2, DType> d_back_dht1(back_dht1, Shape2(N, H)); linalg_gemm(d_dart, back_wh, d_back_dht1, alpha, beta, false, false); // dwh = da.T * ht1 [H, H] = [H, N] * [N, H] Tensor<cpu, 2, DType> d_back_dwh(back_dwh, Shape2(H, H)); Tensor<cpu, 2, DType> d_back_ht1(back_ht1 + H, Shape2(N, D * H)); Tensor<cpu, 3, DType> d_back_ht1_tmp = Tensor<cpu, 3, DType> (reinterpret_cast<DType*>(tmp_buf), Shape3(D, H, N)); d_back_ht1_tmp = reshape(d_back_ht1.T(), Shape3(D, H, N)); if (req_params == kAddTo) { beta = 2.0; // dwx = da.T * x [ H, I] = [H, N] * [N, I] for AddTo Tensor<cpu, 2, DType> d_xt(x.dptr_ + t * N * I, Shape2(N, I)); Tensor<cpu, 2, DType> d_back_dwx(back_dwx, Shape2(H, I)); linalg_gemm(d_dart, d_xt, d_back_dwx, alpha, beta, true, false); } linalg_gemm(d_dart, d_back_ht1_tmp[0], d_back_dwh, alpha, beta, true, true); } } if (req_params != kNullOp) { // dbx = e * da [1, H] = [1, N] * [N, H] if (req_params != kAddTo) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < H; ++i) { for (index_t j = 0; j < N * T; ++j) { back_dbx[i] += dar[j * H + i]; back_dbh[i] = back_dbx[i]; } } } else { const Tensor<cpu, 2, DType> tmp_dbx(tmp_buf + T * N * D * H, Shape2(H, T)); const Tensor<cpu, 2, DType> tmp_dbh(tmp_buf + T * N * D * H + H * T, Shape2(H, T)); #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < H * T; ++i) { tmp_dbx.dptr_[i] = 0; tmp_dbh.dptr_[i] = 0; } for (index_t t = T - 1; t >= 0; --t) { #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < H; ++i) { for (index_t j = 0; j < N; ++j) { tmp_dbx[i][t] += dar[t * N * H + j * H + i]; tmp_dbh[i][t] = tmp_dbx[i][t]; } } #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < H; ++i) { back_dbx[i] += tmp_dbx[i][t] + back_dbx[i]; back_dbh[i] = back_dbx[i]; } } } } alpha = 1.0; beta = 1.0; // dxt = da * wx [T * N, I] = [T * N, H] * [H, I] Tensor<cpu, 2, DType> d_dar2(dar, Shape2(T * N, H)); if (req_data != kNullOp) { Tensor<cpu, 2, DType> d_dx(dx, Shape2(T * N, I)); linalg_gemm(d_dar2, back_wx, d_dx, alpha, beta, false, false); } alpha = 1.0; beta = 0.0; // dwx = da.T * x [H, I] = [H, T * N] * [T * N, I] if (req_params != kNullOp && req_params != kAddTo) { Tensor<cpu, 2, DType> d_back_dwx(back_dwx, Shape2(H, I)); linalg_gemm(d_dar2, x, d_back_dwx, alpha, beta, true, false); } } if (req_state != kNullOp) { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < N * H * D; ++i) { dhx[i] = dht1[i]; } } } template <typename DType> void VanillaRNNBackward(DType* ws, DType* rs, const int L, const int D, const index_t T, const index_t N, index_t I, const int H, DType* x_ptr, DType* hx_ptr, DType* w_ptr, DType* dy_ptr, DType* dhy_ptr, DType* dx_ptr, DType* dhx_ptr, DType* dw_ptr, int req_data, int req_params, int req_state, const float dropout, int mode) { DType* wx = w_ptr; DType* dwx = dw_ptr; DType* dwh = dwx + I * H; DType* dbx = dwh + H * H + (D - 1) * (H * H + I * H) + (L - 1) * ((D + 1) * H) * H * D; DType* gateN_l = rs + (L - 1) * T * D * N * H; DType* y_l = gateN_l + L * T * D * N * H; DType* dropout_random = y_l + L * D * T * N * H; DType* tmp_buf = dropout_random + (L - 1) * D * T * N * H; DType* dx_l = tmp_buf + T * N * D * H + H * T * 2; DType* ws2 = dx_l + T * N * D * H; DType* wx_l = (L == 1)? wx : wx + (L - 2) * D * (D + 1) * H * H + D * I * H + D * H * H; DType* wh_l = wx_l; if (L == 1) { wh_l = wh_l + I * H; } else { wh_l = wh_l + (D * H) * H; } DType* dhy_l = nullptr; if (dhy_ptr) dhy_l = dhy_ptr + (L - 1) * D * N * H; DType* dwx_l = (L == 1)? dwx : dwx + (L - 2) * D * (D + 1) * H * H + D * I * H + D * H * H; DType* dwh_l = nullptr; if (L == 1) { dwh_l = dwx_l + I * H; } else { dwh_l = dwx_l + (D * H) * H; } DType* dbx_l = dbx + (L - 1) * D * H * 2; DType* dbh_l = dbx_l + H; DType* dhx_l = dhx_ptr + (L - 1) * D * N * H; DType* dy_l = dy_ptr; Tensor<cpu, 3, DType> hx(hx_ptr, Shape3(L, D * N, H)); index_t inputsize = I; DType* y_tmp = y_l - T * N * H * D; const int omp_threads = mxnet::engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); for (int l = L - 1; l >= 0; --l) { if (l == 0) { I = inputsize; y_tmp = x_ptr; dx_l = dx_ptr; } else { I = D * H; } Tensor<cpu, 2, DType> hx_l = hx[l]; Tensor<cpu, 2, DType> x_l(y_tmp, Shape2(T * N, I)); VanillaRNNBackwardSingleLayer<DType>(ws2, tmp_buf, D, T, N, I, H, x_l, hx_l, wx_l, wh_l, y_l, dy_l, dhy_l, gateN_l, dx_l, dhx_l, dwx_l, dwh_l, dbx_l, dbh_l, req_data, req_params, req_state, mode); if (dropout > 0.0f && l > 0 && req_data != kNullOp) { dropout_random = dropout_random - T * N * D * H; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < T * N * I; i++) { if (dropout_random[i] == 0) { dx_l[i] = 0; } else { dx_l[i] = dx_l[i] / (1.0f - dropout); } } } if (l > 0) { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < T * N * H * D; ++i) { dy_l[i] = dx_l[i]; } gateN_l = gateN_l - T * D * N * H; dhx_l = dhx_l - D * N * H; if (dhy_l) dhy_l = dhy_l - D * N * H; y_l = y_l - T * N * H * D; y_tmp = y_l; if (l == 1) { wx_l = wx_l - (inputsize + H) * H * D; wh_l = wx_l + inputsize * H; dwx_l = dwx_l - (inputsize + H) * H * D; dwh_l = dwx_l + inputsize * H; } else { wx_l = wx_l - (I + H) * H * D; wh_l = wx_l + I * H; dwx_l = dwx_l - (I + H) * H * D; dwh_l = dwx_l + I * H; } dbx_l = dbx_l - D * H * 2; dbh_l = dbx_l + H; } } } } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_RNN_IMPL_H_
GB_unaryop__lnot_bool_uint16.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_bool_uint16 // op(A') function: GB_tran__lnot_bool_uint16 // C type: bool // A type: uint16_t // cast: bool cij = (bool) aij // unaryop: cij = !aij #define GB_ATYPE \ uint16_t #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !x ; // casting #define GB_CASTING(z, x) \ bool z = (bool) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_BOOL || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_bool_uint16 ( bool *restrict Cx, const uint16_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_bool_uint16 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
mkl_util.h
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_UTIL_MKL_UTIL_H_ #define TENSORFLOW_CORE_UTIL_MKL_UTIL_H_ #ifdef INTEL_MKL #include <list> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> #if defined(INTEL_MKL_ML_ONLY) || defined(INTEL_MKL_DNN_ONLY) #ifndef INTEL_MKL #error "INTEL_MKL_{ML,DNN}_ONLY require INTEL_MKL" #endif #endif #if defined(INTEL_MKL_ML_ONLY) && defined(INTEL_MKL_DNN_ONLY) #error "at most one of INTEL_MKL_ML_ONLY and INTEL_MKL_DNN_ONLY may be defined" #endif #ifdef INTEL_MKL_ML_ONLY #error "Please use INTEL MKL DNN (the default option for --config=mkl)." #endif #ifdef INTEL_MKL_ML_ONLY #include "mkl_dnn.h" #include "mkl_dnn_types.h" #include "mkl_service.h" #include "mkl_trans.h" #endif #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/graph/mkl_graph_util.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/gtl/array_slice.h" #include "tensorflow/core/platform/cpu_info.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/util/env_var.h" #include "tensorflow/core/util/padding.h" #include "tensorflow/core/util/tensor_format.h" #ifndef INTEL_MKL_ML_ONLY #include "mkldnn.hpp" #include "tensorflow/core/lib/core/stringpiece.h" using mkldnn::engine; using mkldnn::memory; using mkldnn::padding_kind; using mkldnn::primitive; using mkldnn::reorder; #endif #ifdef _WIN32 typedef unsigned int uint; #endif namespace tensorflow { // The file contains a number of utility classes and functions used by MKL // enabled kernels // This class encapsulates all the meta data that is associated with an MKL // tensor. A tensor is an MKL tensor if it was created as the result of an // MKL operation, and did not go through a conversion to a standard // Tensorflow tensor. // For use with MKL ML, has been deprecated typedef enum { W = 0, H = 1, C = 2, N = 3 } MklDims; // The dimensions order that MKL-DNN internally uses for 2D activations // [Batch, Channel, Height, Width] and // for 2D filters [Out_Channel, In_Channel, Height, Width]. typedef enum { Dim_N = 0, Dim_C = 1, Dim_H = 2, Dim_W = 3, Dim_O = 0, Dim_I = 1 } MklDnnDims; // The dimensions order that MKL-DNN internally uses for 3D activations // [Batch, Channel, Depth, Height, Width] and // for 3D filters [Out_Channel, In_Channel, Depth, Height, Width]. typedef enum { Dim3d_N = 0, Dim3d_C = 1, Dim3d_D = 2, Dim3d_H = 3, Dim3d_W = 4, Dim3d_O = 0, Dim3d_I = 1 } MklDnnDims3D; // Enum for the order of dimensions of a TF 2D filter with shape [filter_height, // filter_width, in_channels, out_channels] typedef enum { TF_2DFILTER_DIM_H = 0, TF_2DFILTER_DIM_W = 1, TF_2DFILTER_DIM_I = 2, TF_2DFILTER_DIM_O = 3 } TFFilterDims2d; // Enum for the order of dimensions of a TF 3D filter with shape [filter_depth, // filter_height, filter_width, in_channels, out_channels] typedef enum { TF_3DFILTER_DIM_P = 0, TF_3DFILTER_DIM_H = 1, TF_3DFILTER_DIM_W = 2, TF_3DFILTER_DIM_I = 3, TF_3DFILTER_DIM_O = 4 } TFFilterDims3d; // The dimensions order that MKL-DNN requires for the filter in a grouped // convolution (2D only) typedef enum { MKL_GROUP_FILTER_DIM_G = 0, MKL_GROUP_FILTER_DIM_O = 1, MKL_GROUP_FILTER_DIM_I = 2, MKL_GROUP_FILTER_DIM_H = 3, MKL_GROUP_FILTER_DIM_W = 4 } MklDnnFilterGroupDims; // Enum used to templatize MklOp kernel implementations // that support both fp32 and int8 versions. enum class MklQuantization { QUANTIZED_VERSION, FP_VERSION, }; static const int kSmallBatchSize = 32; #ifdef INTEL_MKL_ML_ONLY class MklShape { public: MklShape() {} TF_DISALLOW_COPY_AND_ASSIGN(MklShape); // Cannot copy ~MklShape() { if (sizes_) delete[] sizes_; if (strides_) delete[] strides_; if (mklLayout_) CHECK_EQ(dnnLayoutDelete_F32(mklLayout_), E_SUCCESS); if (tfLayout_) CHECK_EQ(dnnLayoutDelete_F32(tfLayout_), E_SUCCESS); if (tf_to_mkl_dim_map_) delete[] tf_to_mkl_dim_map_; } const bool IsMklTensor() const { return isMklTensor_; } void SetMklTensor(const bool isMklTensor) { isMklTensor_ = isMklTensor; } void SetDimensions(const size_t dimension) { dimension_ = dimension; } void SetMklLayout(dnnLayout_t mklLayout) { mklLayout_ = mklLayout; } void SetMklLayout(const void* primitive, size_t resourceType) { CHECK_EQ( dnnLayoutCreateFromPrimitive_F32(&mklLayout_, (dnnPrimitive_t)primitive, (dnnResourceType_t)resourceType), E_SUCCESS); } void SetTfLayout(const size_t dimension, const size_t* sizes, const size_t* strides) { dimension_ = dimension; if (dimension > 0) { // MKl doesn't support zero dimension tensors sizes_ = new size_t[dimension]; strides_ = new size_t[dimension]; for (int ii = 0; ii < dimension; ii++) { sizes_[ii] = sizes[ii]; strides_[ii] = strides[ii]; } CHECK_EQ(dnnLayoutCreate_F32(&tfLayout_, dimension, sizes, strides), E_SUCCESS); } } // Default case - MKL dim ordering is opposite of TF dim ordering // MKL -> (DIMS-1)...0 where (DIMS-1) is outermost dim and 0 is innermost dim // TF -> 0...(DIMS-1) where 0 is outermost dim and (DIMS-1) is innermost dim // For layers that rely on data_format semantics (conv, pooling etc.) // or operate only on certain dimensions (relu, concat, split etc.), // Mkl APIs might require us to reorder these dimensions. In such cases, // kernels should explicitly set this map void SetTfDimOrder(const size_t dimension) { CHECK(dimension == dimension_); if (tf_to_mkl_dim_map_ == nullptr) { tf_to_mkl_dim_map_ = new size_t[dimension]; } for (size_t ii = 0; ii < dimension; ii++) { tf_to_mkl_dim_map_[ii] = dimension - (ii + 1); } } void SetTfDimOrder(const size_t dimension, const size_t* tf_to_mkl_dim_map) { CHECK(dimension == dimension_); if (tf_to_mkl_dim_map_ == nullptr) { tf_to_mkl_dim_map_ = new size_t[dimension]; } for (size_t ii = 0; ii < dimension; ii++) { tf_to_mkl_dim_map_[ii] = tf_to_mkl_dim_map[ii]; } } void SetTfDimOrder(const size_t dimension, TensorFormat data_format) { CHECK_EQ(dimension, 4); CHECK(dimension == dimension_); if (tf_to_mkl_dim_map_ == nullptr) { tf_to_mkl_dim_map_ = new size_t[dimension]; } tf_to_mkl_dim_map_[GetTensorDimIndex<2>(data_format, 'W')] = MklDims::W; tf_to_mkl_dim_map_[GetTensorDimIndex<2>(data_format, 'H')] = MklDims::H; tf_to_mkl_dim_map_[GetTensorDimIndex<2>(data_format, 'C')] = MklDims::C; tf_to_mkl_dim_map_[GetTensorDimIndex<2>(data_format, 'N')] = MklDims::N; } const dnnLayout_t GetMklLayout() const { return mklLayout_; } const dnnLayout_t GetTfLayout() const { return tfLayout_; } const dnnLayout_t GetCurLayout() const { return isMklTensor_ ? mklLayout_ : tfLayout_; } size_t GetDimension() const { return dimension_; } const size_t* GetSizes() const { return sizes_; } int64 dim_size(int index) const { return sizes_[index]; } int64 tf_dim_size(int index) const { return sizes_[tf_to_mkl_dim_map_[index]]; } const size_t* GetStrides() const { return strides_; } const size_t* GetTfToMklDimMap() const { return tf_to_mkl_dim_map_; } size_t tf_dim_idx(int index) const { return tf_to_mkl_dim_map_[index]; } // Query TF-MKL dimension ordering map and check if Tensorflow dimension 'd' // corresponds to MKL's Channel dimension. bool IsMklChannelDim(int d) const { return tf_dim_idx(d) == MklDims::C; } // Query TF-MKL dimension ordering map and check if Tensorflow dimension 'd' // corresponds to MKL's Batch dimension. bool IsMklBatchDim(int d) const { return tf_dim_idx(d) == MklDims::N; } // Query TF-MKL dimension ordering map and check if Tensorflow dimension 'd' // corresponds to MKL's Width dimension. bool IsMklWidthDim(int d) const { return tf_dim_idx(d) == MklDims::W; } // Query TF-MKL dimension ordering map and check if Tensorflow dimension 'd' // corresponds to MKL's Height dimension. bool IsMklHeightDim(int d) const { return tf_dim_idx(d) == MklDims::H; } // Check if the TF-Mkl dimension ordering map specifies if the input // tensor is in NCHW format. bool IsTensorInNCHWFormat() const { TensorFormat data_format = FORMAT_NCHW; return (IsMklBatchDim(GetTensorDimIndex<2>(data_format, 'N')) && IsMklChannelDim(GetTensorDimIndex<2>(data_format, 'C')) && IsMklHeightDim(GetTensorDimIndex<2>(data_format, 'H')) && IsMklWidthDim(GetTensorDimIndex<2>(data_format, 'W'))); } // Check if the TF-Mkl dimension ordering map specifies if the input // tensor is in NHWC format. bool IsTensorInNHWCFormat() const { TensorFormat data_format = FORMAT_NHWC; return (IsMklBatchDim(GetTensorDimIndex<2>(data_format, 'N')) && IsMklChannelDim(GetTensorDimIndex<2>(data_format, 'C')) && IsMklHeightDim(GetTensorDimIndex<2>(data_format, 'H')) && IsMklWidthDim(GetTensorDimIndex<2>(data_format, 'W'))); } void GetConvertedFlatData(dnnLayout_t targetLayout, void* input, void* output) const { dnnLayout_t curLayout; if (isMklTensor_) curLayout = mklLayout_; else curLayout = tfLayout_; dnnPrimitive_t convert; CHECK_EQ(dnnConversionCreate_F32(&convert, curLayout, targetLayout), E_SUCCESS); CHECK_EQ(dnnConversionExecute_F32(convert, input, output), E_SUCCESS); CHECK_EQ(dnnDelete_F32(convert), E_SUCCESS); } // The following methods are used for serializing and de-serializing the // contents of the mklshape object. // The data is serialized in this order // isMklTensor_ // dimension_ // sizes_ // strides_ // mklLayout_ // tfLayout_ // tf_to_mkl_dim_map_ #define SIZE_OF_MKL_DNN_BUF \ (dnnLayoutSerializationBufferSize_F32()) // Size of buffer needed to // serialize dnn_layout pointer // Size of buffer to hold the serialized object, the size is computed as // follows sizeof(isMklTensor_) + sizeof(dimension_) + sizeof(sizes_) + // sizeof(strides_) // + sizeof(mklLayout_ buffer) + sizeof(tfLayout_ buffer) // + sizeof(tf_to_mkl_dim_map_) #define SIZE_OF_MKL_SERIAL_DATA(dims) \ (2 * sizeof(size_t) + 3 * dims * sizeof(size_t) + 2 * SIZE_OF_MKL_DNN_BUF) // First we need to define some macro for offsets into the serial buffer where // different elements of Mklshape is written/read from #define IS_MKL_TENSOR_OFFSET 0 // Location from start of buffer where isMklTensor_ is serialized #define DIMS_OFFSET \ (IS_MKL_TENSOR_OFFSET + sizeof(size_t)) // Location of dimension_ // Location of sizes. Note dim is not used here, left here // to make macros consistent. #define SIZES_OFFSET(dims) (DIMS_OFFSET + sizeof(size_t)) #define STRIDES_OFFSET(dims) \ (SIZES_OFFSET(dims) + dims * sizeof(size_t)) // Location of strides #define MKL_LAYOUT_OFFSET(dims) \ (STRIDES_OFFSET(dims) + dims * sizeof(size_t)) // Location of mklLayout_ #define TF_LAYOUT_OFFSET(dims) \ (MKL_LAYOUT_OFFSET(dims) + SIZE_OF_MKL_DNN_BUF) // Location of tfLayout_ // Location of tf_to_mkl_dim_map_ #define TF_TO_MKL_DIM_MAP_OFFSET(dims) \ (TF_LAYOUT_OFFSET(dims) + SIZE_OF_MKL_DNN_BUF) // TODO(agramesh1) make sure to create a const to share with rewrite pass // for min size of MKL metadata tensor. void DeSerializeMklShape(const unsigned char* buf, size_t buf_size) { CHECK(buf_size >= sizeof(size_t)) << "Bufsize too small in DeSerialize"; // Make sure buffer holds at least isMklTensor_ isMklTensor_ = *reinterpret_cast<const size_t*>(buf + IS_MKL_TENSOR_OFFSET) != 0; if (isMklTensor_) { // If it is an MKL Tensor then read the rest dimension_ = *(reinterpret_cast<const size_t*>(buf + DIMS_OFFSET)); CHECK(buf_size >= SIZE_OF_MKL_SERIAL_DATA(dimension_)) << "Bufsize too small in DeSerialize"; sizes_ = new size_t[dimension_]; strides_ = new size_t[dimension_]; tf_to_mkl_dim_map_ = new size_t[dimension_]; for (int i = 0; i < dimension_; i++) { sizes_[i] = reinterpret_cast<const size_t*>(buf + SIZES_OFFSET(dimension_))[i]; strides_[i] = reinterpret_cast<const size_t*>( buf + STRIDES_OFFSET(dimension_))[i]; tf_to_mkl_dim_map_[i] = reinterpret_cast<const size_t*>( buf + TF_TO_MKL_DIM_MAP_OFFSET(dimension_))[i]; } CHECK_EQ(dnnLayoutDeserialize_F32(&mklLayout_, buf + MKL_LAYOUT_OFFSET(dimension_)), E_SUCCESS); CHECK_EQ(dnnLayoutDeserialize_F32(&tfLayout_, buf + TF_LAYOUT_OFFSET(dimension_)), E_SUCCESS); } } void SerializeMklShape(unsigned char* buf, size_t buf_size) const { CHECK(buf_size >= SIZE_OF_MKL_SERIAL_DATA(dimension_)) << "Bufsize too small to Serialize"; *reinterpret_cast<size_t*>(buf + IS_MKL_TENSOR_OFFSET) = isMklTensor_ ? 1 : 0; if (isMklTensor_) { *(reinterpret_cast<size_t*>(buf + DIMS_OFFSET)) = dimension_; for (int i = 0; i < dimension_; i++) { reinterpret_cast<size_t*>(buf + SIZES_OFFSET(dimension_))[i] = sizes_[i]; reinterpret_cast<size_t*>(buf + STRIDES_OFFSET(dimension_))[i] = strides_[i]; reinterpret_cast<size_t*>(buf + TF_TO_MKL_DIM_MAP_OFFSET(dimension_))[i] = tf_to_mkl_dim_map_[i]; } CHECK_EQ(dnnLayoutSerialize_F32(mklLayout_, buf + MKL_LAYOUT_OFFSET(dimension_)), E_SUCCESS); CHECK_EQ( dnnLayoutSerialize_F32(tfLayout_, buf + TF_LAYOUT_OFFSET(dimension_)), E_SUCCESS); } } private: bool isMklTensor_ = false; // Flag to indicate if the tensor is an MKL tensor or not dnnLayout_t mklLayout_ = nullptr; // Pointer to the MKL layout dnnLayout_t tfLayout_ = nullptr; // Pointer to layout of corresponding // Tensorflow tensor, used when conversion from MKL to standard tensor size_t dimension_ = 0; size_t* sizes_ = nullptr; // Required by MKL for conversions size_t* strides_ = nullptr; // Required by MKL for conversions size_t* tf_to_mkl_dim_map_ = nullptr; // TF dimension corresponding to this MKL dimension }; #else // Forward decl TensorFormat MklDnn3DDataFormatToTFDataFormat(memory::format format); TensorFormat MklDnnDataFormatToTFDataFormat(memory::format format); memory::dims CalculateTFStrides(const memory::dims& dims_tf_order); memory::desc CreateBlockedMemDescHelper(const memory::dims& dim, const memory::dims& strides, memory::data_type dtype); class MklDnnShape { private: typedef struct { /// Flag to indicate if the tensor is an MKL tensor or not bool is_mkl_tensor_ = false; /// Number of dimensions in Tensorflow format size_t dimension_ = 0; /// Required by MKLDNN for conversions mkldnn_dims_t sizes_; // Required by MKL for conversions memory::format tf_data_format_ = memory::format::format_undef; memory::data_type T_ = memory::data_type::data_undef; // MKL layout mkldnn_memory_desc_t mkl_md_; /// TF dimension corresponding to this MKL dimension mkldnn_dims_t map_; } MklShapeData; MklShapeData data_; typedef std::remove_extent<mkldnn_dims_t>::type mkldnn_dim_t; #define INVALID_DIM_SIZE -1 public: MklDnnShape() { for (size_t i = 0; i < sizeof(data_.sizes_) / sizeof(data_.sizes_[0]); ++i) { data_.sizes_[i] = -1; } for (size_t i = 0; i < sizeof(data_.map_) / sizeof(data_.map_[0]); ++i) { data_.map_[i] = -1; } } ~MklDnnShape() {} TF_DISALLOW_COPY_AND_ASSIGN(MklDnnShape); // Cannot copy /// Helper function to compare memory::desc objects for MklDnn. /// May be this should go into MklDnn directly. inline bool CompareMklDnnLayouts(const memory::desc& md1, const memory::desc& md2) const { mkldnn_memory_desc_t mdd1 = md1.data; mkldnn_memory_desc_t mdd2 = md2.data; const char* d1 = reinterpret_cast<const char*>(&mdd1); const char* d2 = reinterpret_cast<const char*>(&mdd2); size_t md_size = sizeof(mdd1); for (size_t i = 0; i < md_size; i++) { if (*d1++ != *d2++) { return false; } } return true; } /// Equality function for MklDnnShape objects /// @return true if both are equal; false otherwise. inline bool operator==(const MklDnnShape& input_shape) const { if (this->IsMklTensor() != input_shape.IsMklTensor()) { return false; } // If input tensors are in Mkl layout, then we check for dimensions and // sizes. if (this->IsMklTensor()) { return this->GetTfShape() == input_shape.GetTfShape() && CompareMklDnnLayouts(this->GetMklLayout(), input_shape.GetMklLayout()); } return true; } /// Equality operator for MklDnnShape and TFShape. /// Returns: true if TF shapes for both are the same, false otherwise inline bool operator==(const TensorShape& input_shape) const { if (!this->IsMklTensor()) { return false; } return this->GetTfShape() == input_shape; } inline const bool IsMklTensor() const { return data_.is_mkl_tensor_; } inline void SetMklTensor(bool is_mkl_tensor) { data_.is_mkl_tensor_ = is_mkl_tensor; } inline void SetDimensions(const size_t dimension) { data_.dimension_ = dimension; } inline size_t GetDimension(char dimension) const { int index = GetMklDnnTensorDimIndex(dimension); CHECK(index >= 0 && index < this->GetDimension()) << "Invalid index from the dimension: " << index << ", " << dimension; return this->DimSize(index); } inline size_t GetDimension3D(char dimension) const { int index = GetMklDnnTensor3DDimIndex(dimension); CHECK(index >= 0 && index < this->GetDimension()) << "Invalid index from the dimension: " << index << ", " << dimension; return this->DimSize(index); } inline int32 GetMklDnnTensorDimIndex(char dimension) const { switch (dimension) { case 'N': return MklDnnDims::Dim_N; case 'C': return MklDnnDims::Dim_C; case 'H': return MklDnnDims::Dim_H; case 'W': return MklDnnDims::Dim_W; default: LOG(FATAL) << "Invalid dimension: " << dimension; return -1; // Avoid compiler warning about missing return value } } inline int32 GetMklDnnTensor3DDimIndex(char dimension) const { switch (dimension) { case 'N': return MklDnnDims3D::Dim3d_N; case 'C': return MklDnnDims3D::Dim3d_C; case 'D': return MklDnnDims3D::Dim3d_D; case 'H': return MklDnnDims3D::Dim3d_H; case 'W': return MklDnnDims3D::Dim3d_W; default: LOG(FATAL) << "Invalid dimension: " << dimension; return -1; // Avoid compiler warning about missing return value } } inline size_t GetDimension() const { return data_.dimension_; } inline const int* GetSizes() const { return reinterpret_cast<const int*>(&data_.sizes_[0]); } // Returns an mkldnn::memory::dims object that contains the sizes of this // MklDnnShape object. inline memory::dims GetSizesAsMklDnnDims() const { memory::dims retVal; if (data_.is_mkl_tensor_) { size_t dimensions = sizeof(data_.sizes_) / sizeof(data_.sizes_[0]); for (size_t i = 0; i < dimensions; i++) { if (data_.sizes_[i] != INVALID_DIM_SIZE) retVal.push_back(data_.sizes_[i]); } } else { CHECK_EQ(data_.is_mkl_tensor_, true); } return retVal; } inline int64 DimSize(int index) const { CHECK_LT(index, sizeof(data_.sizes_) / sizeof(data_.sizes_[0])); return data_.sizes_[index]; } /// Return TensorShape that describes the Tensorflow shape of the tensor /// represented by this MklShape. inline TensorShape GetTfShape() const { CHECK_EQ(data_.is_mkl_tensor_, true); std::vector<int32> shape(data_.dimension_, -1); if (data_.tf_data_format_ != memory::format::blocked) { for (size_t idx = 0; idx < data_.dimension_; ++idx) { shape[idx] = data_.sizes_[TfDimIdx(idx)]; } } else { // If Tensorflow shape is in Blocked format, then we don't have dimension // map for it. So we just create Tensorflow shape from sizes in the // specified order. for (size_t idx = 0; idx < data_.dimension_; ++idx) { shape[idx] = data_.sizes_[idx]; } } TensorShape ts; bool ret = TensorShapeUtils::MakeShape(shape, &ts).ok(); CHECK_EQ(ret, true); return ts; } inline void SetElemType(memory::data_type dt) { data_.T_ = dt; } inline const memory::data_type GetElemType() { return data_.T_; } inline void SetMklLayout(memory::primitive_desc* pd) { CHECK_NOTNULL(pd); data_.mkl_md_ = pd->desc().data; } inline void SetMklLayout(memory::desc* md) { CHECK_NOTNULL(md); data_.mkl_md_ = md->data; } inline const memory::desc GetMklLayout() const { return memory::desc(data_.mkl_md_); } inline memory::format GetTfDataFormat() const { return data_.tf_data_format_; } /// We don't create primitive_descriptor for TensorFlow layout now. /// We use lazy evaluation and create it only when needed. Input format can /// also be Blocked format. inline void SetTfLayout(size_t dims, const memory::dims& sizes, memory::format format) { CHECK_EQ(dims, sizes.size()); data_.dimension_ = dims; for (size_t ii = 0; ii < dims; ii++) { data_.sizes_[ii] = sizes[ii]; } data_.tf_data_format_ = format; if (format != memory::format::blocked) { SetTfDimOrder(dims, format); } } inline const memory::desc GetTfLayout() const { memory::dims dims; for (size_t ii = 0; ii < data_.dimension_; ii++) { dims.push_back(data_.sizes_[ii]); } // Create Blocked memory desc if input TF format was set like that. if (data_.tf_data_format_ == memory::format::blocked) { auto strides = CalculateTFStrides(dims); return CreateBlockedMemDescHelper(dims, strides, data_.T_); } else { return memory::desc(dims, data_.T_, data_.tf_data_format_); } } inline const memory::desc GetCurLayout() const { return IsMklTensor() ? GetMklLayout() : GetTfLayout(); } // nhasabni - I've removed SetTfDimOrder that was setting default order in // case of MKL-ML. We don't need a case of default dimension order because // when an operator that does not get data_format attribute gets all inputs // in Tensorflow format, it will produce output in Tensorflow format. inline void SetTfDimOrder(const size_t dimension, const mkldnn_dims_t map) { CHECK(dimension == data_.dimension_); for (size_t ii = 0; ii < dimension; ii++) { data_.map_[ii] = map[ii]; } } inline void SetTfDimOrder(const size_t dimension, TensorFormat data_format) { if (dimension == 5) { CHECK(dimension == data_.dimension_); data_.map_[GetTensorDimIndex<3>(data_format, '0')] = MklDnnDims3D::Dim3d_D; data_.map_[GetTensorDimIndex<3>(data_format, '1')] = MklDnnDims3D::Dim3d_H; data_.map_[GetTensorDimIndex<3>(data_format, '2')] = MklDnnDims3D::Dim3d_W; data_.map_[GetTensorDimIndex<3>(data_format, 'C')] = MklDnnDims3D::Dim3d_C; data_.map_[GetTensorDimIndex<3>(data_format, 'N')] = MklDnnDims3D::Dim3d_N; } else { CHECK_EQ(dimension, 4); CHECK(dimension == data_.dimension_); data_.map_[GetTensorDimIndex<2>(data_format, 'W')] = MklDnnDims::Dim_W; data_.map_[GetTensorDimIndex<2>(data_format, 'H')] = MklDnnDims::Dim_H; data_.map_[GetTensorDimIndex<2>(data_format, 'C')] = MklDnnDims::Dim_C; data_.map_[GetTensorDimIndex<2>(data_format, 'N')] = MklDnnDims::Dim_N; } } inline void SetTfDimOrder(const size_t dimension, memory::format format) { TensorFormat data_format = MklDnnDataFormatToTFDataFormat(format); SetTfDimOrder(dimension, data_format); } inline const mkldnn_dim_t* GetTfToMklDimMap() const { return &data_.map_[0]; } inline size_t TfDimIdx(int index) const { return data_.map_[index]; } inline int64 TfDimSize(int index) const { return data_.sizes_[TfDimIdx(index)]; } /// Query TF-MKL dimension ordering map and check if Tensorflow dimension 'd' /// corresponds to MKL's Channel dimension. inline bool IsMklChannelDim(int d) const { return TfDimIdx(d) == MklDnnDims::Dim_C; } /// Query TF-MKL dimension ordering map and check if Tensorflow dimension 'd' /// corresponds to MKL's Batch dimension. inline bool IsMklBatchDim(int d) const { return TfDimIdx(d) == MklDnnDims::Dim_N; } /// Query TF-MKL dimension ordering map and check if Tensorflow dimension 'd' /// corresponds to MKL's Width dimension. inline bool IsMklWidthDim(int d) const { return TfDimIdx(d) == MklDnnDims::Dim_W; } /// Query TF-MKL dimension ordering map and check if Tensorflow dimension 'd' /// corresponds to MKL's Height dimension. inline bool IsMklHeightDim(int d) const { return TfDimIdx(d) == MklDnnDims::Dim_H; } /// Check if the TF-Mkl dimension ordering map specifies if the input /// tensor is in NCHW format. inline bool IsTensorInNCHWFormat() const { TensorFormat data_format = FORMAT_NCHW; return (IsMklBatchDim(GetTensorDimIndex<2>(data_format, 'N')) && IsMklChannelDim(GetTensorDimIndex<2>(data_format, 'C')) && IsMklHeightDim(GetTensorDimIndex<2>(data_format, 'H')) && IsMklWidthDim(GetTensorDimIndex<2>(data_format, 'W'))); } /// Check if the TF-Mkl dimension ordering map specifies if the input /// tensor is in NHWC format. inline bool IsTensorInNHWCFormat() const { TensorFormat data_format = FORMAT_NHWC; return (IsMklBatchDim(GetTensorDimIndex<2>(data_format, 'N')) && IsMklChannelDim(GetTensorDimIndex<2>(data_format, 'C')) && IsMklHeightDim(GetTensorDimIndex<2>(data_format, 'H')) && IsMklWidthDim(GetTensorDimIndex<2>(data_format, 'W'))); } /// The following methods are used for serializing and de-serializing the /// contents of the mklshape object. /// The data is serialized in this order /// is_mkl_tensor_ : dimension_ : sizes_ : map_: format_ : T_ : mkl_pd_; /// Size of buffer to hold the serialized object, the size is computed by /// following above mentioned order inline size_t GetSerializeBufferSize() const { return sizeof(MklShapeData); } void SerializeMklDnnShape(unsigned char* buf, size_t buf_size) const { CHECK(buf_size >= GetSerializeBufferSize()) << "Buffer size is too small to SerializeMklDnnShape"; *reinterpret_cast<MklShapeData*>(buf) = data_; } void DeSerializeMklDnnShape(const unsigned char* buf, size_t buf_size) { // Make sure buffer holds at least is_mkl_tensor_. CHECK(buf_size >= sizeof(data_.is_mkl_tensor_)) << "Buffer size is too small in DeSerializeMklDnnShape"; const bool is_mkl_tensor = *reinterpret_cast<const bool*>(buf); if (is_mkl_tensor) { // If it is an MKL Tensor then read the rest CHECK(buf_size >= GetSerializeBufferSize()) << "Buffer size is too small in DeSerializeMklDnnShape"; data_ = *reinterpret_cast<const MklShapeData*>(buf); } } }; #endif // List of MklShape objects. Used in Concat/Split layers. #ifndef INTEL_MKL_ML_ONLY typedef std::vector<MklDnnShape> MklDnnShapeList; #else typedef std::vector<MklShape> MklShapeList; #endif #ifdef INTEL_MKL_ML_ONLY // Check if all tensors specified by MklShapes are MKL tensors. inline bool AreAllMklTensors(const MklShapeList& shapes) { for (auto& s : shapes) { if (!s.IsMklTensor()) { return false; } } return true; } template <typename T> inline Tensor ConvertMklToTF(OpKernelContext* context, const Tensor& mkl_tensor, const MklShape& mkl_shape) { Tensor output_tensor; TensorShape output_shape; for (size_t j = 0; j < mkl_shape.GetDimension(); j++) { // Outermost to innermost dimension output_shape.AddDim(mkl_shape.GetSizes()[mkl_shape.tf_dim_idx(j)]); } // Allocate output tensor. context->allocate_temp(DataTypeToEnum<T>::v(), output_shape, &output_tensor); dnnLayout_t output_layout = static_cast<dnnLayout_t>(mkl_shape.GetTfLayout()); void* input_buffer = const_cast<T*>(mkl_tensor.flat<T>().data()); void* output_buffer = const_cast<T*>(output_tensor.flat<T>().data()); if (mkl_tensor.NumElements() != 0) { mkl_shape.GetConvertedFlatData(output_layout, input_buffer, output_buffer); } return output_tensor; } #else using mkldnn::stream; template <typename T> class MklDnnData; template <typename T> inline Tensor ConvertMklToTF(OpKernelContext* context, const Tensor& mkl_tensor, const MklDnnShape& mkl_shape) { Tensor output_tensor; try { if (!mkl_shape.IsMklTensor()) return mkl_tensor; // return input since it is already TF tensor TensorShape output_shape = mkl_shape.GetTfShape(); // Allocate output tensor. context->allocate_temp(DataTypeToEnum<T>::v(), output_shape, &output_tensor); auto cpu_engine = engine(engine::cpu, 0); MklDnnData<T> input(&cpu_engine); // Get Mkl layout of input tensor. auto input_mkl_md = mkl_shape.GetMklLayout(); auto output_tf_md = mkl_shape.GetTfLayout(); auto output_tf_pd = memory::primitive_desc(output_tf_md, cpu_engine); input.SetUsrMem(input_mkl_md, &mkl_tensor); // reorder if (input.IsReorderNeeded(output_tf_pd)) { std::vector<primitive> net; CHECK_EQ(input.CheckReorderToOpMem(output_tf_pd, &output_tensor, &net), true); stream(stream::kind::eager).submit(net).wait(); } else { // If not, just forward input tensor to output tensor. CHECK(output_tensor.CopyFrom(mkl_tensor, output_shape)); } } catch (mkldnn::error& e) { string error_msg = "Status: " + std::to_string(e.status) + ", message: " + string(e.message) + ", in file " + string(__FILE__) + ":" + std::to_string(__LINE__); LOG(FATAL) << "Operation received an exception: " << error_msg; } return output_tensor; } #endif // Get the MKL shape from the second string tensor #ifdef INTEL_MKL_ML_ONLY inline void GetMklShape(OpKernelContext* ctext, int n, MklShape* mklshape) { mklshape->DeSerializeMklShape( ctext->input(GetTensorMetaDataIndex(n, ctext->num_inputs())) .flat<uint8>() .data(), ctext->input(GetTensorMetaDataIndex(n, ctext->num_inputs())) .flat<uint8>() .size() * sizeof(uint8)); } #else inline void GetMklShape(OpKernelContext* ctext, int n, MklDnnShape* mklshape) { mklshape->DeSerializeMklDnnShape( ctext->input(GetTensorMetaDataIndex(n, ctext->num_inputs())) .flat<uint8>() .data(), ctext->input(GetTensorMetaDataIndex(n, ctext->num_inputs())) .flat<uint8>() .size() * sizeof(uint8)); } #endif // Gets the actual input inline const Tensor& MklGetInput(OpKernelContext* ctext, int n) { return ctext->input(GetTensorDataIndex(n, ctext->num_inputs())); } inline void GetMklInputList(OpKernelContext* ctext, StringPiece name, OpInputList* input_tensors) { CHECK_NOTNULL(input_tensors); ctext->input_list(name, input_tensors); } #ifdef INTEL_MKL_ML_ONLY inline void GetMklShapeList(OpKernelContext* ctext, StringPiece name, MklShapeList* mkl_shapes) { OpInputList input_mkl_tensors; GetMklInputList(ctext, strings::StrCat("mkl_", name), &input_mkl_tensors); for (int i = 0; i < input_mkl_tensors.size(); i++) { (*mkl_shapes)[i].DeSerializeMklShape( input_mkl_tensors[i].flat<uint8>().data(), input_mkl_tensors[i].flat<uint8>().size() * sizeof(uint8)); } } #else inline void GetMklShapeList(OpKernelContext* ctext, StringPiece name, MklDnnShapeList* mkl_shapes) { OpInputList input_mkl_tensors; GetMklInputList(ctext, strings::StrCat("mkl_", name), &input_mkl_tensors); for (int i = 0; i < input_mkl_tensors.size(); i++) { (*mkl_shapes)[i].DeSerializeMklDnnShape( input_mkl_tensors[i].flat<uint8>().data(), input_mkl_tensors[i].flat<uint8>().size() * sizeof(uint8)); } } #endif #ifndef INTEL_MKL_ML_ONLY /// Get shape of input tensor pointed by 'input_idx' in TensorShape format. /// If the input tensor is in MKL layout, then obtains TensorShape from /// MklShape. inline TensorShape GetTfShape(OpKernelContext* context, size_t input_idx) { // Sanity check. CHECK_NOTNULL(context); CHECK_LT(input_idx, context->num_inputs()); MklDnnShape input_mkl_shape; GetMklShape(context, input_idx, &input_mkl_shape); if (input_mkl_shape.IsMklTensor()) { return input_mkl_shape.GetTfShape(); } else { const Tensor& t = MklGetInput(context, input_idx); return t.shape(); } } #endif #ifdef INTEL_MKL_ML_ONLY // Allocate the second output tensor that will contain // the MKL shape serialized inline void AllocateOutputSetMklShape(OpKernelContext* ctext, int n, const MklShape& mkl_shape) { Tensor* second_tensor = nullptr; TensorShape second_shape; second_shape.AddDim(SIZE_OF_MKL_SERIAL_DATA(mkl_shape.GetDimension())); OP_REQUIRES_OK(ctext, ctext->allocate_output( GetTensorMetaDataIndex(n, ctext->num_outputs()), second_shape, &second_tensor)); mkl_shape.SerializeMklShape( second_tensor->flat<uint8>().data(), second_tensor->flat<uint8>().size() * sizeof(uint8)); } #else // Allocate the second output tensor that will contain // the MKL shape serialized inline void AllocateOutputSetMklShape(OpKernelContext* ctext, int n, const MklDnnShape& mkl_shape) { Tensor* second_tensor = nullptr; TensorShape second_shape; second_shape.AddDim(mkl_shape.GetSerializeBufferSize()); OP_REQUIRES_OK(ctext, ctext->allocate_output( GetTensorMetaDataIndex(n, ctext->num_outputs()), second_shape, &second_tensor)); mkl_shape.SerializeMklDnnShape( second_tensor->flat<uint8>().data(), second_tensor->flat<uint8>().size() * sizeof(uint8)); } #endif #ifdef INTEL_MKL_ML_ONLY // Allocate the output tensor, create a second output tensor that will contain // the MKL shape serialized inline void AllocateOutputSetMklShape(OpKernelContext* ctext, int n, Tensor** output, const TensorShape& tf_shape, const MklShape& mkl_shape) { Tensor* second_tensor = nullptr; TensorShape second_shape; second_shape.AddDim(SIZE_OF_MKL_SERIAL_DATA(mkl_shape.GetDimension())); OP_REQUIRES_OK( ctext, ctext->allocate_output(GetTensorDataIndex(n, ctext->num_outputs()), tf_shape, output)); OP_REQUIRES_OK(ctext, ctext->allocate_output( GetTensorMetaDataIndex(n, ctext->num_outputs()), second_shape, &second_tensor)); mkl_shape.SerializeMklShape( second_tensor->flat<uint8>().data(), second_tensor->flat<uint8>().size() * sizeof(uint8)); } #else // Allocate the output tensor, create a second output tensor that will contain // the MKL shape serialized inline void AllocateOutputSetMklShape(OpKernelContext* ctext, int n, Tensor** output, const TensorShape& tf_shape, const MklDnnShape& mkl_shape) { Tensor* second_tensor = nullptr; TensorShape second_shape; second_shape.AddDim(mkl_shape.GetSerializeBufferSize()); OP_REQUIRES_OK( ctext, ctext->allocate_output(GetTensorDataIndex(n, ctext->num_outputs()), tf_shape, output)); OP_REQUIRES_OK(ctext, ctext->allocate_output( GetTensorMetaDataIndex(n, ctext->num_outputs()), second_shape, &second_tensor)); mkl_shape.SerializeMklDnnShape( second_tensor->flat<uint8>().data(), second_tensor->flat<uint8>().size() * sizeof(uint8)); } #endif // Allocates a temp tensor and returns the data buffer for temporary storage. // Currently #ifndef INTEL_MKL_ML_ONLY template <typename T> inline void AllocTmpBuffer(OpKernelContext* context, Tensor* tensor_out, const memory::primitive_desc& pd, void** buf_out) { TensorShape tf_shape; tf_shape.AddDim(pd.get_size() / sizeof(T) + 1); OP_REQUIRES_OK(context, context->allocate_temp(DataTypeToEnum<T>::v(), tf_shape, tensor_out)); *buf_out = static_cast<void*>(tensor_out->flat<T>().data()); } #else inline void AllocTmpBuffer(OpKernelContext* context, Tensor* tensor_out, dnnLayout_t lt_buff, void** buf_out) { TensorShape tf_shape; tf_shape.AddDim( dnnLayoutGetMemorySize_F32(static_cast<dnnLayout_t>(lt_buff)) / sizeof(float) + 1); OP_REQUIRES_OK(context, context->allocate_temp(DataTypeToEnum<float>::v(), tf_shape, tensor_out)); *buf_out = static_cast<void*>(tensor_out->flat<float>().data()); } #endif template <typename T> inline void AllocTmpBuffer(OpKernelContext* context, Tensor* tensor_out, TensorShape tf_shape) { OP_REQUIRES_OK(context, context->allocate_temp(DataTypeToEnum<T>::v(), tf_shape, tensor_out)); } inline void GetStridesFromSizes(TensorFormat data_format, size_t* strides, const size_t* sizes) { // MKL requires strides in NCHW if (data_format == FORMAT_NHWC) { strides[0] = sizes[2]; strides[1] = sizes[0] * sizes[2]; strides[2] = 1; strides[3] = sizes[0] * sizes[1] * sizes[2]; } else { strides[0] = 1; strides[1] = sizes[0]; strides[2] = sizes[0] * sizes[1]; strides[3] = sizes[0] * sizes[1] * sizes[2]; } } #ifdef INTEL_MKL_ML_ONLY inline void MklSizesToTFSizes(OpKernelContext* context, TensorFormat data_format_, const MklShape& mkl_shape, TensorShape* tf_shape) { size_t tf_dim = mkl_shape.GetDimension(); const size_t* tf_sizes = mkl_shape.GetSizes(); OP_REQUIRES(context, tf_dim == 4, errors::InvalidArgument("MKLSizesToTFSizes: size must be 4-dim")); std::vector<int32> sizes; sizes.push_back(tf_sizes[3]); if (data_format_ == FORMAT_NHWC) { sizes.push_back(tf_sizes[1]); sizes.push_back(tf_sizes[0]); sizes.push_back(tf_sizes[2]); } else { sizes.push_back(tf_sizes[2]); sizes.push_back(tf_sizes[1]); sizes.push_back(tf_sizes[0]); } OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape(sizes, tf_shape)); } #endif inline int32 GetMklTensorDimIndex(char dimension) { switch (dimension) { case 'N': return MklDims::N; case 'C': return MklDims::C; case 'H': return MklDims::H; case 'W': return MklDims::W; default: LOG(FATAL) << "Invalid dimension: " << dimension; return -1; // Avoid compiler warning about missing return value } } #ifdef INTEL_MKL_ML_ONLY inline int64 GetMklTensorDim(const MklShape& mkl_shape, char dimension) { int index = GetMklTensorDimIndex(dimension); CHECK(index >= 0 && index < mkl_shape.GetDimension()) << "Invalid index from the dimension: " << index << ", " << dimension; return mkl_shape.dim_size(index); } #endif inline void CopyMklTensorInToOut(OpKernelContext* context, int idx_in, int idx_out) { int num_inputs = context->num_inputs(); int num_outputs = context->num_outputs(); int idx_data_in = GetTensorDataIndex(idx_in, num_inputs); int idx_meta_in = GetTensorMetaDataIndex(idx_in, num_inputs); int idx_data_out = GetTensorDataIndex(idx_out, num_outputs); int idx_meta_out = GetTensorMetaDataIndex(idx_out, num_outputs); const Tensor& data = context->input(idx_data_in); const Tensor& meta = context->input(idx_meta_in); Tensor output(data.dtype()); Tensor meta_output(meta.dtype()); // TODO(intel_tf): alternatively, call forward_input_to_output_with_shape(...) CHECK(output.CopyFrom(data, data.shape())); CHECK(meta_output.CopyFrom(meta, meta.shape())); context->set_output(idx_data_out, output); context->set_output(idx_meta_out, meta_output); } #ifdef INTEL_MKL_ML_ONLY inline void CopyTfTensorInToOutWithShape(OpKernelContext* context, int idx_in, int idx_out, const TensorShape& shape) { int num_inputs = context->num_inputs(); int num_outputs = context->num_outputs(); int idx_data_in = GetTensorDataIndex(idx_in, num_inputs); int idx_data_out = GetTensorDataIndex(idx_out, num_outputs); const Tensor& data = context->input(idx_data_in); MklShape mkl_shape_output; mkl_shape_output.SetMklTensor(false); AllocateOutputSetMklShape(context, idx_out, mkl_shape_output); Tensor output(data.dtype()); // TODO(intel_tf): alternatively, call forward_input_to_output_with_shape(...) CHECK(output.CopyFrom(data, shape)); context->set_output(idx_data_out, output); } #else inline void CopyTfTensorInToOutWithShape(OpKernelContext* context, int idx_in, int idx_out, const TensorShape& shape) { int num_inputs = context->num_inputs(); int num_outputs = context->num_outputs(); int idx_data_in = GetTensorDataIndex(idx_in, num_inputs); int idx_data_out = GetTensorDataIndex(idx_out, num_outputs); const Tensor& data = context->input(idx_data_in); MklDnnShape mkl_shape_output; mkl_shape_output.SetMklTensor(false); AllocateOutputSetMklShape(context, idx_out, mkl_shape_output); Tensor output(data.dtype()); // TODO(intel_tf): alternatively, call forward_input_to_output_with_shape(...) CHECK(output.CopyFrom(data, shape)); context->set_output(idx_data_out, output); } #endif #ifdef INTEL_MKL_ML_ONLY inline void ForwardTfTensorInToOut(OpKernelContext* context, int idx_in, int idx_out) { int num_inputs = context->num_inputs(); int num_outputs = context->num_outputs(); int idx_data_in = GetTensorDataIndex(idx_in, num_inputs); int idx_data_out = GetTensorDataIndex(idx_out, num_outputs); MklShape mkl_shape_output; mkl_shape_output.SetMklTensor(false); AllocateOutputSetMklShape(context, idx_out, mkl_shape_output); if (IsRefType(context->input_dtype(idx_data_in))) { context->forward_ref_input_to_ref_output(idx_data_in, idx_data_out); } else { context->set_output(idx_data_out, context->input(idx_data_in)); } } #else inline void ForwardTfTensorInToOut(OpKernelContext* context, int idx_in, int idx_out) { int num_inputs = context->num_inputs(); int num_outputs = context->num_outputs(); int idx_data_in = GetTensorDataIndex(idx_in, num_inputs); int idx_data_out = GetTensorDataIndex(idx_out, num_outputs); MklDnnShape dnn_shape_output; dnn_shape_output.SetMklTensor(false); AllocateOutputSetMklShape(context, idx_out, dnn_shape_output); if (IsRefType(context->input_dtype(idx_data_in))) { context->forward_ref_input_to_ref_output(idx_data_in, idx_data_out); } else { context->set_output(idx_data_out, context->input(idx_data_in)); } } #endif inline void ForwardMklTensorInToOut(OpKernelContext* context, int idx_in, int idx_out) { int num_inputs = context->num_inputs(); int num_outputs = context->num_outputs(); int idx_data_in = GetTensorDataIndex(idx_in, num_inputs); int idx_meta_in = GetTensorMetaDataIndex(idx_in, num_inputs); int idx_data_out = GetTensorDataIndex(idx_out, num_outputs); int idx_meta_out = GetTensorMetaDataIndex(idx_out, num_outputs); if (IsRefType(context->input_dtype(idx_data_in))) { context->forward_ref_input_to_ref_output(idx_data_in, idx_data_out); context->forward_ref_input_to_ref_output(idx_meta_in, idx_meta_out); } else { context->set_output(idx_data_out, context->input(idx_data_in)); context->set_output(idx_meta_out, context->input(idx_meta_in)); } } #ifndef INTEL_MKL_ML_ONLY // Set a dummy MKLDNN shape (called when the output is in TF format) inline void SetDummyMklDnnShapeOutput(OpKernelContext* context, uint32 idx_data_out) { MklDnnShape mkl_shape_output; mkl_shape_output.SetMklTensor(false); AllocateOutputSetMklShape(context, idx_data_out, mkl_shape_output); } inline void ForwardMklTensorInToOutWithMklShape(OpKernelContext* context, int idx_in, int idx_out, const MklDnnShape& mkl_shape) { int num_inputs = context->num_inputs(); int num_outputs = context->num_outputs(); int idx_data_in = GetTensorDataIndex(idx_in, num_inputs); int idx_data_out = GetTensorDataIndex(idx_out, num_outputs); AllocateOutputSetMklShape(context, idx_out, mkl_shape); if (IsRefType(context->input_dtype(idx_data_in))) { context->forward_ref_input_to_ref_output(idx_data_in, idx_data_out); } else { context->set_output(idx_data_out, context->input(idx_data_in)); } } #endif // Forward the MKL shape ONLY (used in elementwise and other ops where // we call the eigen implementation and MKL shape is not used) inline void ForwardMklMetaDataInToOut(OpKernelContext* context, uint32 idx_data_in, uint32_t idx_data_out) { uint32 idx_meta_in = GetTensorMetaDataIndex(idx_data_in, context->num_inputs()); uint32 idx_meta_out = GetTensorMetaDataIndex(idx_data_out, context->num_outputs()); if (IsRefType(context->input_dtype(idx_data_in))) { context->forward_ref_input_to_ref_output(idx_meta_in, idx_meta_out); } else { context->set_output(idx_meta_out, context->input(idx_meta_in)); } } #ifdef INTEL_MKL_ML_ONLY // Set a dummy MKL shape (called when the output is in TF format) inline void SetDummyMklShapeOutput(OpKernelContext* context, uint32 idx_data_out) { MklShape mkl_shape_output; mkl_shape_output.SetMklTensor(false); AllocateOutputSetMklShape(context, idx_data_out, mkl_shape_output); } // We don't need these functions in MKLDNN. We have defined equality operator // on MklDnnShape class directly. // Checks if the TF shape for both MKL tensors is the same or not // Returns: true if both TF shapes are the same, false otherwise inline bool MklCompareShapes(const MklShape* input_shape_0, const MklShape* input_shape_1) { // Check for number of dimensions if (input_shape_0->GetDimension() != input_shape_1->GetDimension()) { return false; } // Check size of each dimension size_t ndims = input_shape_0->GetDimension(); for (size_t i = 0; i < ndims; i++) { if (input_shape_0->dim_size(i) != input_shape_1->dim_size(i)) { return false; } } return true; } // Checks if the TF shape for both tensors is the same or not // Returns: true if TF shapes for both are the same, false otherwise inline bool MklCompareShapes(const MklShape* input_shape_0, const TensorShape* input_shape_1) { // Check for number of dimensions if (input_shape_0->GetDimension() != input_shape_1->dims()) { return false; } // Check size of each dimension size_t ndims = input_shape_0->GetDimension(); for (size_t i = 0; i < ndims; i++) { if (input_shape_0->tf_dim_size(i) != input_shape_1->dim_size(i)) { return false; } } return true; } // Checks if the TF shape for both tensors is the same or not // Returns: true if TF shapes for both are the same, false otherwise inline bool MklCompareShapes(const TensorShape* input_shape_0, const MklShape* input_shape_1) { return MklCompareShapes(input_shape_1, input_shape_0); } // Checks if the TF shape for both tensors is the same or not // Returns: true if TF shapes for both are the same, false otherwise inline bool MklCompareShapes(const TensorShape* input_shape_0, const TensorShape* input_shape_1) { // Check for number of dimensions if (input_shape_0->dims() != input_shape_1->dims()) { return false; } // Check size of each dimension size_t ndims = input_shape_0->dims(); for (size_t i = 0; i < ndims; i++) { if (input_shape_0->dim_size(i) != input_shape_1->dim_size(i)) { return false; } } return true; } // These functions do not compile with MKL-DNN since mkl.h is missing. // We may need to remove them later. // TODO(intel_tf): Remove this routine when faster MKL layout conversion is // out. inline void MklNHWCToNCHW(const Tensor& input, Tensor** output) { const float* buf_in = input.flat<float>().data(); float* buf_out = (*output)->flat<float>().data(); int64 N = input.dim_size(0); int64 H = input.dim_size(1); int64 W = input.dim_size(2); int64 C = input.dim_size(3); int64 stride_n = H * W * C; #pragma omp parallel for num_threads(16) for (int64 n = 0; n < N; ++n) { mkl_somatcopy('R', 'T', H * W, C, 1, buf_in + n * stride_n, C, buf_out + n * stride_n, H * W); } } inline void MklNCHWToNHWC(const Tensor& input, Tensor** output) { const float* buf_in = input.flat<float>().data(); float* buf_out = (*output)->flat<float>().data(); int64 N = (*output)->dim_size(0); int64 H = (*output)->dim_size(1); int64 W = (*output)->dim_size(2); int64 C = (*output)->dim_size(3); int64 stride_n = H * W * C; #pragma omp parallel for num_threads(16) for (int64 n = 0; n < N; ++n) { mkl_somatcopy('R', 'T', C, H * W, 1, buf_in + n * stride_n, H * W, buf_out + n * stride_n, C); } } #endif // ------------------------------------------------------------------- #ifndef INTEL_MKL_ML_ONLY /// Return MKL-DNN data type (memory::data_type) for input type T /// /// @input None /// @return memory::data_type corresponding to type T template <typename T> static memory::data_type MklDnnType(); /// Instantiation for float type. Add similar instantiations for other /// type if needed. template <> memory::data_type MklDnnType<float>() { return memory::data_type::f32; } template <> memory::data_type MklDnnType<quint8>() { return memory::data_type::u8; } template <> memory::data_type MklDnnType<qint8>() { return memory::data_type::s8; } template <> memory::data_type MklDnnType<qint32>() { return memory::data_type::s32; } template <> memory::data_type MklDnnType<bfloat16>() { // TODO(nhasabni): Enable MKL-DNN bfloat16 type later. // Currently, falling back to f32 to get compilation working. return memory::data_type::f32; } /// Map TensorFlow's data format into MKL-DNN 3D data format /// @input: TensorFlow data format /// @return: memory::format corresponding to TensorFlow data format; /// Fails with an error if invalid data format. inline memory::format TFDataFormatToMklDnn3DDataFormat(TensorFormat format) { if (format == FORMAT_NHWC) return memory::format::ndhwc; else if (format == FORMAT_NCHW) return memory::format::ncdhw; TF_CHECK_OK(Status(error::Code::INVALID_ARGUMENT, "Unsupported data format")); return memory::format::format_undef; } /// Map TensorFlow's data format into MKL-DNN data format /// /// @input: TensorFlow data format /// @return: memory::format corresponding to TensorFlow data format; /// Fails with an error if invalid data format. inline memory::format TFDataFormatToMklDnnDataFormat(TensorFormat format) { if (format == FORMAT_NHWC) return memory::format::nhwc; else if (format == FORMAT_NCHW) return memory::format::nchw; TF_CHECK_OK(Status(error::Code::INVALID_ARGUMENT, "Unsupported data format")); return memory::format::format_undef; } /// Map MKL-DNN data format to TensorFlow's data format /// /// @input: memory::format /// @return: Tensorflow data format corresponding to memory::format /// Fails with an error if invalid data format. inline TensorFormat MklDnnDataFormatToTFDataFormat(memory::format format) { if (format == memory::format::nhwc || format == memory::format::ndhwc) return FORMAT_NHWC; else if (format == memory::format::nchw || format == memory::format::ncdhw) return FORMAT_NCHW; TF_CHECK_OK(Status(error::Code::INVALID_ARGUMENT, "Unsupported data format")); // Return to prevent compiler warnings, otherwise TF_CHECK_OK will ensure // that we don't come here. return FORMAT_NHWC; } /// Map TensorShape object into memory::dims required by MKL-DNN /// /// This function will simply map input TensorShape into MKL-DNN dims /// naively. So it will preserve the order of dimensions. E.g., if /// input tensor is in NHWC format, then dims will be in NHWC format /// also. /// /// @input TensorShape object in shape /// @return memory::dims corresponding to TensorShape inline memory::dims TFShapeToMklDnnDims(const TensorShape& shape) { memory::dims dims(shape.dims()); for (int d = 0; d < shape.dims(); ++d) { dims[d] = shape.dim_size(d); } return dims; } /// Map TensorShape object into memory::dims in NCHW format required by MKL-DNN /// /// This function is a specific one than above function. It will map input /// TensorShape into MKL-DNN dims in NCHW format. So it may not preserve the /// order of dimensions. E.g., if input tensor is in NHWC format, then dims /// will be in NCHW format, and not in NHWC format. /// /// @input TensorShape object in shape /// @return memory::dims in MKL-DNN required NCHW format inline memory::dims TFShapeToMklDnnDimsInNCHW(const TensorShape& shape, TensorFormat format) { // Check validity of format. CHECK_NE(TFDataFormatToMklDnnDataFormat(format), memory::format::format_undef); int n = shape.dim_size(GetTensorDimIndex(format, 'N')); int c = shape.dim_size(GetTensorDimIndex(format, 'C')); int h = shape.dim_size(GetTensorDimIndex(format, 'H')); int w = shape.dim_size(GetTensorDimIndex(format, 'W')); // MKL-DNN requires dimensions in NCHW format. return memory::dims({n, c, h, w}); } inline memory::dims TFShapeToMklDnnDimsInNCDHW(const TensorShape& shape, TensorFormat format) { // Check validity of format. CHECK_NE(TFDataFormatToMklDnn3DDataFormat(format), memory::format::format_undef); int n = shape.dim_size(GetTensorDimIndex<3>(format, 'N')); int c = shape.dim_size(GetTensorDimIndex<3>(format, 'C')); int d = shape.dim_size(GetTensorDimIndex<3>(format, '0')); int h = shape.dim_size(GetTensorDimIndex<3>(format, '1')); int w = shape.dim_size(GetTensorDimIndex<3>(format, '2')); // MKL-DNN requires dimensions in NCDHW format. return memory::dims({n, c, d, h, w}); } /// Overloaded version of function above. Input parameters are /// self-explanatory. inline memory::dims MklDnnDimsInNCHW(const memory::dims& in_dims, TensorFormat format) { // Check validity of format. CHECK_NE(TFDataFormatToMklDnnDataFormat(format), memory::format::format_undef); int n = in_dims[GetTensorDimIndex(format, 'N')]; int c = in_dims[GetTensorDimIndex(format, 'C')]; int h = in_dims[GetTensorDimIndex(format, 'H')]; int w = in_dims[GetTensorDimIndex(format, 'W')]; // MKL-DNN requires dimensions in NCHW format. return memory::dims({n, c, h, w}); } /// Map MklDnn memory::dims object into TensorShape object. /// /// This function will simply map input shape in MKL-DNN memory::dims format /// in Tensorflow's TensorShape object by preserving dimension order. /// /// @input MKL-DNN memory::dims object /// @output TensorShape corresponding to memory::dims inline TensorShape MklDnnDimsToTFShape(const memory::dims& dims) { std::vector<int32> shape(dims.size(), -1); for (int d = 0; d < dims.size(); d++) { shape[d] = dims[d]; } TensorShape ret; CHECK_EQ(TensorShapeUtils::MakeShape(shape, &ret).ok(), true); return ret; } /// Function to calculate strides given tensor shape in Tensorflow order /// E.g., if dims_tf_order is {1, 2, 3, 4}, then as per Tensorflow convention, /// dimension with size 1 is outermost dimension; while dimension with size 4 is /// innermost dimension. So strides for this tensor would be {4 * 3 * 2, /// 4 * 3, 4, 1}, i.e., {24, 12, 4, 1}. /// /// @input Tensorflow shape in memory::dims type /// @return memory::dims containing strides for the tensor. inline memory::dims CalculateTFStrides(const memory::dims& dims_tf_order) { CHECK_GT(dims_tf_order.size(), 0); memory::dims strides(dims_tf_order.size()); int last_dim_idx = dims_tf_order.size() - 1; strides[last_dim_idx] = 1; for (int d = last_dim_idx - 1; d >= 0; d--) { strides[d] = strides[d + 1] * dims_tf_order[d + 1]; } return strides; } inline padding_kind TFPaddingToMklDnnPadding(Padding pad) { // MKL-DNN only supports zero padding. return padding_kind::zero; } /// Helper function to create memory descriptor in Blocked format /// /// @input: Tensor dimensions /// @input: strides corresponding to dimensions. One can use utility /// function such as CalculateTFStrides to compute strides /// for given dimensions. /// @return: memory::desc object corresponding to blocked memory format /// for given dimensions and strides. inline memory::desc CreateBlockedMemDescHelper(const memory::dims& dim, const memory::dims& strides, memory::data_type dtype) { CHECK_EQ(dim.size(), strides.size()); // We have to construct memory descriptor in a C style. This is not at all // ideal but MKLDNN does not offer any API to construct descriptor in // blocked format except a copy constructor that accepts // mkldnn_memory_desc_t. mkldnn_memory_desc_t md; md.primitive_kind = mkldnn_memory; md.ndims = dim.size(); md.format = mkldnn_blocked; md.data_type = memory::convert_to_c(dtype); for (size_t i = 0; i < dim.size(); i++) { md.layout_desc.blocking.block_dims[i] = 1; md.layout_desc.blocking.strides[1][i] = 1; md.layout_desc.blocking.strides[0][i] = strides[i]; md.layout_desc.blocking.padding_dims[i] = dim[i]; md.layout_desc.blocking.offset_padding_to_data[i] = 0; md.dims[i] = dim[i]; } md.layout_desc.blocking.offset_padding = 0; return memory::desc(md); } template <typename T> inline primitive FindOrCreateReorder(const memory* from, const memory* to); /* * Class to represent all the resources corresponding to a tensor in TensorFlow * that are required to execute an operation (such as Convolution). */ template <typename T> class MklDnnData { private: /// MKL-DNN memory primitive for input user memory memory* user_memory_; /// MKL-DNN memory primitive in case input or output reorder is needed. memory* reorder_memory_; /// Operations memory descriptor memory::desc* op_md_; // flat to indicate if data is 3D or not. bool bIs3D; /// Operations temp buffer void* allocated_buffer_; /// CPU engine on which operation will be executed const engine* cpu_engine_; public: explicit MklDnnData(const engine* e) : user_memory_(nullptr), reorder_memory_(nullptr), op_md_(nullptr), allocated_buffer_(nullptr), cpu_engine_(e) {} ~MklDnnData() { if (allocated_buffer_ != nullptr) { cpu_allocator()->DeallocateRaw(allocated_buffer_); } cpu_engine_ = nullptr; // We don't own this. delete (user_memory_); delete (reorder_memory_); delete (op_md_); } inline void* GetTensorBuffer(const Tensor* tensor) const { CHECK_NOTNULL(tensor); return const_cast<void*>( static_cast<const void*>(tensor->flat<T>().data())); } void SetIs3DData(bool bIs3D_) { bIs3D = bIs3D_; } bool GetIs3D() { return bIs3D; } /// Set user memory primitive using specified dimensions, memory format and /// data_buffer. Function automatically uses element data type by using /// input type T used for creating call object. /// /// In a nutshell, function allows user to describe the input tensor to /// an operation. E.g., filter of Conv2D is of shape {1, 2, 3, 4}, and /// memory format HWIO, and the buffer that contains actual values is /// pointed by data_buffer. inline void SetUsrMem(const memory::dims& dim, memory::format fm, void* data_buffer = nullptr) { auto md = memory::desc(dim, MklDnnType<T>(), fm); SetUsrMem(md, data_buffer); } inline void SetUsrMem(const memory::dims& dim, memory::format fm, const Tensor* tensor) { CHECK_NOTNULL(tensor); SetUsrMem(dim, fm, GetTensorBuffer(tensor)); } /// Helper function to create memory descriptor in Blocked format /// /// @input: Tensor dimensions /// @input: strides corresponding to dimensions. One can use utility /// function such as CalculateTFStrides to compute strides /// for given dimensions. /// @return: memory::desc object corresponding to blocked memory format /// for given dimensions and strides. static inline memory::desc CreateBlockedMemDesc(const memory::dims& dim, const memory::dims& strides) { return CreateBlockedMemDescHelper(dim, strides, MklDnnType<T>()); } /// A version of SetUsrMem call that allows user to create memory in blocked /// format. So in addition to accepting dimensions, it also accepts strides. /// This allows user to create memory for tensor in a format that is not /// supported by MKLDNN. E.g., MKLDNN does not support tensor format for 6 /// dimensional tensor as a native format. But by using blocked format, a user /// can create memory for 6D tensor. inline void SetUsrMem(const memory::dims& dim, const memory::dims& strides, void* data_buffer = nullptr) { CHECK_EQ(dim.size(), strides.size()); auto blocked_md = MklDnnData<T>::CreateBlockedMemDesc(dim, strides); SetUsrMem(blocked_md, data_buffer); } inline void SetUsrMem(const memory::dims& dim, const memory::dims& strides, const Tensor* tensor) { CHECK_NOTNULL(tensor); SetUsrMem(dim, strides, GetTensorBuffer(tensor)); } /// A version of function to set user memory primitive that accepts memory /// descriptor directly, instead of accepting dimensions and format. This /// function is more generic that the one above, but the function above is /// sufficient in most cases. inline void SetUsrMem(const memory::desc& md, void* data_buffer = nullptr) { auto pd = memory::primitive_desc(md, *cpu_engine_); SetUsrMem(pd, data_buffer); } /// A version of SetUsrMem with memory descriptor and tensor inline void SetUsrMem(const memory::desc& md, const Tensor* tensor) { CHECK_NOTNULL(tensor); SetUsrMem(md, GetTensorBuffer(tensor)); } /// A version of function to set user memory primitive that accepts primitive /// descriptor directly, instead of accepting dimensions and format. This /// function is more generic that the one above, but the function above is /// sufficient in most cases. inline void SetUsrMem(const memory::primitive_desc& pd, void* data_buffer = nullptr) { CHECK_NOTNULL(cpu_engine_); if (user_memory_) delete user_memory_; // TODO(nhasabni): can we remove dynamic memory allocation? if (data_buffer) { user_memory_ = new memory(pd, data_buffer); } else { user_memory_ = new memory(pd); } } /// A version of SetUsrMem with primitive descriptor and tensor inline void SetUsrMem(const memory::primitive_desc& pd, const Tensor* tensor) { CHECK_NOTNULL(tensor); SetUsrMem(pd, GetTensorBuffer(tensor)); } /// Get function for user memory primitive. inline const memory* GetUsrMem() const { return user_memory_; } /// Get function for primitive descriptor of user memory primitive. inline const memory::primitive_desc GetUsrMemPrimDesc() const { CHECK_NOTNULL(user_memory_); return user_memory_->get_primitive_desc(); } /// Get function for descriptor of user memory. inline memory::desc GetUsrMemDesc() { // This is ugly. Why MKL-DNN does not provide desc() method of const type?? const memory::primitive_desc pd = GetUsrMemPrimDesc(); return const_cast<memory::primitive_desc*>(&pd)->desc(); } /// Get function for data buffer of user memory primitive. inline void* GetUsrMemDataHandle() const { CHECK_NOTNULL(user_memory_); return user_memory_->get_data_handle(); } /// Set function for data buffer of user memory primitive. inline void SetUsrMemDataHandle(void* data_buffer) { CHECK_NOTNULL(user_memory_); CHECK_NOTNULL(data_buffer); user_memory_->set_data_handle(data_buffer); } /// Set function for data buffer of user memory primitive. inline void SetUsrMemDataHandle(const Tensor* tensor) { CHECK_NOTNULL(user_memory_); CHECK_NOTNULL(tensor); user_memory_->set_data_handle(GetTensorBuffer(tensor)); } /// allocate function for data buffer inline void AllocateBuffer(size_t size) { const int64 kMemoryAlginment = 64; // For AVX512 memory alignment. allocated_buffer_ = cpu_allocator()->AllocateRaw(kMemoryAlginment, size); } inline void* GetAllocatedBuffer() { return allocated_buffer_; } /// Get the memory primitive for input and output of an op. If inputs /// to an op require reorders, then this function returns memory primitive /// for reorder. Otherwise, it will return memory primitive for user memory. /// /// E.g., Conv2D(I, F) is a primitive with I and F being inputs. Then to /// execute Conv2D, we need memory primitive for I and F. Buf if reorder is /// required for I and F (say I_r is reorder primitive for I; F_r is reorder /// primitive for F), then we need I_r and F_r to perform Conv2D. inline const memory& GetOpMem() const { return reorder_memory_ ? *reorder_memory_ : *user_memory_; } /// Set memory descriptor of an operation in terms of dimensions and memory /// format. E.g., For Conv2D, the dimensions would be same as user dimensions /// but memory::format would be mkldnn::any because we want MKL-DNN to choose /// best layout/format for given input dimensions. inline void SetOpMemDesc(const memory::dims& dim, memory::format fm) { // TODO(nhasabni): can we remove dynamic memory allocation? op_md_ = new memory::desc(dim, MklDnnType<T>(), fm); } /// Get function for memory descriptor for an operation inline const memory::desc& GetOpMemDesc() const { return *op_md_; } /// Predicate that checks if we need to reorder user's memory into memory /// pointed by op_pd. /// /// @input: op_pd - memory primitive descriptor of the given input of an /// operation /// @return: true in case reorder of input is needed; false, otherwise. inline bool IsReorderNeeded(const memory::primitive_desc& op_pd) const { CHECK_NOTNULL(user_memory_); return op_pd != user_memory_->get_primitive_desc(); } /// Predicate that checks if we need to reorder user's memory into memory /// based on the provided format. /// /// @input: target_format - memory format of the given input of an /// operation /// @return: true in case reorder of input is needed; false, otherwise. inline bool IsReorderNeeded(const memory::format& target_format) const { CHECK_NOTNULL(user_memory_); return target_format != user_memory_->get_primitive_desc().desc().data.format; } /// Function to create a reorder from memory pointed by from to memory pointed /// by to. Returns created primitive. inline primitive CreateReorder(const memory* from, const memory* to) const { CHECK_NOTNULL(from); CHECK_NOTNULL(to); return reorder(*from, *to); } /// Function to handle input reordering /// /// Check if we need to reorder this input of an operation. /// Return true and allocate reorder memory primitive if reorder is needed. /// Otherwise, return false and do not allocate reorder memory primitive. /// /// To check if reorder is needed, this function compares memory primitive /// descriptor of an operation (op_pd) for the given input with the /// user-specified memory primitive descriptor. /// /// @input: op_pd - memory primitive descriptor of the given input of an /// operation /// @input: net - net to which to add reorder primitive in case it is needed. /// @return: true in case reorder of input is needed; false, otherwise. inline bool CheckReorderToOpMem(const memory::primitive_desc& op_pd, std::vector<primitive>* net) { CHECK_NOTNULL(net); CHECK_NOTNULL(user_memory_); if (IsReorderNeeded(op_pd)) { // TODO(nhasabni): can we remove dynamic memory allocation? reorder_memory_ = new memory(op_pd); net->push_back(CreateReorder(user_memory_, reorder_memory_)); return true; } return false; } /// TODO: this is a faster path with reorder primitive cache compared with /// CheckReorderToOpMem(..., std::vector<primitive>* net), will remove /// slow path in the future inline bool CheckReorderToOpMem(const memory::primitive_desc& op_pd) { CHECK_NOTNULL(user_memory_); if (IsReorderNeeded(op_pd)) { // TODO(nhasabni): can we remove dynamic memory allocation? // primitive reuse don't allow two same reorder prim in // one stream, so submit it immediately reorder_memory_ = new memory(op_pd); std::vector<primitive> net; net.push_back(FindOrCreateReorder<T>(user_memory_, reorder_memory_)); stream(stream::kind::eager).submit(net).wait(); return true; } return false; } /// Overloaded version of above function that accepts memory buffer /// where output of reorder needs to be stored. /// /// @input: op_pd - memory primitive descriptor of the given input of an /// operation /// @reorder_data_handle - memory buffer where output of reorder needs to be /// stored. Primitive does not check if buffer is /// enough size to write. /// @input: net - net to which to add reorder primitive in case it is needed. /// @return: true in case reorder of input is needed; false, otherwise. inline bool CheckReorderToOpMem(const memory::primitive_desc& op_pd, void* reorder_data_handle, std::vector<primitive>* net) { CHECK_NOTNULL(net); CHECK_NOTNULL(reorder_data_handle); CHECK_NOTNULL(user_memory_); if (IsReorderNeeded(op_pd)) { // TODO(nhasabni): can we remove dynamic memory allocation? reorder_memory_ = new memory(op_pd, reorder_data_handle); net->push_back(CreateReorder(user_memory_, reorder_memory_)); return true; } return false; } /// TODO: this is a faster path with reorder primitive cache compared with /// CheckReorderToOpMem(..., std::vector<primitive>* net), will remove /// slow path in the future inline bool CheckReorderToOpMem(const memory::primitive_desc& op_pd, void* reorder_data_handle) { CHECK_NOTNULL(reorder_data_handle); CHECK_NOTNULL(user_memory_); if (IsReorderNeeded(op_pd)) { // TODO(nhasabni): can we remove dynamic memory allocation? // primitive reuse don't allow two same reorder prim in // one stream, so submit it immediately std::vector<primitive> net; reorder_memory_ = new memory(op_pd, reorder_data_handle); net.push_back(FindOrCreateReorder<T>(user_memory_, reorder_memory_)); stream(stream::kind::eager).submit(net).wait(); return true; } return false; } /// Another overloaded version of CheckReorderToOpMem that accepts Tensor /// where output of reorder needs to be stored. /// /// @input: op_pd - memory primitive descriptor of the given input of an /// operation /// @reorder_tensor - Tensor whose buffer is to be used to store output of /// reorder. Primitive does not check if buffer is /// enough size to write. /// @input: net - net to which to add reorder primitive in case it is needed. /// @return: true in case reorder of input is needed; false, otherwise. inline bool CheckReorderToOpMem(const memory::primitive_desc& op_pd, Tensor* reorder_tensor, std::vector<primitive>* net) { CHECK_NOTNULL(net); CHECK_NOTNULL(reorder_tensor); return CheckReorderToOpMem(op_pd, GetTensorBuffer(reorder_tensor), net); } /// TODO: this is a faster path with reorder primitive cache compared with /// CheckReorderToOpMem(..., std::vector<primitive>* net), will remove /// slow path in the future inline bool CheckReorderToOpMem(const memory::primitive_desc& op_pd, Tensor* reorder_tensor) { CHECK_NOTNULL(reorder_tensor); return CheckReorderToOpMem(op_pd, GetTensorBuffer(reorder_tensor)); } /// Function to handle output reorder /// /// This function performs very similar functionality as input reordering /// function above. The only difference is that this function does not add /// reorder primitive to the net. The reason for this is: the reorder /// primitive for output needs to be added to the list only after operation /// has executed. But we need to prepare a temporary buffer in case output /// reorder is needed. And this temporary buffer will hold the output of /// an operation before it is fed to reorder primitive. /// /// @input memory primitive descriptor for the given output of an operation /// @return: true in case reorder of output is needed; false, otherwise. inline bool PrepareReorderToUserMemIfReq( const memory::primitive_desc& op_pd) { CHECK_NOTNULL(user_memory_); if (IsReorderNeeded(op_pd)) { // TODO(nhasabni): can we remove dynamic memory allocation? reorder_memory_ = new memory(op_pd); return true; } return false; } /// Function to actually insert reorder primitive in the net /// /// This function completes remaining part of output reordering. It inserts /// a reordering primitive from the temporary buffer that holds the output /// to the user-specified output buffer. /// /// @input: net - net to which to add reorder primitive inline void InsertReorderToUserMem(std::vector<primitive>* net) { CHECK_NOTNULL(net); CHECK_NOTNULL(user_memory_); CHECK_NOTNULL(reorder_memory_); net->push_back(CreateReorder(reorder_memory_, user_memory_)); } /// TODO: this is a faster path with reorder primitive cache compared with /// InsertReorderToUserMem(std::vector<primitive>* net), will remove /// slow path in the future inline void InsertReorderToUserMem() { CHECK_NOTNULL(user_memory_); CHECK_NOTNULL(reorder_memory_); // primitive reuse don't allow two same reorder prim in // one stream, so submit it immediately std::vector<primitive> net; net.push_back(FindOrCreateReorder<T>(reorder_memory_, user_memory_)); stream(stream::kind::eager).submit(net).wait(); } }; /// Base class for operations with reuse of primitives /// class MklPrimitive { public: virtual ~MklPrimitive() {} // Dummy data which MKL DNN never operates on unsigned char* DummyData = nullptr; }; const mkldnn::memory::dims NONE_DIMS = {}; // // LRUCache is a class which implements LRU (Least Recently Used) cache. // The implementation is similar to that of // tensorflow/core/platform/cloud/expiring_lru_cache.h // without its thread-safe part because the cache is supposed to be // used as thread local (for instance, MklPrimitive caching). // // The LRU list maintains objects in chronological order based on // creation time, with the least recently accessed object at the // tail of LRU list, while the most recently accessed object // at the head of LRU list. // // This class is used to maintain an upper bound on the total number of // cached items. When the cache reaches its capacity, the LRU item will // be removed and replaced by a new one from SetOp call. // template <typename T> class LRUCache { public: explicit LRUCache(size_t capacity) { capacity_ = capacity; Clear(); } T* GetOp(const string& key) { auto it = cache_.find(key); if (it == cache_.end()) { return nullptr; } // Move to the front of LRU list as the most recently accessed. lru_list_.erase(it->second.lru_iterator); lru_list_.push_front(it->first); it->second.lru_iterator = lru_list_.begin(); return it->second.op; } void SetOp(const string& key, T* op) { if (lru_list_.size() >= capacity_) { Delete(); } // Insert an entry to the front of the LRU list lru_list_.push_front(key); Entry entry(op, lru_list_.begin()); cache_.emplace(std::make_pair(key, std::move(entry))); } void Clear() { if (lru_list_.empty()) return; // Clean up the cache cache_.clear(); lru_list_.clear(); } private: struct Entry { // The entry's value. T* op; // A list iterator pointing to the entry's position in the LRU list. std::list<string>::iterator lru_iterator; // Constructor Entry(T* op, std::list<string>::iterator it) { this->op = op; this->lru_iterator = it; } // Move construcctor Entry(Entry&& source) noexcept : lru_iterator(std::move(source.lru_iterator)) { op = std::move(source.op); source.op = std::forward<T*>(nullptr); } // Destructor ~Entry() { if (op != nullptr) delete op; } }; // Remove the least recently accessed entry from LRU list, which // is the tail of lru_list_. Update cache_ correspondingly. bool Delete() { if (lru_list_.empty()) return false; string key = lru_list_.back(); lru_list_.pop_back(); cache_.erase(key); return true; } // Cache capacity size_t capacity_; // The cache, a map from string key to a LRU entry. std::unordered_map<string, Entry> cache_; // The LRU list of entries. // The front of the list contains the key of the most recently accessed // entry, while the back of the list is the least recently accessed entry. std::list<string> lru_list_; }; template <typename T> class MklPrimitiveFactory { public: MklPrimitiveFactory() {} ~MklPrimitiveFactory() {} MklPrimitive* GetOp(const string& key) { auto& lru_cache = MklPrimitiveFactory<T>::GetLRUCache(); return lru_cache.GetOp(key); } void SetOp(const string& key, MklPrimitive* op) { auto& lru_cache = MklPrimitiveFactory<T>::GetLRUCache(); lru_cache.SetOp(key, op); } /// Function to decide whether HW has AVX512 or AVX2 /// For those legacy device(w/o AVX512 and AVX2), /// MKL-DNN GEMM will be used. static inline bool IsLegacyPlatform() { return (!port::TestCPUFeature(port::CPUFeature::AVX512F) && !port::TestCPUFeature(port::CPUFeature::AVX2)); } /// Fuction to check whether primitive memory optimization is enabled static inline bool IsPrimitiveMemOptEnabled() { bool is_primitive_mem_opt_enabled = true; TF_CHECK_OK(ReadBoolFromEnvVar("TF_MKL_OPTIMIZE_PRIMITIVE_MEMUSE", true, &is_primitive_mem_opt_enabled)); return is_primitive_mem_opt_enabled; } private: static inline LRUCache<MklPrimitive>& GetLRUCache() { static const int kCapacity = 1024; // cache capacity static thread_local LRUCache<MklPrimitive> lru_cache_(kCapacity); return lru_cache_; } }; // utility class for creating keys of MKL primitive pool. class FactoryKeyCreator { public: FactoryKeyCreator() { key_.reserve(kMaxKeyLength); } ~FactoryKeyCreator() {} void AddAsKey(const string& str) { Append(str); } void AddAsKey(const mkldnn::memory::dims& dims) { for (unsigned int i = 0; i < dims.size(); i++) { AddAsKey<int>(dims[i]); } } template <typename T> void AddAsKey(const T data) { auto buffer = reinterpret_cast<const char*>(&data); Append(StringPiece(buffer, sizeof(T))); } string GetKey() { return key_; } private: string key_; const char delimiter = 'x'; const int kMaxKeyLength = 256; void Append(StringPiece s) { key_.append(string(s)); key_.append(1, delimiter); } }; static inline memory::format get_desired_format(int channel, bool is_2d = true) { memory::format fmt_desired = memory::format::any; if (port::TestCPUFeature(port::CPUFeature::AVX512F)) { fmt_desired = is_2d ? memory::format::nChw16c : memory::format::nCdhw16c; } else if (port::TestCPUFeature(port::CPUFeature::AVX2) && (channel % 8) == 0) { fmt_desired = is_2d ? memory::format::nChw8c : memory::format::ncdhw; // no avx2 support for 3d yet. } else { fmt_desired = is_2d ? memory::format::nchw : memory::format::ncdhw; } return fmt_desired; } class MklReorderPrimitive : public MklPrimitive { public: explicit MklReorderPrimitive(const memory* from, const memory* to) { Setup(from, to); } ~MklReorderPrimitive() {} std::shared_ptr<primitive> GetPrimitive() { return context_.reorder_prim; } void SetMemory(const memory* from, const memory* to) { context_.src_mem->set_data_handle(from->get_data_handle()); context_.dst_mem->set_data_handle(to->get_data_handle()); } private: struct ReorderContext { std::shared_ptr<mkldnn::memory> src_mem; std::shared_ptr<mkldnn::memory> dst_mem; std::shared_ptr<primitive> reorder_prim; ReorderContext() : src_mem(nullptr), dst_mem(nullptr), reorder_prim(nullptr) {} } context_; engine cpu_engine_ = engine(engine::cpu, 0); void Setup(const memory* from, const memory* to) { context_.src_mem.reset(new memory( {from->get_primitive_desc().desc(), cpu_engine_}, DummyData)); context_.dst_mem.reset( new memory({to->get_primitive_desc().desc(), cpu_engine_}, DummyData)); context_.reorder_prim = std::make_shared<mkldnn::reorder>( reorder(*context_.src_mem, *context_.dst_mem)); } }; template <typename T> class MklReorderPrimitiveFactory : public MklPrimitiveFactory<T> { public: static MklReorderPrimitive* Get(const memory* from, const memory* to) { auto reorderPrim = static_cast<MklReorderPrimitive*>( MklReorderPrimitiveFactory<T>::GetInstance().GetReorder(from, to)); if (reorderPrim == nullptr) { reorderPrim = new MklReorderPrimitive(from, to); MklReorderPrimitiveFactory<T>::GetInstance().SetReorder(from, to, reorderPrim); } reorderPrim->SetMemory(from, to); return reorderPrim; } static MklReorderPrimitiveFactory& GetInstance() { static MklReorderPrimitiveFactory instance_; return instance_; } private: MklReorderPrimitiveFactory() {} ~MklReorderPrimitiveFactory() {} static string CreateKey(const memory* from, const memory* to) { string prefix = "reorder"; FactoryKeyCreator key_creator; auto const& from_desc = from->get_primitive_desc().desc().data; auto const& to_desc = to->get_primitive_desc().desc().data; const int KIdxFirstStride = 0; memory::dims from_dims(from_desc.dims, &from_desc.dims[from_desc.ndims]); memory::dims to_dims(to_desc.dims, &to_desc.dims[to_desc.ndims]); memory::dims from_strides( from_desc.layout_desc.blocking.strides[KIdxFirstStride], &from_desc.layout_desc.blocking .strides[KIdxFirstStride][from_desc.ndims]); memory::dims to_strides( to_desc.layout_desc.blocking.strides[KIdxFirstStride], &to_desc.layout_desc.blocking.strides[KIdxFirstStride][to_desc.ndims]); key_creator.AddAsKey(prefix); key_creator.AddAsKey(static_cast<int>(from_desc.format)); key_creator.AddAsKey(static_cast<int>(from_desc.data_type)); key_creator.AddAsKey(from_dims); key_creator.AddAsKey(from_strides); key_creator.AddAsKey(static_cast<int>(to_desc.format)); key_creator.AddAsKey(static_cast<int>(to_desc.data_type)); key_creator.AddAsKey(to_dims); key_creator.AddAsKey(to_strides); return key_creator.GetKey(); } MklPrimitive* GetReorder(const memory* from, const memory* to) { string key = CreateKey(from, to); return this->GetOp(key); } void SetReorder(const memory* from, const memory* to, MklPrimitive* op) { string key = CreateKey(from, to); this->SetOp(key, op); } }; /// Fuction to find(or create) a reorder from memory pointed by /// from to memory pointed by to, it will created primitive or /// get primitive from pool if it is cached. /// Returns the primitive. template <typename T> inline primitive FindOrCreateReorder(const memory* from, const memory* to) { CHECK_NOTNULL(from); CHECK_NOTNULL(to); MklReorderPrimitive* reorder_prim = MklReorderPrimitiveFactory<T>::Get(from, to); return *reorder_prim->GetPrimitive(); } // utility function to determine if it is conv 1x1 and stride != 1 // for purpose of temporarily disabling primitive reuse inline bool IsConv1x1StrideNot1(memory::dims filter_dims, memory::dims strides) { if (filter_dims.size() != 4 || strides.size() != 2) return false; return ((filter_dims[2] == 1) && (filter_dims[3] == 1) && ((strides[0] != 1) || (strides[1] != 1))); } #endif // INTEL_MKL_DNN } // namespace tensorflow #endif // INTEL_MKL #endif // TENSORFLOW_CORE_UTIL_MKL_UTIL_H_