source
stringlengths
3
92
c
stringlengths
26
2.25M
GB_unaryop__minv_int8_fp64.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__minv_int8_fp64 // op(A') function: GB_tran__minv_int8_fp64 // C type: int8_t // A type: double // cast: int8_t cij ; GB_CAST_SIGNED(cij,aij,8) // unaryop: cij = GB_IMINV_SIGNED (aij, 8) #define GB_ATYPE \ double #define GB_CTYPE \ int8_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_IMINV_SIGNED (x, 8) ; // casting #define GB_CASTING(z, aij) \ int8_t z ; GB_CAST_SIGNED(z,aij,8) ; // 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_MINV || GxB_NO_INT8 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_int8_fp64 ( int8_t *Cx, // Cx and Ax may be aliased double *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__minv_int8_fp64 ( 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_binop__first_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary 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_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_uint64) // A.*B function (eWiseMult): GB (_AemultB_08__first_uint64) // A.*B function (eWiseMult): GB (_AemultB_02__first_uint64) // A.*B function (eWiseMult): GB (_AemultB_04__first_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__first_uint64) // A*D function (colscale): GB (_AxD__first_uint64) // D*A function (rowscale): GB (_DxB__first_uint64) // C+=B function (dense accum): GB (_Cdense_accumB__first_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__first_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__first_uint64) // C=scalar+B GB ((none)) // C=scalar+B' GB ((none)) // C=A+scalar GB ((none)) // C=A'+scalar GB ((none)) // C type: uint64_t // A type: uint64_t // A pattern? 0 // B type: uint64_t // B pattern? 1 // BinaryOp: cij = aij #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,A_iso) \ uint64_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) \ ; // true if values of B are not used #define GB_B_IS_PATTERN \ 1 \ // 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,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 ; // 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_UINT64 || GxB_NO_FIRST_UINT64) //------------------------------------------------------------------------------ // 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__first_uint64) ( 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__first_uint64) ( 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_uint64) ( 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 uint64_t uint64_t bwork = (*((uint64_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__first_uint64) ( 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 uint64_t *restrict Cx = (uint64_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__first_uint64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_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__first_uint64) ( 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) ; uint64_t alpha_scalar ; uint64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint64_t *) alpha_scalar_in)) ; beta_scalar = (*((uint64_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__first_uint64) ( 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__first_uint64) ( 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__first_uint64) ( 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__first_uint64) ( 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 //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 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 < bnz ; p++) { if (!GBB (Bb, p)) continue ; ; ; Cx [p] = x ; } return (GrB_SUCCESS) ; #endif } #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 ; 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++) { if (!GBB (Ab, p)) continue ; uint64_t aij = GBX (Ax, p, false) ; Cx [p] = aij ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // 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 ((none)) ( 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 \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } #endif //------------------------------------------------------------------------------ // 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) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ 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 uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
108403fb_so8.c
#define _POSIX_C_SOURCE 200809L #include "stdlib.h" #include "math.h" #include "sys/time.h" #include "xmmintrin.h" #include "pmmintrin.h" #include "omp.h" #include <stdio.h> #define min(a, b) (((a) < (b)) ? (a) : (b)) #define max(a, b) (((a) > (b)) ? (a) : (b)) struct dataobj { void *restrict data; int *size; int *npsize; int *dsize; int *hsize; int *hofs; int *oofs; }; struct profiler { double section0; double section1; double section2; }; void bf0(struct dataobj *restrict damp_vec, const float dt, struct dataobj *restrict epsilon_vec, float *restrict r49_vec, float *restrict r50_vec, float *restrict r51_vec, float *restrict r52_vec, float *restrict r53_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, struct dataobj *restrict vp_vec, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict save_src_u_vec, struct dataobj *restrict save_src_v_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, const int x0_blk0_size, const int x_size, const int y0_blk0_size, const int y_size, const int z_size, const int t0, const int t1, const int t2, const int x_M, const int x_m, const int y_M, const int y_m, const int z_M, const int z_m, const int sp_zi_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, float **restrict r108_vec, float **restrict r109_vec, const int time, const int tw); int ForwardTTI(struct dataobj *restrict damp_vec, struct dataobj *restrict delta_vec, const float dt, struct dataobj *restrict epsilon_vec, const float o_x, const float o_y, const float o_z, struct dataobj *restrict phi_vec, struct dataobj *restrict src_vec, struct dataobj *restrict src_coords_vec, struct dataobj *restrict theta_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, struct dataobj *restrict vp_vec, const int x0_blk0_size, const int x_M, const int x_m, const int x_size, const int y0_blk0_size, const int y_M, const int y_m, const int y_size, const int z_M, const int z_m, const int z_size, const int p_src_M, const int p_src_m, const int time_M, const int time_m, struct profiler *timers, const int nthreads, const int nthreads_nonaffine) { float(*restrict delta)[delta_vec->size[1]][delta_vec->size[2]] __attribute__((aligned(64))) = (float(*)[delta_vec->size[1]][delta_vec->size[2]])delta_vec->data; float(*restrict phi)[phi_vec->size[1]][phi_vec->size[2]] __attribute__((aligned(64))) = (float(*)[phi_vec->size[1]][phi_vec->size[2]])phi_vec->data; float(*restrict src)[src_vec->size[1]] __attribute__((aligned(64))) = (float(*)[src_vec->size[1]])src_vec->data; float(*restrict src_coords)[src_coords_vec->size[1]] __attribute__((aligned(64))) = (float(*)[src_coords_vec->size[1]])src_coords_vec->data; float(*restrict theta)[theta_vec->size[1]][theta_vec->size[2]] __attribute__((aligned(64))) = (float(*)[theta_vec->size[1]][theta_vec->size[2]])theta_vec->data; float(*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__((aligned(64))) = (float(*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]])u_vec->data; float(*restrict v)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]])v_vec->data; float(*restrict vp)[vp_vec->size[1]][vp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[vp_vec->size[1]][vp_vec->size[2]])vp_vec->data; float(*r49)[y_size + 2 + 2][z_size + 2 + 2]; posix_memalign((void **)&r49, 64, sizeof(float[x_size + 2 + 2][y_size + 2 + 2][z_size + 2 + 2])); float(*r50)[y_size + 2 + 2][z_size + 2 + 2]; posix_memalign((void **)&r50, 64, sizeof(float[x_size + 2 + 2][y_size + 2 + 2][z_size + 2 + 2])); float(*r51)[y_size + 2 + 2][z_size + 2 + 2]; posix_memalign((void **)&r51, 64, sizeof(float[x_size + 2 + 2][y_size + 2 + 2][z_size + 2 + 2])); float(*r52)[y_size + 2 + 2][z_size + 2 + 2]; posix_memalign((void **)&r52, 64, sizeof(float[x_size + 2 + 2][y_size + 2 + 2][z_size + 2 + 2])); float(*r53)[y_size + 2 + 2][z_size + 2 + 2]; posix_memalign((void **)&r53, 64, sizeof(float[x_size + 2 + 2][y_size + 2 + 2][z_size + 2 + 2])); float **r108; posix_memalign((void **)&r108, 64, sizeof(float *) * nthreads); float **r109; posix_memalign((void **)&r109, 64, sizeof(float *) * nthreads); #pragma omp parallel num_threads(nthreads) { const int tid = omp_get_thread_num(); posix_memalign((void **)&r108[tid], 64, sizeof(float[x0_blk0_size + 2 + 2][y0_blk0_size + 2 + 2][z_size + 2 + 2])); posix_memalign((void **)&r109[tid], 64, sizeof(float[x0_blk0_size + 2 + 2][y0_blk0_size + 2 + 2][z_size + 2 + 2])); } /* Flush denormal numbers to zero in hardware */ _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); struct timeval start_section0, end_section0; gettimeofday(&start_section0, NULL); /* Begin section0 */ #pragma omp parallel num_threads(nthreads) { #pragma omp for collapse(1) schedule(static, 1) for (int x = x_m - 2; x <= x_M + 2; x += 1) { for (int y = y_m - 2; y <= y_M + 2; y += 1) { #pragma omp simd aligned(delta, phi, theta : 32) for (int z = z_m - 2; z <= z_M + 2; z += 1) { r49[x + 2][y + 2][z + 2] = sqrt(2 * delta[x + 8][y + 8][z + 8] + 1); r50[x + 2][y + 2][z + 2] = cos(theta[x + 8][y + 8][z + 8]); r51[x + 2][y + 2][z + 2] = cos(phi[x + 8][y + 8][z + 8]); r52[x + 2][y + 2][z + 2] = sin(theta[x + 8][y + 8][z + 8]); r53[x + 2][y + 2][z + 2] = sin(phi[x + 8][y + 8][z + 8]); } } } } /* End section0 */ gettimeofday(&end_section0, NULL); timers->section0 += (double)(end_section0.tv_sec - start_section0.tv_sec) + (double)(end_section0.tv_usec - start_section0.tv_usec) / 1000000; for (int time = time_m, t1 = (time + 2) % (3), t0 = (time) % (3), t2 = (time + 1) % (3); time <= time_M; time += 1, t1 = (time + 2) % (3), t0 = (time) % (3), t2 = (time + 1) % (3)) { struct timeval start_section1, end_section1; gettimeofday(&start_section1, NULL); /* Begin section1 */ bf0(damp_vec, dt, epsilon_vec, (float *)r49, (float *)r50, (float *)r51, (float *)r52, (float *)r53, u_vec, v_vec, vp_vec, x0_blk0_size, x_size, y0_blk0_size, y_size, z_size, t0, t1, t2, x_M - (x_M - x_m + 1) % (x0_blk0_size), x_m, y_M - (y_M - y_m + 1) % (y0_blk0_size), y_m, z_M, z_m, nthreads, (float **)r108, (float **)r109); bf0(damp_vec, dt, epsilon_vec, (float *)r49, (float *)r50, (float *)r51, (float *)r52, (float *)r53, u_vec, v_vec, vp_vec, x0_blk0_size, x_size, (y_M - y_m + 1) % (y0_blk0_size), y_size, z_size, t0, t1, t2, x_M - (x_M - x_m + 1) % (x0_blk0_size), x_m, y_M, y_M - (y_M - y_m + 1) % (y0_blk0_size) + 1, z_M, z_m, nthreads, (float **)r108, (float **)r109); bf0(damp_vec, dt, epsilon_vec, (float *)r49, (float *)r50, (float *)r51, (float *)r52, (float *)r53, u_vec, v_vec, vp_vec, (x_M - x_m + 1) % (x0_blk0_size), x_size, y0_blk0_size, y_size, z_size, t0, t1, t2, x_M, x_M - (x_M - x_m + 1) % (x0_blk0_size) + 1, y_M - (y_M - y_m + 1) % (y0_blk0_size), y_m, z_M, z_m, nthreads, (float **)r108, (float **)r109); bf0(damp_vec, dt, epsilon_vec, (float *)r49, (float *)r50, (float *)r51, (float *)r52, (float *)r53, u_vec, v_vec, vp_vec, (x_M - x_m + 1) % (x0_blk0_size), x_size, (y_M - y_m + 1) % (y0_blk0_size), y_size, z_size, t0, t1, t2, x_M, x_M - (x_M - x_m + 1) % (x0_blk0_size) + 1, y_M, y_M - (y_M - y_m + 1) % (y0_blk0_size) + 1, z_M, z_m, nthreads, (float **)r108, (float **)r109); /* End section1 */ gettimeofday(&end_section1, NULL); timers->section1 += (double)(end_section1.tv_sec - start_section1.tv_sec) + (double)(end_section1.tv_usec - start_section1.tv_usec) / 1000000; struct timeval start_section2, end_section2; gettimeofday(&start_section2, NULL); /* Begin section2 */ #pragma omp parallel num_threads(nthreads_nonaffine) { int chunk_size = (int)(fmax(1, (1.0F / 3.0F) * (p_src_M - p_src_m + 1) / nthreads_nonaffine)); #pragma omp for collapse(1) schedule(dynamic, chunk_size) for (int p_src = p_src_m; p_src <= p_src_M; p_src += 1) { float posx = -o_x + src_coords[p_src][0]; float posy = -o_y + src_coords[p_src][1]; float posz = -o_z + src_coords[p_src][2]; int ii_src_0 = (int)(floor(1.0e-1 * posx)); int ii_src_1 = (int)(floor(1.0e-1 * posy)); int ii_src_2 = (int)(floor(1.0e-1 * posz)); int ii_src_3 = (int)(floor(1.0e-1 * posz)) + 1; int ii_src_4 = (int)(floor(1.0e-1 * posy)) + 1; int ii_src_5 = (int)(floor(1.0e-1 * posx)) + 1; float px = (float)(posx - 1.0e+1F * (int)(floor(1.0e-1F * posx))); float py = (float)(posy - 1.0e+1F * (int)(floor(1.0e-1F * posy))); float pz = (float)(posz - 1.0e+1F * (int)(floor(1.0e-1F * posz))); if (ii_src_0 >= x_m - 1 && ii_src_1 >= y_m - 1 && ii_src_2 >= z_m - 1 && ii_src_0 <= x_M + 1 && ii_src_1 <= y_M + 1 && ii_src_2 <= z_M + 1) { float r54 = (dt * dt) * (vp[ii_src_0 + 8][ii_src_1 + 8][ii_src_2 + 8] * vp[ii_src_0 + 8][ii_src_1 + 8][ii_src_2 + 8]) * (-1.0e-3F * px * py * pz + 1.0e-2F * px * py + 1.0e-2F * px * pz - 1.0e-1F * px + 1.0e-2F * py * pz - 1.0e-1F * py - 1.0e-1F * pz + 1) * src[time][p_src]; #pragma omp atomic update u[t2][ii_src_0 + 8][ii_src_1 + 8][ii_src_2 + 8] += r54; } if (ii_src_0 >= x_m - 1 && ii_src_1 >= y_m - 1 && ii_src_3 >= z_m - 1 && ii_src_0 <= x_M + 1 && ii_src_1 <= y_M + 1 && ii_src_3 <= z_M + 1) { float r55 = (dt * dt) * (vp[ii_src_0 + 8][ii_src_1 + 8][ii_src_3 + 8] * vp[ii_src_0 + 8][ii_src_1 + 8][ii_src_3 + 8]) * (1.0e-3F * px * py * pz - 1.0e-2F * px * pz - 1.0e-2F * py * pz + 1.0e-1F * pz) * src[time][p_src]; #pragma omp atomic update u[t2][ii_src_0 + 8][ii_src_1 + 8][ii_src_3 + 8] += r55; } if (ii_src_0 >= x_m - 1 && ii_src_2 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_0 <= x_M + 1 && ii_src_2 <= z_M + 1 && ii_src_4 <= y_M + 1) { float r56 = (dt * dt) * (vp[ii_src_0 + 8][ii_src_4 + 8][ii_src_2 + 8] * vp[ii_src_0 + 8][ii_src_4 + 8][ii_src_2 + 8]) * (1.0e-3F * px * py * pz - 1.0e-2F * px * py - 1.0e-2F * py * pz + 1.0e-1F * py) * src[time][p_src]; #pragma omp atomic update u[t2][ii_src_0 + 8][ii_src_4 + 8][ii_src_2 + 8] += r56; } if (ii_src_0 >= x_m - 1 && ii_src_3 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_0 <= x_M + 1 && ii_src_3 <= z_M + 1 && ii_src_4 <= y_M + 1) { float r57 = (dt * dt) * (vp[ii_src_0 + 8][ii_src_4 + 8][ii_src_3 + 8] * vp[ii_src_0 + 8][ii_src_4 + 8][ii_src_3 + 8]) * (-1.0e-3F * px * py * pz + 1.0e-2F * py * pz) * src[time][p_src]; #pragma omp atomic update u[t2][ii_src_0 + 8][ii_src_4 + 8][ii_src_3 + 8] += r57; } if (ii_src_1 >= y_m - 1 && ii_src_2 >= z_m - 1 && ii_src_5 >= x_m - 1 && ii_src_1 <= y_M + 1 && ii_src_2 <= z_M + 1 && ii_src_5 <= x_M + 1) { float r58 = (dt * dt) * (vp[ii_src_5 + 8][ii_src_1 + 8][ii_src_2 + 8] * vp[ii_src_5 + 8][ii_src_1 + 8][ii_src_2 + 8]) * (1.0e-3F * px * py * pz - 1.0e-2F * px * py - 1.0e-2F * px * pz + 1.0e-1F * px) * src[time][p_src]; #pragma omp atomic update u[t2][ii_src_5 + 8][ii_src_1 + 8][ii_src_2 + 8] += r58; } if (ii_src_1 >= y_m - 1 && ii_src_3 >= z_m - 1 && ii_src_5 >= x_m - 1 && ii_src_1 <= y_M + 1 && ii_src_3 <= z_M + 1 && ii_src_5 <= x_M + 1) { float r59 = (dt * dt) * (vp[ii_src_5 + 8][ii_src_1 + 8][ii_src_3 + 8] * vp[ii_src_5 + 8][ii_src_1 + 8][ii_src_3 + 8]) * (-1.0e-3F * px * py * pz + 1.0e-2F * px * pz) * src[time][p_src]; #pragma omp atomic update u[t2][ii_src_5 + 8][ii_src_1 + 8][ii_src_3 + 8] += r59; } if (ii_src_2 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_5 >= x_m - 1 && ii_src_2 <= z_M + 1 && ii_src_4 <= y_M + 1 && ii_src_5 <= x_M + 1) { float r60 = (dt * dt) * (vp[ii_src_5 + 8][ii_src_4 + 8][ii_src_2 + 8] * vp[ii_src_5 + 8][ii_src_4 + 8][ii_src_2 + 8]) * (-1.0e-3F * px * py * pz + 1.0e-2F * px * py) * src[time][p_src]; #pragma omp atomic update u[t2][ii_src_5 + 8][ii_src_4 + 8][ii_src_2 + 8] += r60; } if (ii_src_3 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_5 >= x_m - 1 && ii_src_3 <= z_M + 1 && ii_src_4 <= y_M + 1 && ii_src_5 <= x_M + 1) { float r61 = 1.0e-3F * px * py * pz * (dt * dt) * (vp[ii_src_5 + 8][ii_src_4 + 8][ii_src_3 + 8] * vp[ii_src_5 + 8][ii_src_4 + 8][ii_src_3 + 8]) * src[time][p_src]; #pragma omp atomic update u[t2][ii_src_5 + 8][ii_src_4 + 8][ii_src_3 + 8] += r61; } posx = -o_x + src_coords[p_src][0]; posy = -o_y + src_coords[p_src][1]; posz = -o_z + src_coords[p_src][2]; ii_src_0 = (int)(floor(1.0e-1 * posx)); ii_src_1 = (int)(floor(1.0e-1 * posy)); ii_src_2 = (int)(floor(1.0e-1 * posz)); ii_src_3 = (int)(floor(1.0e-1 * posz)) + 1; ii_src_4 = (int)(floor(1.0e-1 * posy)) + 1; ii_src_5 = (int)(floor(1.0e-1 * posx)) + 1; px = (float)(posx - 1.0e+1F * (int)(floor(1.0e-1F * posx))); py = (float)(posy - 1.0e+1F * (int)(floor(1.0e-1F * posy))); pz = (float)(posz - 1.0e+1F * (int)(floor(1.0e-1F * posz))); if (ii_src_0 >= x_m - 1 && ii_src_1 >= y_m - 1 && ii_src_2 >= z_m - 1 && ii_src_0 <= x_M + 1 && ii_src_1 <= y_M + 1 && ii_src_2 <= z_M + 1) { float r62 = (dt * dt) * (vp[ii_src_0 + 8][ii_src_1 + 8][ii_src_2 + 8] * vp[ii_src_0 + 8][ii_src_1 + 8][ii_src_2 + 8]) * (-1.0e-3F * px * py * pz + 1.0e-2F * px * py + 1.0e-2F * px * pz - 1.0e-1F * px + 1.0e-2F * py * pz - 1.0e-1F * py - 1.0e-1F * pz + 1) * src[time][p_src]; #pragma omp atomic update v[t2][ii_src_0 + 8][ii_src_1 + 8][ii_src_2 + 8] += r62; } if (ii_src_0 >= x_m - 1 && ii_src_1 >= y_m - 1 && ii_src_3 >= z_m - 1 && ii_src_0 <= x_M + 1 && ii_src_1 <= y_M + 1 && ii_src_3 <= z_M + 1) { float r63 = (dt * dt) * (vp[ii_src_0 + 8][ii_src_1 + 8][ii_src_3 + 8] * vp[ii_src_0 + 8][ii_src_1 + 8][ii_src_3 + 8]) * (1.0e-3F * px * py * pz - 1.0e-2F * px * pz - 1.0e-2F * py * pz + 1.0e-1F * pz) * src[time][p_src]; #pragma omp atomic update v[t2][ii_src_0 + 8][ii_src_1 + 8][ii_src_3 + 8] += r63; } if (ii_src_0 >= x_m - 1 && ii_src_2 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_0 <= x_M + 1 && ii_src_2 <= z_M + 1 && ii_src_4 <= y_M + 1) { float r64 = (dt * dt) * (vp[ii_src_0 + 8][ii_src_4 + 8][ii_src_2 + 8] * vp[ii_src_0 + 8][ii_src_4 + 8][ii_src_2 + 8]) * (1.0e-3F * px * py * pz - 1.0e-2F * px * py - 1.0e-2F * py * pz + 1.0e-1F * py) * src[time][p_src]; #pragma omp atomic update v[t2][ii_src_0 + 8][ii_src_4 + 8][ii_src_2 + 8] += r64; } if (ii_src_0 >= x_m - 1 && ii_src_3 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_0 <= x_M + 1 && ii_src_3 <= z_M + 1 && ii_src_4 <= y_M + 1) { float r65 = (dt * dt) * (vp[ii_src_0 + 8][ii_src_4 + 8][ii_src_3 + 8] * vp[ii_src_0 + 8][ii_src_4 + 8][ii_src_3 + 8]) * (-1.0e-3F * px * py * pz + 1.0e-2F * py * pz) * src[time][p_src]; #pragma omp atomic update v[t2][ii_src_0 + 8][ii_src_4 + 8][ii_src_3 + 8] += r65; } if (ii_src_1 >= y_m - 1 && ii_src_2 >= z_m - 1 && ii_src_5 >= x_m - 1 && ii_src_1 <= y_M + 1 && ii_src_2 <= z_M + 1 && ii_src_5 <= x_M + 1) { float r66 = (dt * dt) * (vp[ii_src_5 + 8][ii_src_1 + 8][ii_src_2 + 8] * vp[ii_src_5 + 8][ii_src_1 + 8][ii_src_2 + 8]) * (1.0e-3F * px * py * pz - 1.0e-2F * px * py - 1.0e-2F * px * pz + 1.0e-1F * px) * src[time][p_src]; #pragma omp atomic update v[t2][ii_src_5 + 8][ii_src_1 + 8][ii_src_2 + 8] += r66; } if (ii_src_1 >= y_m - 1 && ii_src_3 >= z_m - 1 && ii_src_5 >= x_m - 1 && ii_src_1 <= y_M + 1 && ii_src_3 <= z_M + 1 && ii_src_5 <= x_M + 1) { float r67 = (dt * dt) * (vp[ii_src_5 + 8][ii_src_1 + 8][ii_src_3 + 8] * vp[ii_src_5 + 8][ii_src_1 + 8][ii_src_3 + 8]) * (-1.0e-3F * px * py * pz + 1.0e-2F * px * pz) * src[time][p_src]; #pragma omp atomic update v[t2][ii_src_5 + 8][ii_src_1 + 8][ii_src_3 + 8] += r67; } if (ii_src_2 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_5 >= x_m - 1 && ii_src_2 <= z_M + 1 && ii_src_4 <= y_M + 1 && ii_src_5 <= x_M + 1) { float r68 = (dt * dt) * (vp[ii_src_5 + 8][ii_src_4 + 8][ii_src_2 + 8] * vp[ii_src_5 + 8][ii_src_4 + 8][ii_src_2 + 8]) * (-1.0e-3F * px * py * pz + 1.0e-2F * px * py) * src[time][p_src]; #pragma omp atomic update v[t2][ii_src_5 + 8][ii_src_4 + 8][ii_src_2 + 8] += r68; } if (ii_src_3 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_5 >= x_m - 1 && ii_src_3 <= z_M + 1 && ii_src_4 <= y_M + 1 && ii_src_5 <= x_M + 1) { float r69 = 1.0e-3F * px * py * pz * (dt * dt) * (vp[ii_src_5 + 8][ii_src_4 + 8][ii_src_3 + 8] * vp[ii_src_5 + 8][ii_src_4 + 8][ii_src_3 + 8]) * src[time][p_src]; #pragma omp atomic update v[t2][ii_src_5 + 8][ii_src_4 + 8][ii_src_3 + 8] += r69; } } } /* End section2 */ gettimeofday(&end_section2, NULL); timers->section2 += (double)(end_section2.tv_sec - start_section2.tv_sec) + (double)(end_section2.tv_usec - start_section2.tv_usec) / 1000000; } #pragma omp parallel num_threads(nthreads) { const int tid = omp_get_thread_num(); free(r108[tid]); free(r109[tid]); } free(r49); free(r50); free(r51); free(r52); free(r53); free(r108); free(r109); return 0; } void bf0(struct dataobj *restrict damp_vec, const float dt, struct dataobj *restrict epsilon_vec, float *restrict r49_vec, float *restrict r50_vec, float *restrict r51_vec, float *restrict r52_vec, float *restrict r53_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, struct dataobj *restrict vp_vec, const int x0_blk0_size, const int x_size, const int y0_blk0_size, const int y_size, const int z_size, const int t0, const int t1, const int t2, const int x_M, const int x_m, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads, float **restrict r108_vec, float **restrict r109_vec) { float(*restrict damp)[damp_vec->size[1]][damp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[damp_vec->size[1]][damp_vec->size[2]])damp_vec->data; float(*restrict epsilon)[epsilon_vec->size[1]][epsilon_vec->size[2]] __attribute__((aligned(64))) = (float(*)[epsilon_vec->size[1]][epsilon_vec->size[2]])epsilon_vec->data; float(*restrict r49)[y_size + 2 + 2][z_size + 2 + 2] __attribute__((aligned(64))) = (float(*)[y_size + 2 + 2][z_size + 2 + 2]) r49_vec; float(*restrict r50)[y_size + 2 + 2][z_size + 2 + 2] __attribute__((aligned(64))) = (float(*)[y_size + 2 + 2][z_size + 2 + 2]) r50_vec; float(*restrict r51)[y_size + 2 + 2][z_size + 2 + 2] __attribute__((aligned(64))) = (float(*)[y_size + 2 + 2][z_size + 2 + 2]) r51_vec; float(*restrict r52)[y_size + 2 + 2][z_size + 2 + 2] __attribute__((aligned(64))) = (float(*)[y_size + 2 + 2][z_size + 2 + 2]) r52_vec; float(*restrict r53)[y_size + 2 + 2][z_size + 2 + 2] __attribute__((aligned(64))) = (float(*)[y_size + 2 + 2][z_size + 2 + 2]) r53_vec; float(*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__((aligned(64))) = (float(*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]])u_vec->data; float(*restrict v)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]])v_vec->data; float(*restrict vp)[vp_vec->size[1]][vp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[vp_vec->size[1]][vp_vec->size[2]])vp_vec->data; float **r108 = (float **)r108_vec; float **r109 = (float **)r109_vec; if (x0_blk0_size == 0) { return; } #pragma omp parallel num_threads(nthreads) { const int tid = omp_get_thread_num(); float(*restrict r96)[y0_blk0_size + 2 + 2][z_size + 2 + 2] __attribute__((aligned(64))) = (float(*)[y0_blk0_size + 2 + 2][z_size + 2 + 2]) r108[tid]; float(*restrict r97)[y0_blk0_size + 2 + 2][z_size + 2 + 2] __attribute__((aligned(64))) = (float(*)[y0_blk0_size + 2 + 2][z_size + 2 + 2]) r109[tid]; #pragma omp for collapse(1) schedule(dynamic, 1) for (int x0_blk0 = x_m; x0_blk0 <= x_M; x0_blk0 += x0_blk0_size) { for (int y0_blk0 = y_m; y0_blk0 <= y_M; y0_blk0 += y0_blk0_size) { for (int x = x0_blk0 - 2, xs = 0; x <= x0_blk0 + x0_blk0_size + 1; x += 1, xs += 1) { for (int y = y0_blk0 - 2, ys = 0; y <= y0_blk0 + y0_blk0_size + 1; y += 1, ys += 1) { #pragma omp simd aligned(u, v : 32) for (int z = z_m - 2; z <= z_M + 2; z += 1) { r96[xs][ys][z + 2] = -(8.33333346e-3F * (u[t0][x + 6][y + 8][z + 8] - u[t0][x + 10][y + 8][z + 8]) + 6.66666677e-2F * (-u[t0][x + 7][y + 8][z + 8] + u[t0][x + 9][y + 8][z + 8])) * r51[x + 2][y + 2][z + 2] * r52[x + 2][y + 2][z + 2] - (8.33333346e-3F * (u[t0][x + 8][y + 6][z + 8] - u[t0][x + 8][y + 10][z + 8]) + 6.66666677e-2F * (-u[t0][x + 8][y + 7][z + 8] + u[t0][x + 8][y + 9][z + 8])) * r52[x + 2][y + 2][z + 2] * r53[x + 2][y + 2][z + 2] - (8.33333346e-3F * (u[t0][x + 8][y + 8][z + 6] - u[t0][x + 8][y + 8][z + 10]) + 6.66666677e-2F * (-u[t0][x + 8][y + 8][z + 7] + u[t0][x + 8][y + 8][z + 9])) * r50[x + 2][y + 2][z + 2]; r97[xs][ys][z + 2] = -(8.33333346e-3F * (v[t0][x + 6][y + 8][z + 8] - v[t0][x + 10][y + 8][z + 8]) + 6.66666677e-2F * (-v[t0][x + 7][y + 8][z + 8] + v[t0][x + 9][y + 8][z + 8])) * r51[x + 2][y + 2][z + 2] * r52[x + 2][y + 2][z + 2] - (8.33333346e-3F * (v[t0][x + 8][y + 6][z + 8] - v[t0][x + 8][y + 10][z + 8]) + 6.66666677e-2F * (-v[t0][x + 8][y + 7][z + 8] + v[t0][x + 8][y + 9][z + 8])) * r52[x + 2][y + 2][z + 2] * r53[x + 2][y + 2][z + 2] - (8.33333346e-3F * (v[t0][x + 8][y + 8][z + 6] - v[t0][x + 8][y + 8][z + 10]) + 6.66666677e-2F * (-v[t0][x + 8][y + 8][z + 7] + v[t0][x + 8][y + 8][z + 9])) * r50[x + 2][y + 2][z + 2]; } } } for (int x = x0_blk0, xs = 0; x <= x0_blk0 + x0_blk0_size - 1; x += 1, xs += 1) { for (int y = y0_blk0, ys = 0; y <= y0_blk0 + y0_blk0_size - 1; y += 1, ys += 1) { #pragma omp simd aligned(damp, epsilon, u, v, vp : 32) for (int z = z_m; z <= z_M; z += 1) { float r107 = 1.0 / dt; float r106 = 1.0 / (dt * dt); float r105 = 6.66666677e-2F * (r50[x + 2][y + 2][z + 1] * r97[xs + 2][ys + 2][z + 1] - r50[x + 2][y + 2][z + 3] * r97[xs + 2][ys + 2][z + 3] + r51[x + 1][y + 2][z + 2] * r52[x + 1][y + 2][z + 2] * r97[xs + 1][ys + 2][z + 2] - r51[x + 3][y + 2][z + 2] * r52[x + 3][y + 2][z + 2] * r97[xs + 3][ys + 2][z + 2] + r52[x + 2][y + 1][z + 2] * r53[x + 2][y + 1][z + 2] * r97[xs + 2][ys + 1][z + 2] - r52[x + 2][y + 3][z + 2] * r53[x + 2][y + 3][z + 2] * r97[xs + 2][ys + 3][z + 2]); float r104 = 8.33333346e-3F * (-r50[x + 2][y + 2][z] * r97[xs + 2][ys + 2][z] + r50[x + 2][y + 2][z + 4] * r97[xs + 2][ys + 2][z + 4] - r51[x][y + 2][z + 2] * r52[x][y + 2][z + 2] * r97[xs][ys + 2][z + 2] + r51[x + 4][y + 2][z + 2] * r52[x + 4][y + 2][z + 2] * r97[xs + 4][ys + 2][z + 2] - r52[x + 2][y][z + 2] * r53[x + 2][y][z + 2] * r97[xs + 2][ys][z + 2] + r52[x + 2][y + 4][z + 2] * r53[x + 2][y + 4][z + 2] * r97[xs + 2][ys + 4][z + 2]); float r103 = 1.0 / (vp[x + 8][y + 8][z + 8] * vp[x + 8][y + 8][z + 8]); float r102 = 1.0 / (r103 * r106 + r107 * damp[x + 1][y + 1][z + 1]); float r101 = 8.33333346e-3F * (r50[x + 2][y + 2][z] * r96[xs + 2][ys + 2][z] - r50[x + 2][y + 2][z + 4] * r96[xs + 2][ys + 2][z + 4] + r51[x][y + 2][z + 2] * r52[x][y + 2][z + 2] * r96[xs][ys + 2][z + 2] - r51[x + 4][y + 2][z + 2] * r52[x + 4][y + 2][z + 2] * r96[xs + 4][ys + 2][z + 2] + r52[x + 2][y][z + 2] * r53[x + 2][y][z + 2] * r96[xs + 2][ys][z + 2] - r52[x + 2][y + 4][z + 2] * r53[x + 2][y + 4][z + 2] * r96[xs + 2][ys + 4][z + 2]) + 6.66666677e-2F * (-r50[x + 2][y + 2][z + 1] * r96[xs + 2][ys + 2][z + 1] + r50[x + 2][y + 2][z + 3] * r96[xs + 2][ys + 2][z + 3] - r51[x + 1][y + 2][z + 2] * r52[x + 1][y + 2][z + 2] * r96[xs + 1][ys + 2][z + 2] + r51[x + 3][y + 2][z + 2] * r52[x + 3][y + 2][z + 2] * r96[xs + 3][ys + 2][z + 2] - r52[x + 2][y + 1][z + 2] * r53[x + 2][y + 1][z + 2] * r96[xs + 2][ys + 1][z + 2] + r52[x + 2][y + 3][z + 2] * r53[x + 2][y + 3][z + 2] * r96[xs + 2][ys + 3][z + 2]) - 1.78571425e-5F * (u[t0][x + 4][y + 8][z + 8] + u[t0][x + 8][y + 4][z + 8] + u[t0][x + 8][y + 8][z + 4] + u[t0][x + 8][y + 8][z + 12] + u[t0][x + 8][y + 12][z + 8] + u[t0][x + 12][y + 8][z + 8]) + 2.53968248e-4F * (u[t0][x + 5][y + 8][z + 8] + u[t0][x + 8][y + 5][z + 8] + u[t0][x + 8][y + 8][z + 5] + u[t0][x + 8][y + 8][z + 11] + u[t0][x + 8][y + 11][z + 8] + u[t0][x + 11][y + 8][z + 8]) - 1.99999996e-3F * (u[t0][x + 6][y + 8][z + 8] + u[t0][x + 8][y + 6][z + 8] + u[t0][x + 8][y + 8][z + 6] + u[t0][x + 8][y + 8][z + 10] + u[t0][x + 8][y + 10][z + 8] + u[t0][x + 10][y + 8][z + 8]) + 1.59999996e-2F * (u[t0][x + 7][y + 8][z + 8] + u[t0][x + 8][y + 7][z + 8] + u[t0][x + 8][y + 8][z + 7] + u[t0][x + 8][y + 8][z + 9] + u[t0][x + 8][y + 9][z + 8] + u[t0][x + 9][y + 8][z + 8]) - 8.54166647e-2F * u[t0][x + 8][y + 8][z + 8]; float r94 = r106 * (-2.0F * u[t0][x + 8][y + 8][z + 8] + u[t1][x + 8][y + 8][z + 8]); float r95 = r106 * (-2.0F * v[t0][x + 8][y + 8][z + 8] + v[t1][x + 8][y + 8][z + 8]); u[t2][x + 8][y + 8][z + 8] = r102 * (r101 * (2 * epsilon[x + 8][y + 8][z + 8] + 1) + r103 * (-r94) + r107 * (damp[x + 1][y + 1][z + 1] * u[t0][x + 8][y + 8][z + 8]) + (r104 + r105) * r49[x + 2][y + 2][z + 2]); v[t2][x + 8][y + 8][z + 8] = r102 * (r101 * r49[x + 2][y + 2][z + 2] + r103 * (-r95) + r104 + r105 + r107 * (damp[x + 1][y + 1][z + 1] * v[t0][x + 8][y + 8][z + 8])); } } } } } } }
ejemplo_01.c
/* EJERCICIO 1 * Ejemplo 1 * Usando la API(OpenMP) hacer un programa que realice lo siguiente: * - Crear la Matriz A de 50 columnas x 50 filas (50x50), inicializada con valores aleatorios. [✔] */ // Librerias #include <omp.h> #include <stdio.h> #include <stdlib.h> // Definiciones #define CHUNKSIZE 10 #define N 10 #define NRA 5 // numero de filas en matriz A #define NCA 5 // numero de columnas en matriz A // Metodo para obtener numeros random long Random(long li, long ls) { long n; n=li+rand()%(ls-li+1); return n; } // Ejecucion del programa int main (int argc, char *argv[]) { int i, j; double mA[NRA][NCA]; // Establece el numero de subprocesos en las proximas regiones paralelas omp_set_num_threads(2); // Directiva con constructor PARALLEL FOR con clausula SCHEDULE #pragma omp parallel for schedule( static,10) for (i=0; i<NRA; i++) { for (j=0; j<NCA; j++) { // Creacion de Matriz A con numeros aleatorios mA[i][j]= Random(1,20); // Impresion de Matriz A printf("%6.2f ", mA[i][j]); } printf("\n"); } } // Fin main
GMS_simd_memops.h
#ifndef __GMS_SIMD_MEMOPS_H__ #define __GMS_SIMD_MEMOPS_H__ namespace file_info { const unsigned int gGMS_SIMD_MEMOPS_MAJOR = 1U; const unsigned int gGMS_SIMD_MEMOPS_MINOR = 1U; const unsigned int gGMS_SIMD_MEMOPS_MICRO = 0U; const unsigned int gGMS_SIMD_MEMOPS_FULLVER = 1000U*gGMS_SIMD_MEMOPS_MAJOR+100U*gGMS_SIMD_MEMOPS_MINOR+10U*gGMS_SIMD_MEMOPS_MICRO; const char * const pgGMS_SIMD_MEMOPS_CREATE_DATE = "26-09-2020 3:47PM +00200 (SAT 26 SEP 2020 GMT+2)"; const char * const pgGMS_SIMD_MEMOPS_BUILD_DATE = __DATE__ ":" __TIME__; const char * const pgGMS_SIMD_MEMOPS_AUTHOR = "Programmer: Bernard Gingold, contact: beniekg@gmail.com"; } #include <immintrin.h> #include <cstdint> #if defined __GNUC__ && !defined __INTEL_COMPILER #include <omp.h> #endif #include "GMS_config.h" #include "GMS_avxvecf32.h" #include "GMS_avxc8f32.h" #include "GMS_avx512vec16.h" #if !defined (MEMMOVE_1ELEM) #define MEMMOVE_1ELEM 1 #endif #if !defined (MEMMOVE_16ELEMS) #define MEMMOVE_16ELEMS 16 #endif #if !defined (MEMMOVE_32ELEMS) #define MEMMOVE_32ELEMS 32 #endif #if !defined (MEMMOVE_64ELEMS) #define MEMMOVE_64ELEMS 64 #endif #if !defined (MEMMOVE_128ELEMS) #define MEMMOVE_128ELEMS 128 #endif #if !defined (MEMMOVE_256ELEMS) #define MEMMOVE_256ELEMS 256 #endif // float type (4-bytes) #define YMM_LEN (8) #define ZMM_LEN (16) #if !defined (PAGE4KiB) #define PAGE4KiB 4096 #endif #if !defined (MAXFLOATSPERPAGE4KiB) #define MAXFLOATSPERPAGE4KiB 1024 #endif #if !defined (min_val) #define min_val(A,B) ((A)<(B)?(A):(B)) #endif namespace gms { namespace common { __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void init_unroll2x_cmplxr4(std::complex<float> * __restrict __ATTR_ALIGN__(32) vc4, const int32_t len, const std::complex<float> val) { #if defined __GNUC__ && !defined __INTEL_COMPILER vc4 = (std::complex<float>*)__builtin_assume_aligned(vc4,32); #pragma omp simd aligned(vc4:32) #elif defined __INTEL_COMPILER __assume_aligned(vc4,32); #pragma vector always #endif for(int32_t i = 0; i != len-1; i += 2) { vc4[i+0] = val; vc4[i+1] = val; } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void init_unroll4x_cmplxr4(std::complex<float> * __restrict __ATTR_ALIGN__(32) vc4, const int32_t len, const std::complex<float> val) { #if defined __GNUC__ && !defined __INTEL_COMPILER vc4 = (std::complex<float>*)__builtin_assume_aligned(vc4,32); #pragma omp simd aligned(vc4:32) #elif defined __INTEL_COMPILER __assume_aligned(vc4,32); #pragma vector always #endif for(int32_t i = 0; i != len-3; i += 4) { vc4[i+0] = val; vc4[i+1] = val; vc4[i+2] = val; vc4[i+3] = val; } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void init_unroll8x_cmplxr4(std::complex<float> * __restrict __ATTR_ALIGN__(32) vc4, const int32_t len, const std::complex<float> val) { #if defined __GNUC__ && !defined __INTEL_COMPILER vc4 = (std::complex<float>*)__builtin_assume_aligned(vc4,32); #pragma omp simd aligned(vc4:32) #elif defined __INTEL_COMPILER __assume_aligned(vc4,32); #pragma vector always #endif for(int32_t i = 0; i != len-7; i += 8) { vc4[i+0LL] = val; vc4[i+1LL] = val; vc4[i+2LL] = val; vc4[i+3LL] = val; vc4[i+4LL] = val; vc4[i+5LL] = val; vc4[i+6LL] = val; vc4[i+7LL] = val; } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avxvec8_init_unroll2x(AVXVec8 * __restrict __ATTR_ALIGN__(32) vec8, const int32_t len, const AVXVec8 v) { #if defined __GNUC__ && !defined __INTEL_COMPILER vec8 = (AVXVec8*)__builtin_assume_aligned(vec8,32); #elif defined __INTEL_COMPILER assume_aligned(vec8,32); #endif #if defined __GNUC__ && !defined __INTEL_COMPILER #pragma omp simd aligned(vec8:32) #elif defined __INTEL_COMPILER #pragma vector always #pragma code_align(32) #endif for(int32_t i = 0; i != len-1; i += 2) { vec8[i+0] = v; vec8[i+1] = v; } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avxvec8_init_unroll4x(AVXVec8 * __restrict __ATTR_ALIGN__(32) vec8, const int32_t len, const AVXVec8 v) { #if defined __GNUC__ vec8 = (AVXVec8*)__builtin_assume_aligned(vec8,32); #elif defined __INTEL_COMPILER assume_aligned(vec8,32); #endif #if defined __GNUC__ && !defined __INTEL_COMPILER #pragma omp simd aligned(vec8:32) #elif defined __INTEL_COMPILER #pragma vector always #pragma code_align(32) #endif for(int32_t i = 0; i != len-3; i += 4) { vec8[i+0] = v; vec8[i+1] = v; vec8[i+2] = v; vec8[i+3] = v; } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avxvec8_init_unroll8x(AVXVec8 * __restrict __ATTR_ALIGN__(32) vec8, const int32_t len, const AVXVec8 v) { #if defined __GNUC__ && !defined __INTEL_COMPILER vec8 = (AVXVec8*)__builtin_assume_aligned(vec8,32); #elif defined __INTEL_COMPILER __assume_aligned(vec8,32) #endif #if defined __GNUC__ && !defined __INTEL_COMPILER #pragma omp simd aligned(vec8:32) #elif defined __INTEL_COMPILER #pragma vector always #pragma code_align(32) #endif for(int32_t i = 0; i != len-7; i += 8) { vec8[i+0LL] = v; vec8[i+1LL] = v; vec8[i+2LL] = v; vec8[i+3LL] = v; vec8[i+4LL] = v; vec8[i+5LL] = v; vec8[i+6LL] = v; vec8[i+7LL] = v; } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avxvec8_copy_unroll2x(AVXVec8 * __restrict __ATTR_ALIGN__(32) dst, const AVXVec8 * __restrict __ATTR_ALIGN__(32) src, const int32_t len) { #if defined __GNUC__ && !defined __INTEL_COMPILER dst = (AVXVec8*)__builtin_assume_aligned(dst,32); src = (const AVXVec8*)__builtin_assume_aligned(src,32); #elif defined __INTEL_COMPILER __assume_aligned(dst,32); __assume_aligned(src,32); #endif #if defined __GNUC__ && !defined __INTEL_COMPILER #pragma omp simd aligned(src,dst:32) #elif defined __INTEL_COMPILER #pragma vector always #pragma code_align(32) #endif for(int32_t i = 0; i != len-1; i += 2) { dst[i+0] = src[i+0]; dst[i+1] = src[i+1]; } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avxvec8_copy_unroll4x(AVXVec8 * __restrict __ATTR_ALIGN__(32) dst, const AVXVec8 * __restrict __ATTR_ALIGN__(32) src, const int32_t len) { #if defined __GNUC__ && !defined __INTEL_COMPILER dst = (AVXVec8*)__builtin_assume_aligned(dst,32); src = (const AVXVec8*)__builtin_assume_aligned(src,32); #elif defined __INTEL_COMPILER __assume_aligned(dst,32); __assume_aligned(src,32); #endif #if defined __GNUC__ && !defined __INTEL_COMPILER #pragma omp simd aligned(dst,src:32); #elif defined __INTEL_COMPILER #pragma vector always #pragma code_align(32) #endif for(int32_t i = 0; i != len-3; i += 4) { dst[i+0] = src[i+0]; dst[i+1] = src[i+1]; dst[i+2] = src[i+2]; dst[i+3] = src[i+3]; } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avxvec8_copy_unroll8x(AVXVec8 * __restrict __ATTR_ALIGN__(32) dst, const AVXVec8 * __restrict __ATTR_ALIGN__(32) src, const int32_t len) { #if defined __GNUC__ && !defined __INTEL_COMPILER dst = (AVXVec8*)__builtin_assume_aligned(dst,32); src = (const AVXVec8*)__builtin_assume_aligned(src,32); #elif defined __INTEL_COMPILER __assume_aligned(dst,32); __assume_aligned(src,32); #endif #if defined __GNUC__ && !defined __INTEL_COMPILER #pragma omp simd aligned(dst,src:32); #elif defined __INTEL_COMPILER #pragma vector always #pragma code_align(32) #endif for(int32_t i = 0; i != len-7; i += 8) { dst[i+0] = src[i+0]; dst[i+1] = src[i+1]; dst[i+2] = src[i+2]; dst[i+3] = src[i+3]; dst[i+4] = src[i+4]; dst[i+5] = src[i+5]; dst[i+6] = src[i+6]; dst[i+7] = src[i+7]; } } #if defined __AVX512F__ __ATTR_ALWAYS_INLINE__ __ATTR_VECTORCALL__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512vec16_init_unroll2x(AVX512Vec16 * __restrict __ATTR_ALIGN__(64) vec16, const int32_t len, const AVX512Vec16 v) { #if defined __GNUC__ && !defined __INTEL_COMPILER vec16 = (AVX512Vec16*)__builtin_assume_aligned(vec16,64); #elif defined __ICC || defined __INTEL_COMPILER __assume_aligned(vec16,64); #endif #if defined __GNUC__ && !defined __INTEL_COMPILER #pragma omp simd aligned(vec16:64) #elif defined __INTEL_COMPILER #pragma vector always #pragma code_align(32) #endif for(int32_t i = 0; i != len-1; i += 2) { vec16[i+0] = v; vec16[i+1] = v; } } __ATTR_ALWAYS_INLINE__ __ATTR_VECTORCALL__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512vec16_init_unroll4x(AVX512Vec16 * __restrict __ATTR_ALIGN__(64) vec16, const int32_t len, const AVX512Vec16 v) { #if defined __GNUC__ && !defined __INTEL_COMPILER vec16 = (AVX512Vec16*)__builtin_assume_aligned(vec16,64); #elif defined __ICC || defined __INTEL_COMPILER __assume_aligned(vec16,64); #endif #if defined __GNUC__ && !defined __INTEL_COMPILER #pragma omp simd aligned(vec16:64) #elif defined __INTEL_COMPILER #pragma vector always #pragma code_align(32) #endif for(int64_t i = 0; i != len-3; i += 4) { vec16[i+0] = v; vec16[i+1] = v; vec16[i+2] = v; vec16[i+3] = v; } } __ATTR_ALWAYS_INLINE__ __ATTR_VECTORCALL__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512vec16_init_unroll8x(AVX512Vec16 * __restrict __ATTR_ALIGN__(64) vec16, const int32_t len, const AVX512Vec16 v) { #if defined __GNUC__ && !defined __INTEL_COMPILER vec16 = (AVX512Vec16*)__builtin_assume_aligned(vec16,64); #elif defined __ICC || defined __INTEL_COMPILER __assume_aligned(vec16,64); #endif #if defined __GNUC__ && !defined __INTEL_COMPILER #pragma omp simd aligned(vec16:64) #elif defined __INTEL_COMPILER #pragma vector always #pragma code_align(32) #endif for(int64_t i = 0; i != len-7; i += 8) { vec16[i+0] = v; vec16[i+1] = v; vec16[i+2] = v; vec16[i+3] = v; vec16[i+4] = v; vec16[i+5] = v; vec16[i+6] = v; vec16[i+7] = v; } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512vec16_copy_unroll2x(AVX512Vec16 * __restrict __ATTR_ALIGN__(64) dst, const AVX512Vec16 * __restrict __ATTR_ALIGN__(64) src, const int32_t len) { #if defined __GNUC__ && !defined __INTEL_COMPILER dst = (AVXV512ec16*)__builtin_assume_aligned(dst,64); src = (const AVX512Vec16*)__builtin_assume_aligned(src,64); #elif defined __INTEL_COMPILER __assume_aligned(dst,64); __assume_aligned(src,64); #endif #if defined __GNUC__ && !defined __INTEL_COMPILER #pragma omp simd aligned(dst,src:64); #elif defined __INTEL_COMPILER #pragma vector always #pragma code_align(32) #endif for(int32_t i = 0; i != len-1; i += 2) { dst[i+0] = src[i+0]; dst[i+1] = src[i+1]; } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512vec16_copy_unroll4x(AVX512Vec16 * __restrict __ATTR_ALIGN__(64) dst, const AVX512Vec16 * __restrict __ATTR_ALIGN__(64) src, const int32_t len) { #if defined __GNUC__ && !defined __INTEL_COMPILER dst = (AVXV512ec16*)__builtin_assume_aligned(dst,64); src = (const AVX512Vec16*)__builtin_assume_aligned(src,64); #elif defined __INTEL_COMPILER __assume_aligned(dst,64); __assume_aligned(src,64); #endif #if defined __GNUC__ && !defined __INTEL_COMPILER #pragma omp simd aligned(dst,src:64); #elif defined __INTEL_COMPILER #pragma vector always #pragma code_align(32) #endif for(int32_t i = 0; i != len-3; i += 4) { dst[i+0] = src[i+0]; dst[i+1] = src[i+1]; dst[i+2] = src[i+2]; dst[i+3] = src[i+3]; } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512vec16_copy_unroll8x(AVX512Vec16 * __restrict __ATTR_ALIGN__(64) dst, const AVX512Vec16 * __restrict __ATTR_ALIGN__(64) src, const int32_t len) { #if defined __GNUC__ && !defined __INTEL_COMPILER dst = (AVXV512ec16*)__builtin_assume_aligned(dst,64); src = (const AVX512Vec16*)__builtin_assume_aligned(src,64); #elif defined __INTEL_COMPILER __assume_aligned(dst,64); __assume_aligned(src,64); #endif #if defined __GNUC__ && !defined __INTEL_COMPILER #pragma omp simd aligned(dst,src:64); #elif defined __INTEL_COMPILER #pragma vector always #pragma code_align(32) #endif for(int64_t i = 0; i != len-7; i += 8) { dst[i+0] = src[i+0]; dst[i+1] = src[i+1]; dst[i+2] = src[i+2]; dst[i+3] = src[i+3]; dst[i+4] = src[i+4]; dst[i+5] = src[i+5]; dst[i+6] = src[i+6]; dst[i+7] = src[i+7]; } } #endif __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avxvec8_copy_from_r4(AVXVec8 * __restrict __ATTR_ALIGN__(32) dst, const float * __restrict __ATTR_ALIGN__(32) src, const int32_t len) { #if defined __GNUC__ && !defined __INTEL_COMPILER dst = (AVXVec8*)__builtin_assume_aligned(dst,64); src = (const float*)__builtin_assume_aligned(src,64); #elif defined __INTEL_COMPILER __assume_aligned(dst,64); __assume_aligned(src,64); #endif int32_t j; j = 0; #if defined __ICC || defined __INTEL_COMPILER #pragma code_align(32) #endif for(int32_t i = 0; i != len; i += 8) { const __m256 t = _mm256_load_ps(&src[i]); dst[j].m_v8 = t; ++j; } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void r4_copy_from_avxvec8(float * __restrict _ATTR_ALIGN__(32) dst, const AVXVec8 * __restrict __ATTR_ALIGN__(64) src, const int32_t len) { #if defined __GNUC__ && !defined __INTEL_COMPILER dst = (AVXVec8*)__builtin_assume_aligned(dst,64); src = (const float*)__builtin_assume_aligned(src,64); #elif defined __INTEL_COMPILER __assume_aligned(dst,64); __assume_aligned(src,64); #endif int32_t j; j = 0; #if defined __ICC || defined __INTEL_COMPILER #pragma code_align(32) #endif for(int32_t i = 0; i != len; i += 8) { const __m256 t = src[j].m_v8; _mm256_store_ps(&dst[i],t); ++j; } } #if defined __AVX512F__ __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void r4_copy_from_avx512vec16(float * __restrict __ATTR_ALIGN__(64) dst, const AVX512Vec16 * __restrict _ATTTR_ALIGN__(64) src, const int32_t len) { #if defined __GNUC__ && !defined __INTEL_COMPILER dst = (AVX512Vec16*)__builtin_assume_aligned(dst,64); src = (const float*)__builtin_assume_aligned(src,64); #elif defined __INTEL_COMPILER __assume_aligned(dst,64); __assume_aligned(src,64); #endif int32_t j; j = 0; #if defined __ICC || defined __INTEL_COMPILER #pragma code_align(32) #endif for(int32_t i = 0; i != len; i += 16) { const __m512 t = src[j].m_v16; _mm512_store_ps(&dst[i],t); ++j; } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512vec16_copy_from_r4(AVX512Vec16 * __restrict __ATTR_ALIGN__(64) dst, const float * __restrict __ATTR_ALIGN__(64) src, const int32_t len) { #if defined __GNUC__ && !defined __INTEL_COMPILER dst = (AVX512Vec16*)__builtin_assume_aligned(dst,64); src = (const float*)__builtin_assume_aligned(src,64); #elif defined __INTEL_COMPILER __assume_aligned(dst,64); __assume_aligned(src,64); #endif int32_t j; j = 0; #if defined __ICC || defined __INTEL_COMPILER #pragma code_align(32) #endif for(int32_t i = 0; i != len; i += 16){ const __m512 t = _mm512_load_ps(&src[i]); dst[j].m_v16 = t; ++j; } } #endif __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avxc8f32_copy_from_r4(AVXc8f32 * __restrict __ATTR_ALIGN__(32) dst, const float * __restrict __ATTR_ALIGN__(32) src_re, const float * __restrict _ATTR_ALIGN__(32) src_im, const int32_t len) { #if defined __GNUC__ && !defined __INTEL_COMPILER dst = (AVXc8f32*)__builtin_assume_aligned(dst,64); src_re = (const float*)__builtin_assume_aligned(src_re,64); src_im = (const float*)__builtin_assume_aligned(src_im,64); #elif defined __ICC || defined __INTEL_COMPILER __assume_aligned(dst,64); __assume_aligned(src_re,64); __assume_aligned(src_im,64); #endif int32_t j; j = 0; #if defined __ICC || defined __INTEL_COMPILER #pragma code_align(32) #endif for(int64_t i = 0LL; i != len; i += 8LL) { const __m256 tre = _mm256_load_ps(&src_re[i]); dst[j].m_re = tre; const __m256 tim = _mm256_load_ps(&src_im[i]); dst[j].m_im = tim; ++j; } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void r4_copy_from_avxc8f32(float * __restrict __ATTR_ALIGN__(32) dst_re, float * __restrict __ATTR_ALIGN__(32) dst_im, const AVXc8f32 * __restrict _ATTR_ALIGN__(32) src, const int32_t len) { #if defined __GNUC__ && !defined __INTEL_COMPILER dst_re = (float*)__builtin_assume_aligned(dst_re,64); dst_im = (float*)__builtin_assume_aligned(dst_im,64); src = (const AVXc8f32*)__builtin_assume_aligned(src,64); #elif defined __ICC || defined __INTEL_COMPILER __assume_aligned(dst_re,64); __assume_aligned(dst_im,64); __assume_aligned(src,64); #endif int32_t j; j = 0; #if defined __ICC || defined __INTEL_COMPILER #pragma code_align(32) #endif for(int32_t i = 0; i != len; i += 8) { const __m256 tre = src[j].m_re; _mm256_store_ps(&dst_re[i],tre; const __m256 tim = src[j].m_im; _mm256_store_ps(&dst_im[i],tim); } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx256_init_unroll2x_pd( #if defined __ICC || defined __INTEL_COMPILER double * __restrict v, #elif defined __GNUC__ && !defined __INTEL_COMPILER double * __restrict __ATTR_ALIGN__(64), #endif const int32_t vlen, const double val) { __m256d vec = _mm256_set1_pd(val); int32_t i; #if defined __ICC || defined __INTEL_COMPILER #pragma code_align(32) for (i = 0; i != ROUND_TO_FOUR(vlen, 4); i += 8) { _mm256_storeu_pd(&v[i + 0], vec); _mm256_storeu_pd(&v[i + 4], vec); } #pragma loop_count min(1),avg(2),max(3) for(; i != vlen; ++i) { v[i] = val; } #elif defined __GNUC__ && !defined __INTEL_COMPILER if ((reinterpret_cast<uintptr_t>(v)& 0x1F) != 0ULL) { for (i = 0; i != ROUND_TO_FOUR(vlen, 4); i += 8) { _mm256_storeu_pd(&v[i + 0], vec); _mm256_storeu_pd(&v[i + 4], vec); } } else { v = (double*)__builtin_assume_aligned(v,32); for (i = 0; i != ROUND_TO_FOUR(vlen, 4); i += 8) { _mm256_store_pd(&v[i+0], vec); _mm256_store_pd(&v[i+4], vec); } } for (; i != vlen; ++i) { v[i] = val; } #endif } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx256_init_unroll2x_ps( #if defined __ICC || defined __INTEL_COMPILER float * __restrict v, #elif defined __GNUC__ && !defined __INTEL_COMPILER float * __restrict __ATTR_ALIGN__(32) v, #endif const int32_t vlen, const float val) { __m256 ymm0 = _mm256_set1_ps(val); int32_t i; #if defined __ICC || defined __INTEL_COMPILER #pragma code_align(32) for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 16) { _mm256_storeu_ps(&v[i+0], ymm0); _mm256_storeu_ps(&v[i+8], ymm0); } #pragma loop_count min(1),avg(4),max(7) for(; i != vlen; ++i) { v[i] = val; } #elif defined __GNUC__ && !defined __INTEL_COMPILER if((reinterpret_cast<uintptr_t>(v) & 0x1F) != 0ULL) { for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 16) { _mm256_storeu_ps(&v[i+0], ymm0); _mm256_storeu_ps(&v[i+8], ymm0); } } else { v = (float*)__builtin_assume_aligned(v,32); for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 16) { _mm256_store_ps(&v[i+0], ymm0); _mm256_store_ps(&v[i+8], ymm0); } } for(; i != vlen; ++i) { v[i] = val; } #endif } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx256_init_unroll4x_pd( #if defined __ICC || defined __INTEL_COMPILER double * __restrict v, #elif defined __GNUC__ && !defined __INTEL_COMPILER double * __restrict __ATTR_ALIGN__(32) v, #endif const int32_t vlen, const double val) { __m256d vec = _mm256_set1_pd(val); int32_t i; #if defined __ICC || defined __INTEL_COMPILER #pragma code_align(32) for (i = 0; i != ROUND_TO_FOUR(vlen, 4); i += 16) { _mm256_storeu_pd(&v[i + 0], vec); _mm256_storeu_pd(&v[i + 4], vec); _mm256_storeu_pd(&v[i + 8], vec); _mm256_storeu_pd(&v[i + 12], vec); } #pragma loop_count min(1),avg(2),max(3) for (; i != vlen; ++i) { v[i] = val; } #elif defined __GNUC__ && !defined __INTEL_COMPILER if ((reinterpret_cast<uintptr_t>(v)& 0x1F) != 0ULL) { for (i = 0; i != ROUND_TO_FOUR(vlen, 4); i += 16) { _mm256_storeu_pd(&v[i + 0], vec); _mm256_storeu_pd(&v[i + 4], vec); _mm256_storeu_pd(&v[i + 8], vec); _mm256_storeu_pd(&v[i + 12], vec); } } else { v = (double*)__builtin_assume_aligned(v,32); for (i = 0; i != ROUND_TO_FOUR(vlen, 4); i += 16) { _mm256_store_pd(&v[i+0], vec); _mm256_store_pd(&v[i+4], vec); _mm256_store_pd(&v[i+8], vec); _mm256_store_pd(&v[i+12], vec); } } for (; i != vlen; ++i) { v[i] = val; } #endif } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx256_init_unroll4x_ps( #if defined __ICC || defined __INTEL_COMPILER float * __restrict v, #elif defined __GNUC__ && !defined __INTEL_COMPILER float * __restrict __ATTR_ALIGN__(32) v, #endif const int32_t vlen, const float val) { __m256 ymm0 = _mm256_set1_ps(val); int32_t i; #if defined __ICC || defined __INTEL_COMPILER #pragma code_align(32) for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 32) { _mm256_storeu_ps(&v[i+0], ymm0); _mm256_storeu_ps(&v[i+8], ymm0); _mm256_storeu_ps(&v[i+16], ymm0); _mm256_storeu_ps(&v[i+24], ymm0); } #pragma loop_count min(1),avg(4),max(7) for(; i != vlen; ++i) { v[i] = val; } #elif defined __GNUC__ && !defined __INTEL_COMPILER if((reinterpret_cast<uintptr_t>(v) & 0x1F) != 0ULL) { for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 32) { _mm256_storeu_ps(&v[i+0], ymm0); _mm256_storeu_ps(&v[i+8], ymm0); _mm256_storeu_ps(&v[i+16], ymm0); _mm256_storeu_ps(&v[i+24], ymm0); } } else { v = (float*)__builtin_assume_aligned(v,32); for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 32) { _mm256_store_ps(&v[i+0], ymm0); _mm256_store_ps(&v[i+8], ymm0); _mm256_store_ps(&v[i+16], ymm0); _mm256_store_ps(&v[i+24], ymm0); } } for(; i != vlen; ++i) { v[i] = val; } #endif } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx256_init_unroll8x_pd( #if defined __ICC || defined __INTEL_COMPILER double * __restrict v, #elif defined __GNUC__ && !defined __INTEL_COMPILER double * __restrict __ATTR_ALIGN__(32) v, #endif const int32_t vlen, const double val) { __m256d vec = _mm256_set1_pd(val); int32_t i; #if defined __ICC || defined __INTEL_COMPILER #pragma code_align(32) for(i = 0; i != ROUND_TO_FOUR(vlen, 4); i += 32) { _mm256_storeu_pd(&v[i + 0], vec); _mm256_storeu_pd(&v[i + 4], vec); _mm256_storeu_pd(&v[i + 8], vec); _mm256_storeu_pd(&v[i + 12], vec); _mm256_storeu_pd(&v[i + 16], vec); _mm256_storeu_pd(&v[i + 20], vec); _mm256_storeu_pd(&v[i + 24], vec); _mm256_storeu_pd(&v[i + 28], vec); } #pragma loop_count min(1),avg(2),max(3) for (; i != vlen; ++i){ v[i] = val; } #elif defined __GNUC__ && !defined __INTEL_COMPILER if ((reinterpret_cast<uintptr_t>(v)& 0x1F) != 0ULL) { for (i = 0; i != ROUND_TO_FOUR(vlen, 4); i += 32) { _mm256_storeu_pd(&v[i + 0], vec); _mm256_storeu_pd(&v[i + 4], vec); _mm256_storeu_pd(&v[i + 8], vec); _mm256_storeu_pd(&v[i + 12], vec); _mm256_storeu_pd(&v[i + 16], vec); _mm256_storeu_pd(&v[i + 20], vec); _mm256_storeu_pd(&v[i + 24], vec); _mm256_storeu_pd(&v[i + 28], vec); } } else { v = (double*)__builtin_assume_aligned(v,32); for ( i = 0; i != ROUND_TO_FOUR(vlen, 4); i += 32) { _mm256_store_pd(&v[i+0], vec); _mm256_store_pd(&v[i+4], vec); _mm256_store_pd(&v[i+8], vec); _mm256_store_pd(&v[i+12],vec); _mm256_store_pd(&v[i+16],vec); _mm256_store_pd(&v[i+20],vec); _mm256_store_pd(&v[i+24],vec); _mm256_store_pd(&v[i+28],vec); } } for (; i != vlen; ++i){ v[i] = val; } #endif } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx256_init_unroll8x_ps( #if defined __ICC || defined __INTEL_COMPILER float * __restrict v, #elif defined __GNUC__ && !defined __INTEL_COMPILER float * __restrict __ATTR_ALIGN__(32) v, #endif const int32_t vlen, const float val) { __m256 ymm0 = _mm256_set1_ps(val); int32_t i; #if defined __ICC || defined __INTEL_COMPILER #pragma code_align(32) for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 64) { _mm256_storeu_ps(&v[i+0], ymm0); _mm256_storeu_ps(&v[i+8], ymm0); _mm256_storeu_ps(&v[i+16], ymm0); _mm256_storeu_ps(&v[i+24], ymm0); _mm256_storeu_ps(&v[i+32], ymm0); _mm256_storeu_ps(&v[i+40], ymm0); _mm256_storeu_ps(&v[i+48], ymm0); _mm256_storeu_ps(&v[i+56], ymm0); } #pragma loop_count min(1),avg(4),max(7) for(; i != vlen; ++i) { v[i] = val; } #elif defined __GNUC__ && !defined __INTEL_COMPILER if((reinterpret_cast<uintptr_t>(v) & 0x1F) != 0ULL) { for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 64) { _mm256_storeu_ps(&v[i+0], ymm0); _mm256_storeu_ps(&v[i+8], ymm0); _mm256_storeu_ps(&v[i+16], ymm0); _mm256_storeu_ps(&v[i+24], ymm0); _mm256_storeu_ps(&v[i+32], ymm0); _mm256_storeu_ps(&v[i+40], ymm0); _mm256_storeu_ps(&v[i+48], ymm0); _mm256_storeu_ps(&v[i+56], ymm0); } }else { v = (float*)__builtin_assume_aligned(v,32)l for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 64) { _mm256_store_ps(&v[i+0], ymm0); _mm256_store_ps(&v[i+8], ymm0); _mm256_store_ps(&v[i+16], ymm0); _mm256_store_ps(&v[i+24], ymm0); _mm256_store_ps(&v[i+32], ymm0); _mm256_store_ps(&v[i+40], ymm0); _mm256_store_ps(&v[i+48], ymm0); _mm256_store_ps(&v[i+56], ymm0); } } for(; i != vlen; ++i) { v[i] = val; } #endif } #if defined __AVX512F__ __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512_init_unroll2x_pd( #if defined __ICC || defined __INTEL_COMPILER double * __restrict v, #elif defined __GNUC__ && !defined __INTEL_COMPILER double * __restrict __ATTR_ALIGN__(64) v, #endif const int32_t vlen, const double val) { __m512d zmm0 = _mm512_set1_pd(val); int32_t i; #if defined ICC || defined __INTEL_COMPILER #pragma code_align(32) for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 16) { _mm512_storeu_pd(&v[i+0], zmm0); _mm512_storeu_pd(&v[i+8], zmm0); } #pragma loop_count min(1),avg(4),max(7) for(; i != vlen; ++i) { v[i] = val; } #elif defined __GNUC__ && !defined __INTEL_COMPILER if((reinterpret_cast<uintptr_t>(v) & 0x3F) != 0ULL) { for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 16) { _mm512_storeu_pd(&v[i+0], zmm0); _mm512_storeu_pd(&v[i+8], zmm0); } } else { v = (double*)__builtin_assume_aligned(v,64); for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 16) { _mm512_store_pd(&v[i+0], zmm0); _mm512_store_pd(&v[i+8], zmm0); } } for(; i != vlen; ++i) { v[i] = val; } #endif } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512_init_unroll2x_ps( #if defined __ICC || defined __INTEL_COMPILER float * __restrict v, #elif defined __GNUC__ && !defined __INTEL_COMPILER float * __restrict __ATTR_ALIGN__(64) v, #endif const int32_t vlen, const float val) { __m512 zmm0 = _mm512_set1_ps(val); int32_t i; #if defined __ICC || defined __INTEL_COMPILER #pragma code_align(32) for(i = 0; i != ROUND_TO_SIXTEEN(vlen,16); i += 32) { _mm512_storeu_ps(&v[i+0], zmm0); _mm512_storeu_ps(&v[i+16], zmm0); } #pragma loop_count min(1),avg(8),max(1) for(; i != vlen; ++i) { v[i] = val; } #elif defined __GNUC__ && !defined __INTEL_COMPILER if((reinterpret_cast<uintptr_t>(v) & 0x3F) != 0ULL) { for(i = 0; i != ROUND_TO_SIXTEEN(vlen,16); i += 32) { _mm512_storeu_ps(&v[i+0], zmm0); _mm512_storeu_ps(&v[i+16], zmm0); } } else { v = (float*)__builtin_assume_aligned(v,64); for(i = 0; i != ROUND_TO_SIXTEEN(vlen,16); i += 32) { _mm512_store_ps(&v[i+0], zmm0); _mm512_store_ps(&v[i+16], zmm0); } } for(; i != vlen; ++i) { v[i] = val; } #endif } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512_init_unroll4x_pd( #if defined __ICC || defined __INTEL_COMPILER double * __restrict v, #elif defined __GNUC__ && !defined __INTEL_COMPILER double * __restrict __ATTR_ALIGN__(64) v, #endif const int32_t vlen, const double val) { __m512d zmm0 = _mm512_set1_pd(val); int32_t i; #if defined __ICC || defined __INTEL_COMPILER #pragma code_align(32) for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 32) { _mm512_storeu_pd(&v[i+0], zmm0); _mm512_storeu_pd(&v[i+8], zmm0); _mm512_storeu_pd(&v[i+16], zmm0); _mm512_storeu_pd(&v[i+24], zmm0); } #pragma loop_count min(1),avg(4),max(7) for(; i != vlen; ++i) { v[i] = val; } #elif defined __GNUC__ && !defined __INTEL_COMPILER if((reinterpret_cast<uintptr_t>(v) & 0x3F) != 0ULL) { for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 32) { _mm512_storeu_pd(&v[i+0], zmm0); _mm512_storeu_pd(&v[i+8], zmm0); _mm512_storeu_pd(&v[i+16], zmm0); _mm512_storeu_pd(&v[i+24], zmm0); } } else { v = (double*)__builtin_assume_aligned(v,64); for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 32) { _mm512_store_pd(&v[i+0], zmm0); _mm512_store_pd(&v[i+8], zmm0); _mm512_store_pd(&v[i+16], zmm0); _mm512_store_pd(&v[i+24], zmm0); } } for(; i != vlen; ++i) { v[i] = val; } #endif } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512_init_unroll4x_ps( #if defined __ICC || defined __INTEL_COMPILER float * __restrict v, #elif defined __GNUC__ && defined __INTEL_COMPILER float * __restrict __ATTR_ALIIGN__(64) v, #endif const int32_t vlen, const float val) { __m512 zmm0 = _mm512_set1_ps(val); int32_t i; #if defined __ICC || defined __INTEL_COMPILER #pragma code_align(32) for(i = 0; i != ROUND_TO_SIXTEEN(vlen,16); i += 64) { _mm512_storeu_ps(&v[i+0], zmm0); _mm512_storeu_ps(&v[i+16], zmm0); _mm512_storeu_ps(&v[i+32], zmm0); _mm512_storeu_ps(&v[i+48], zmm0); } #pragma loop_count min(1),avg(8),max(15) for(; i != vlen; ++i) { v[i] = val; } #elif defined __GNUC__ && !defined __INTEL_COMPILER if((reinterpret_cast<uintptr_t>(v) & 0x3F) ! = 0ULL) { for(i = 0LL; i != ROUND_TO_SIXTEEN(vlen,16LL); i += 64LL) { _mm512_storeu_ps(&v[i+0LL], zmm0); _mm512_storeu_ps(&v[i+16LL], zmm0); _mm512_storeu_ps(&v[i+32LL], zmm0); _mm512_storeu_ps(&v[i+48LL], zmm0); } } else { v = (float*)__builtin_assume_aligned(v,64); for(i = 0LL; i != ROUND_TO_SIXTEEN(vlen,16LL); i += 64LL) { _mm512_store_ps(&v[i+0LL], zmm0); _mm512_store_ps(&v[i+16LL], zmm0); _mm512_store_ps(&v[i+32LL], zmm0); _mm512_store_ps(&v[i+48LL], zmm0); } } for(; i != vlen; ++i) { v[i] = val; } #endif } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512_init_unroll8x_pd( #if defined __ICC || defined __INTEL_COMPILER double * __restrict v, #elif defined __GNUC__ && !defined __INTEL_COMPILER double * __restrict __ATTR_ALIGN__(64) v, #endif const int32_t vlen, const double val) { __m512d vec = _mm512_set1_pd(val); int32_t i; #if defined __ICC || defined __INTEL_COMPILER for (i = 0; i != ROUND_TO_EIGHT(vlen, 8); i += 64) { _mm512_storeu_pd(&v[i + 0], vec); _mm512_storeu_pd(&v[i + 8], vec); _mm512_storeu_pd(&v[i + 16], vec); _mm512_storeu_pd(&v[i + 24], vec); _mm512_storeu_pd(&v[i + 32], vec); _mm512_storeu_pd(&v[i + 40], vec); _mm512_storeu_pd(&v[i + 48], vec); _mm512_storeu_pd(&v[i + 56], vec); } #pragma loop_count min(1),avg(4),max(7) for (; i != vlen; ++i){ v[i] = val; } #elif defined __GNUC__ && !defined(__INTEL_COMPILER) if ((reinterpret_cast<uintptr_t>(v)& 0x3F) != 0ULL) { for (i = 0; i != ROUND_TO_EIGHT(vlen, 8); i += 64) { _mm512_storeu_pd(&v[i + 0], vec); _mm512_storeu_pd(&v[i + 8], vec); _mm512_storeu_pd(&v[i + 16], vec); _mm512_storeu_pd(&v[i + 24], vec); _mm512_storeu_pd(&v[i + 32], vec); _mm512_storeu_pd(&v[i + 40], vec); _mm512_storeu_pd(&v[i + 48], vec); _mm512_storeu_pd(&v[i + 56], vec); } } else { for (i = 0; i != ROUND_TO_EIGHT(vlen, 8); i += 64) { _mm512_store_pd(&v[i+0],vec); _mm512_store_pd(&v[i+8],vec); _mm512_store_pd(&v[i+16],vec); _mm512_store_pd(&v[i+24],vec); _mm512_store_pd(&v[i+32],vec); _mm512_store_pd(&v[i+40],vec); _mm512_store_pd(&v[i+48],vec); _mm512_store_pd(&v[i+56],vec); } } for (; i != vlen; ++i){ v[i] = val; } #endif } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512_init_unroll8x_ps( #if defined __ICC || defined __INTEL_COMPILER float * __restrict v, #elif defined __GNUC__ && !defined __INTEL_COMPILER float __restrict __ATTR_ALIGN__(64) v, #endif const int32_t vlen, const float val) { __m512 zmm0 = _mm512_set1_ps(val); int32_t i; #if defined __ICC || defined __INTEL_COMPILER #pragma code_align(32) for(i = 0; i != ROUND_TO_SIXTEEN(vlen,16); i += 128) { _mm512_storeu_ps(&v[i+0], zmm0); _mm512_storeu_ps(&v[i+16], zmm0); _mm512_storeu_ps(&v[i+32], zmm0); _mm512_storeu_ps(&v[i+48], zmm0); _mm512_storeu_ps(&v[i+64], zmm0); _mm512_storeu_ps(&v[i+80], zmm0); _mm512_storeu_ps(&v[i+96], zmm0); _mm512_storeu_ps(&v[i+112], zmm0); } #pragma loop_count min(1),avg(8),max(15) for(; i != vlen; ++i) { v[i] = val; } #elif defined __GNUC__ && !defined __INTEL_COMPILER if((reinterpret_cast<uintptr_t>(v) & 0x3F) != 0ULL) { for(i = 0; i != ROUND_TO_SIXTEEN(vlen,16); i += 128) { _mm512_storeu_ps(&v[i+0], zmm0); _mm512_storeu_ps(&v[i+16], zmm0); _mm512_storeu_ps(&v[i+32], zmm0); _mm512_storeu_ps(&v[i+48], zmm0); _mm512_storeu_ps(&v[i+64], zmm0); _mm512_storeu_ps(&v[i+80], zmm0); _mm512_storeu_ps(&v[i+96], zmm0); _mm512_storeu_ps(&v[i+112], zmm0); } } else { v = (float*)__builtin_assume_aligned(v,64); for(i = 0LL; i != ROUND_TO_SIXTEEN(vlen,16LL); i += 128) { _mm512_store_ps(&v[i+0LL], zmm0); _mm512_store_ps(&v[i+16LL], zmm0); _mm512_store_ps(&v[i+32LL], zmm0); _mm512_store_ps(&v[i+48LL], zmm0); _mm512_store_ps(&v[i+64LL], zmm0); _mm512_store_ps(&v[i+80LL], zmm0); _mm512_store_ps(&v[i+96LL], zmm0); _mm512_store_ps(&v[i+112LL], zmm0); } } for(; i != vlen; ++i) { v[i] = val; } #endif } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512_init_ps( #if defined __ICC || defined __INTEL_COMPILER float * __restrict v, #elif defined __GNUC__ && !defined __INTEL_COMPILER float __restrict __ATTR_ALIGN__(64) v, #endif const int32_t vlen, const float val) { __m512 zmm = _mm512_set1_ps(val); #if defined __ICC || defined __INTEL_COMPILER if(vlen <= MEMMOVE_1ELEM) { return; } else if(vlen <= MEMMOVE_16ELEMS) { _mm512_storeu_ps(&v[0],zmm); return; } else if(vlen <= MEMMOVE_32ELEMS) { _mm512_storeu_ps(&v[0],zmm); _mm512_storeu_ps(&v[1*ZMM_LEN],zmm); return; } else if(vlen <= MEMMOVE_64ELEMS) { _mm512_storeu_ps(&v[0],zmm); _mm512_storeu_ps(&v[1*ZMM_LEN],zmm); _mm512_storeu_ps(&v[2*ZMM_LEN],zmm); _mm512_storeu_ps(&v[3*ZMM_LEN],zmm); return; } else if(vlen <= MEMMOVE_128ELEMS) { _mm512_storeu_ps(&v[0],zmm); _mm512_storeu_ps(&v[1*ZMM_LEN],zmm); _mm512_storeu_ps(&v[2*ZMM_LEN],zmm); _mm512_storeu_ps(&v[3*ZMM_LEN],zmm); _mm512_storeu_ps(&v[4*ZMM_LEN],zmm); _mm512_storeu_ps(&v[5*ZMM_LEN],zmm); _mm512_storeu_ps(&v[6*ZMM_LEN],zmm); _mm512_storeu_ps(&v[7*ZMM_LEN],zmm); return; } else if(vlen <= MEMMOVE_256ELEMS) { _mm512_storeu_ps(&v[0],zmm); _mm512_storeu_ps(&v[1*ZMM_LEN],zmm); _mm512_storeu_ps(&v[2*ZMM_LEN],zmm); _mm512_storeu_ps(&v[3*ZMM_LEN],zmm); _mm512_storeu_ps(&v[4*ZMM_LEN],zmm); _mm512_storeu_ps(&v[5*ZMM_LEN],zmm); _mm512_storeu_ps(&v[6*ZMM_LEN],zmm); _mm512_storeu_ps(&v[7*ZMM_LEN],zmm); _mm512_storeu_ps(&v[8*ZMM_LEN],zmm); _mm512_storeu_ps(&v[9*ZMM_LEN],zmm); _mm512_storeu_ps(&v[10*ZMM_LEN],zmm); _mm512_storeu_ps(&v[11*ZMM_LEN],zmm); _mm512_storeu_ps(&v[12*ZMM_LEN],zmm); _mm512_storeu_ps(&v[13*ZMM_LEN],zmm); _mm512_storeu_ps(&v[14*ZMM_LEN],zmm); _mm512_storeu_ps(&v[15*ZMM_LEN],zmm); return; } else if(vlen > MEMMOVE_256ELEMS) { int32_t i; #pragma code_align(32) for(i = 0; i != ROUND_TO_SIXTEEN(vlen,16); i += 128) { _mm512_storeu_ps(&v[i+0], zmm); _mm512_storeu_ps(&v[i+16], zmm); _mm512_storeu_ps(&v[i+32], zmm); _mm512_storeu_ps(&v[i+48], zmm); _mm512_storeu_ps(&v[i+64], zmm); _mm512_storeu_ps(&v[i+80], zmm); _mm512_storeu_ps(&v[i+96], zmm); _mm512_storeu_ps(&v[i+112], zmm); } #pragma loop_count min(1),avg(8),max(15) for(; i != vlen; ++i) { v[i] = val; } return; } #elif defined __GNUC__ && !defined __INTEL_COMPILER if((reinterpret_cast<uintptr_t>(v) & 0x3F) != 0ULL) { if(vlen <= MEMMOVE_1ELEM) { return; } else if(vlen <= MEMMOVE_16ELEMS) { _mm512_storeu_ps(&v[0],zmm); return; } else if(vlen <= MEMMOVE_32ELEMS) { _mm512_storeu_ps(&v[0],zmm); _mm512_storeu_ps(&v[1*ZMM_LEN],zmm); return; } else if(vlen <= MEMMOVE_64ELEMS) { _mm512_storeu_ps(&v[0],zmm); _mm512_storeu_ps(&v[1*ZMM_LEN],zmm); _mm512_storeu_ps(&v[2*ZMM_LEN],zmm); _mm512_storeu_ps(&v[3*ZMM_LEN],zmm); return; } else if(vlen <= MEMMOVE_128ELEMS) { _mm512_storeu_ps(&v[0],zmm); _mm512_storeu_ps(&v[1*ZMM_LEN],zmm); _mm512_storeu_ps(&v[2*ZMM_LEN],zmm); _mm512_storeu_ps(&v[3*ZMM_LEN],zmm); _mm512_storeu_ps(&v[4*ZMM_LEN],zmm); _mm512_storeu_ps(&v[5*ZMM_LEN],zmm); _mm512_storeu_ps(&v[6*ZMM_LEN],zmm); _mm512_storeu_ps(&v[7*ZMM_LEN],zmm); return; } else if(vlen <= MEMMOVE_256ELEMS) { _mm512_storeu_ps(&v[0],zmm); _mm512_storeu_ps(&v[1*ZMM_LEN],zmm); _mm512_storeu_ps(&v[2*ZMM_LEN],zmm); _mm512_storeu_ps(&v[3*ZMM_LEN],zmm); _mm512_storeu_ps(&v[4*ZMM_LEN],zmm); _mm512_storeu_ps(&v[5*ZMM_LEN],zmm); _mm512_storeu_ps(&v[6*ZMM_LEN],zmm); _mm512_storeu_ps(&v[7*ZMM_LEN],zmm); _mm512_storeu_ps(&v[8*ZMM_LEN],zmm); _mm512_storeu_ps(&v[9*ZMM_LEN],zmm); _mm512_storeu_ps(&v[10*ZMM_LEN],zmm); _mm512_storeu_ps(&v[11*ZMM_LEN],zmm); _mm512_storeu_ps(&v[12*ZMM_LEN],zmm); _mm512_storeu_ps(&v[13*ZMM_LEN],zmm); _mm512_storeu_ps(&v[14*ZMM_LEN],zmm); _mm512_storeu_ps(&v[15*ZMM_LEN],zmm); return; } else if(vlen > MEMMOVE_256ELEMS) { for(i = 0; i != ROUND_TO_SIXTEEN(vlen,16); i += 128) { _mm512_storeu_ps(&v[i+0], zmm); _mm512_storeu_ps(&v[i+16], zmm); _mm512_storeu_ps(&v[i+32], zmm); _mm512_storeu_ps(&v[i+48], zmm); _mm512_storeu_ps(&v[i+64], zmm); _mm512_storeu_ps(&v[i+80], zmm); _mm512_storeu_ps(&v[i+96], zmm); _mm512_storeu_ps(&v[i+112], zmm); } for(; i != vlen; ++i) { v[i] = val; } return; } else { if(vlen <= MEMMOVE_1ELEM) { return; } else if(vlen <= MEMMOVE_16ELEMS) { _mm512_store_ps(&v[0],zmm); return; } else if(vlen <= MEMMOVE_32ELEMS) { _mm512_store_ps(&v[0],zmm); _mm512_store_ps(&v[1*ZMM_LEN],zmm); return; } else if(vlen <= MEMMOVE_64ELEMS) { _mm512_store_ps(&v[0],zmm); _mm512_store_ps(&v[1*ZMM_LEN],zmm); _mm512_store_ps(&v[2*ZMM_LEN],zmm); _mm512_store_ps(&v[3*ZMM_LEN],zmm); return; } else if(vlen <= MEMMOVE_128ELEMS) { _mm512_store_ps(&v[0],zmm); _mm512_store_ps(&v[1*ZMM_LEN],zmm); _mm512_store_ps(&v[2*ZMM_LEN],zmm); _mm512_store_ps(&v[3*ZMM_LEN],zmm); _mm512_store_ps(&v[4*ZMM_LEN],zmm); _mm512_store_ps(&v[5*ZMM_LEN],zmm); _mm512_store_ps(&v[6*ZMM_LEN],zmm); _mm512_store_ps(&v[7*ZMM_LEN],zmm); return; } else if(vlen <= MEMMOVE_256ELEMS) { _mm512_store_ps(&v[0],zmm); _mm512_store_ps(&v[1*ZMM_LEN],zmm); _mm512_store_ps(&v[2*ZMM_LEN],zmm); _mm512_store_ps(&v[3*ZMM_LEN],zmm); _mm512_store_ps(&v[4*ZMM_LEN],zmm); _mm512_store_ps(&v[5*ZMM_LEN],zmm); _mm512_store_ps(&v[6*ZMM_LEN],zmm); _mm512_store_ps(&v[7*ZMM_LEN],zmm); _mm512_store_ps(&v[8*ZMM_LEN],zmm); _mm512_store_ps(&v[9*ZMM_LEN],zmm); _mm512_store_ps(&v[10*ZMM_LEN],zmm); _mm512_store_ps(&v[11*ZMM_LEN],zmm); _mm512_store_ps(&v[12*ZMM_LEN],zmm); _mm512_store_ps(&v[13*ZMM_LEN],zmm); _mm512_store_ps(&v[14*ZMM_LEN],zmm); _mm512_store_ps(&v[15*ZMM_LEN],zmm); return; } else if(vlen > MEMMOVE_256ELEMS) { v = (float*)__builtin_assume_aligned(v,64); for(i = 0; i != ROUND_TO_SIXTEEN(vlen,16); i += 128) { _mm512_store_ps(&v[i+0], zmm); _mm512_store_ps(&v[i+16], zmm); _mm512_store_ps(&v[i+32], zmm); _mm512_store_ps(&v[i+48], zmm); _mm512_store_ps(&v[i+64], zmm); _mm512_store_ps(&v[i+80], zmm); _mm512_store_ps(&v[i+96], zmm); _mm512_store_ps(&v[i+112], zmm); } for(; i != vlen; ++i) { v[i] = val; } return; } #endif } #endif // __AVX512F__ __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx256_init_ps( #if defined __ICC || defined __INTEL_COMPILER float * __restrict v, #elif defined __GNUC__ && !defined __INTEL_COMPILER float __restrict __ATTR_ALIGN__(32) v, #endif const int32_t vlen, const float val) { __m256 ymm = _mm256_set1_ps(val); #if defined __ICC || defined __INTEL_COMPILER if(vlen <= MEMMOVE_1ELEM) { return; } else if(vlen <= MEMMOVE_16ELEMS) { _mm256_storeu_ps(&v[0],ymm); _mm256_storeu_ps(&v[1*YMM_LEN],ymm); return; } else if(vlen <= MEMMOVE_32ELEMS) { _mm256_storeu_ps(&v[0],ymm); _mm256_storeu_ps(&v[1*YMM_LEN],ymm); _mm256_storeu_ps(&v[2*YMM_LEN],ymm) _mm256_storeu_ps(&v[3*YMM_LEN],ymm); return; } else if(vlen <= MEMMOVE_64ELEMS) { _mm256_storeu_ps(&v[0],ymm); _mm256_storeu_ps(&v[1*YMM_LEN],ymm); _mm256_storeu_ps(&v[2*YMM_LEN],ymm) _mm256_storeu_ps(&v[3*YMM_LEN],ymm); _mm256_storeu_ps(&v[4*YMM_LEN],ymm); _mm256_storeu_ps(&v[5*YMM_LEN],ymm); _mm256_storeu_ps(&v[6*YMM_LEN],ymm); _mm256_storeu_ps(&v[7*YMM_LEN],ymm); return; } else if(vlen <= MEMMOVE_128ELEMS) { _mm256_storeu_ps(&v[0],ymm); _mm256_storeu_ps(&v[1*YMM_LEN],ymm); _mm256_storeu_ps(&v[2*YMM_LEN],ymm) _mm256_storeu_ps(&v[3*YMM_LEN],ymm); _mm256_storeu_ps(&v[4*YMM_LEN],ymm); _mm256_storeu_ps(&v[5*YMM_LEN],ymm); _mm256_storeu_ps(&v[6*YMM_LEN],ymm); _mm256_storeu_ps(&v[7*YMM_LEN],ymm); _mm256_storeu_ps(&v[8*YMM_LEN],ymm); _mm256_storeu_ps(&v[9*YMM_LEN],ymm); _mm256_storeu_ps(&v[10*YMM_LEN],ymm); _mm256_storeu_ps(&v[11*YMM_LEN],ymm); _mm256_storeu_ps(&v[12*YMM_LEN],ymm); _mm256_storeu_ps(&v[13*YMM_LEN],ymm); _mm256_storeu_ps(&v[14*YMM_LEN],ymm); _mm256_storeu_ps(&v[15*YMM_LEN],ymm); return; } else if(vlen > MEMMOVE_128ELEMS) { int32_t i; #pragma code_align(32) for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 64) { _mm256_storeu_ps(&v[i+0], ymm0); _mm256_storeu_ps(&v[i+8], ymm0); _mm256_storeu_ps(&v[i+16], ymm0); _mm256_storeu_ps(&v[i+24], ymm0); _mm256_storeu_ps(&v[i+32], ymm0); _mm256_storeu_ps(&v[i+40], ymm0); _mm256_storeu_ps(&v[i+48], ymm0); _mm256_storeu_ps(&v[i+56], ymm0); } #pragma loop_count min(1),avg(4),max(7) for(; i != vlen; ++i) { v[i] = val; } } #elif defined __GNUC__ && !defined __INTEL_COMPILER if((reinterpret_cast<uintptr_t>(v) & 0x1F) != 0ULL) { if(vlen <= MEMMOVE_1ELEM) { return; } else if(vlen <= MEMMOVE_16ELEMS) { _mm256_storeu_ps(&v[0],ymm); _mm256_storeu_ps(&v[1*YMM_LEN],ymm); return; } else if(vlen <= MEMMOVE_32ELEMS) { _mm256_storeu_ps(&v[0],ymm); _mm256_storeu_ps(&v[1*YMM_LEN],ymm); _mm256_storeu_ps(&v[2*YMM_LEN],ymm) _mm256_storeu_ps(&v[3*YMM_LEN],ymm); return; } else if(vlen <= MEMMOVE_64ELEMS) { _mm256_storeu_ps(&v[0],ymm); _mm256_storeu_ps(&v[1*YMM_LEN],ymm); _mm256_storeu_ps(&v[2*YMM_LEN],ymm) _mm256_storeu_ps(&v[3*YMM_LEN],ymm); _mm256_storeu_ps(&v[4*YMM_LEN],ymm); _mm256_storeu_ps(&v[5*YMM_LEN],ymm); _mm256_storeu_ps(&v[6*YMM_LEN],ymm); _mm256_storeu_ps(&v[7*YMM_LEN],ymm); return; } else if(vlen <= MEMMOVE_128ELEMS) { _mm256_storeu_ps(&v[0],ymm); _mm256_storeu_ps(&v[1*YMM_LEN],ymm); _mm256_storeu_ps(&v[2*YMM_LEN],ymm) _mm256_storeu_ps(&v[3*YMM_LEN],ymm); _mm256_storeu_ps(&v[4*YMM_LEN],ymm); _mm256_storeu_ps(&v[5*YMM_LEN],ymm); _mm256_storeu_ps(&v[6*YMM_LEN],ymm); _mm256_storeu_ps(&v[7*YMM_LEN],ymm); _mm256_storeu_ps(&v[8*YMM_LEN],ymm); _mm256_storeu_ps(&v[9*YMM_LEN],ymm); _mm256_storeu_ps(&v[10*YMM_LEN],ymm); _mm256_storeu_ps(&v[11*YMM_LEN],ymm); _mm256_storeu_ps(&v[12*YMM_LEN],ymm); _mm256_storeu_ps(&v[13*YMM_LEN],ymm); _mm256_storeu_ps(&v[14*YMM_LEN],ymm); _mm256_storeu_ps(&v[15*YMM_LEN],ymm); return; } else if(vlen > MEMMOVE_128ELEMS) { int32_t i; for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 64) { _mm256_storeu_ps(&v[i+0], ymm0); _mm256_storeu_ps(&v[i+8], ymm0); _mm256_storeu_ps(&v[i+16], ymm0); _mm256_storeu_ps(&v[i+24], ymm0); _mm256_storeu_ps(&v[i+32], ymm0); _mm256_storeu_ps(&v[i+40], ymm0); _mm256_storeu_ps(&v[i+48], ymm0); _mm256_storeu_ps(&v[i+56], ymm0); } for(; i != vlen; ++i) { v[i] = val; } }else { if(vlen <= MEMMOVE_1ELEM) { return; } else if(vlen <= MEMMOVE_16ELEMS) { _mm256_store_ps(&v[0],ymm); _mm256_store_ps(&v[1*YMM_LEN],ymm); return; } else if(vlen <= MEMMOVE_32ELEMS) { _mm256_store_ps(&v[0],ymm); _mm256_store_ps(&v[1*YMM_LEN],ymm); _mm256_store_ps(&v[2*YMM_LEN],ymm) _mm256_store_ps(&v[3*YMM_LEN],ymm); return; } else if(vlen <= MEMMOVE_64ELEMS) { _mm256_store_ps(&v[0],ymm); _mm256_store_ps(&v[1*YMM_LEN],ymm); _mm256_store_ps(&v[2*YMM_LEN],ymm) _mm256_store_ps(&v[3*YMM_LEN],ymm); _mm256_store_ps(&v[4*YMM_LEN],ymm); _mm256_store_ps(&v[5*YMM_LEN],ymm); _mm256_store_ps(&v[6*YMM_LEN],ymm); _mm256_store_ps(&v[7*YMM_LEN],ymm); return; } else if(vlen <= MEMMOVE_128ELEMS) { _mm256_store_ps(&v[0],ymm); _mm256_store_ps(&v[1*YMM_LEN],ymm); _mm256_store_ps(&v[2*YMM_LEN],ymm) _mm256_store_ps(&v[3*YMM_LEN],ymm); _mm256_store_ps(&v[4*YMM_LEN],ymm); _mm256_store_ps(&v[5*YMM_LEN],ymm); _mm256_store_ps(&v[6*YMM_LEN],ymm); _mm256_store_ps(&v[7*YMM_LEN],ymm); _mm256_store_ps(&v[8*YMM_LEN],ymm); _mm256_store_ps(&v[9*YMM_LEN],ymm); _mm256_store_ps(&v[10*YMM_LEN],ymm); _mm256_store_ps(&v[11*YMM_LEN],ymm); _mm256_store_ps(&v[12*YMM_LEN],ymm); _mm256_store_ps(&v[13*YMM_LEN],ymm); _mm256_store_ps(&v[14*YMM_LEN],ymm); _mm256_store_ps(&v[15*YMM_LEN],ymm); return; } else if(vlen > MEMMOVE_128ELEMS) { v = (float*)__builtin_assume_aligned(v,32); int32_t i; for(i = 0; i != ROUND_TO_EIGHT(vlen,8); i += 64) { _mm256_store_ps(&v[i+0], ymm0); _mm256_store_ps(&v[i+8], ymm0); _mm256_store_ps(&v[i+16], ymm0); _mm256_store_ps(&v[i+24], ymm0); _mm256_store_ps(&v[i+32], ymm0); _mm256_store_ps(&v[i+40], ymm0); _mm256_store_ps(&v[i+48], ymm0); _mm256_store_ps(&v[i+56], ymm0); } for(; i != vlen; ++i) { v[i] = val; } } #endif } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx256_memcpy_ps( #if defined __ICC || defined __INTEL_COMPILER float * __restrict dst, const float * __restrict src, #elif defined __GNUC__ && !defined __INTEL_COMPILER float * __restrict __ATTR_ALIGN__(32) dst, const float * __restrict __ATTR_ALIGN__(32) src, #endif const int32_t len) { #if defined __ICC || defined __INTEL_COMPILER if(len <= MEMMOVE_1ELEM) { return; } else if(len <= MEMMOVE_16ELEMS) { const __m256 ymm0 = _mm256_loadu_ps(&src[0]); _mm256_storeu_ps(&dst[0],ymm0); const __m256 ymm1 = _mm256_loadu_ps(&src[1*YMM_LEN]); _mm256_storeu_ps(&dst[1*YMM_LEN],ymm1); return; } else if(len <= MEMMOVE_32ELEMS) { const __m256 ymm0 = _mm256_loadu_ps(&src[0]); _mm256_storeu_ps(&dst[0],ymm0); const __m256 ymm1 = _mm256_loadu_ps(&src[1*YMM_LEN]); _mm256_storeu_ps(&dst[1*YMM_LEN],ymm1); const __m256 ymm2 = _mm256_loadu_ps(&src[2*YMM_LEN]); _mm256_storeu_ps(&dst[2*YMM_LEN],ymm2); const _mm256 ymm3 = _mm256_loadu_ps(&src[3*YMM_LEN]); _mm256_storeu_ps(&dst[3*YMM_LEN],ymm3); return; } else if(len <= MEMMOVE_64ELEMS) { const __m256 ymm0 = _mm256_loadu_ps(&src[0]); _mm256_storeu_ps(&dst[0],ymm0); const __m256 ymm1 = _mm256_loadu_ps(&src[1*YMM_LEN]); _mm256_storeu_ps(&dst[1*YMM_LEN],ymm1); const __m256 ymm2 = _mm256_loadu_ps(&src[2*YMM_LEN]); _mm256_storeu_ps(&dst[2*YMM_LEN],ymm2); const _mm256 ymm3 = _mm256_loadu_ps(&src[3*YMM_LEN]); _mm256_storeu_ps(&dst[3*YMM_LEN],ymm3); const __m256 ymm4 = _mm256_loadu_ps(&src[4*YMM_LEN]); _mm256_storeu_ps(&dst[4*YMM_LEN],ymm4); const __m256 ymm5 = _mm256_loadu_ps(&src[5*YMM_LEN]); _mm256_storeu_ps(&dst[5*YMM_LEN],ymm5); const __m256 ymm6 = _mm256_loadu_ps(&src[6*YMM_LEN]); _mm256_storeu_ps(&dst[6*YMM_LEN],ymm6); const __m256 ymm7 = _mm256_loadu_ps(&src[7*YMM_LEN]); _mm256_storeu_ps(&dst[7*YMM_LEN],ymm7); return; } else if(len <= MEMMOVE_128ELEMS) { #if (GMS_MAN_PREFETCH) == 1 _mm_prefetch((const char*)&src[0], _MM_HINT_T0); _mm_prefetch((const char*)&src[2*YMM_LEN],_MM_HINT_T0); _mm_prefetch((const char*)&src[4*YMM_LEN],_MM_HINT_T0); _mm_prefetch((const char*)&src[6*YMM_LEN],_MM_HINT_T0); _mm_prefetch((const char*)&src[8*YMM_LEN],_MM_HINT_T0); #endif const __m256 ymm0 = _mm256_loadu_ps(&src[0]); _mm256_storeu_ps(&dst[0],ymm0); const __m256 ymm1 = _mm256_loadu_ps(&src[1*YMM_LEN]); _mm256_storeu_ps(&dst[1*YMM_LEN],ymm1); const __m256 ymm2 = _mm256_loadu_ps(&src[2*YMM_LEN]); _mm256_storeu_ps(&dst[2*YMM_LEN],ymm2); const _mm256 ymm3 = _mm256_loadu_ps(&src[3*YMM_LEN]); _mm256_storeu_ps(&dst[3*YMM_LEN],ymm3); const __m256 ymm4 = _mm256_loadu_ps(&src[4*YMM_LEN]); _mm256_storeu_ps(&dst[4*YMM_LEN],ymm4); const __m256 ymm5 = _mm256_loadu_ps(&src[5*YMM_LEN]); _mm256_storeu_ps(&dst[5*YMM_LEN],ymm5); const __m256 ymm6 = _mm256_loadu_ps(&src[6*YMM_LEN]); _mm256_storeu_ps(&dst[6*YMM_LEN],ymm6); const __m256 ymm7 = _mm256_loadu_ps(&src[7*YMM_LEN]); _mm256_storeu_ps(&dst[7*YMM_LEN],ymm7); const __m256 ymm8 = _mm256_loadu_ps(&src[8*YMM_LEN]); _mm256_storeu_ps(&dst[8*YMM_LEN],ymm8); const __m256 ymm9 = _mm256_loadu_ps(&src[9*YMM_LEN]); _mm256_storeu_ps(&dst[9*YMM_LEN],ymm9); const __m256 ymm10 = _mm256_loadu_ps(&src[10*YMM_LEN]); _mm256_storeu_ps(&dst[10*YMM_LEN],ymm10); const __m256 ymm11 = _mm256_loadu_ps(&src[11*YMM_LEN]); _mm256_storeu_ps(&dst[11*YMM_LEN],ymm11); const __m256 ymm12 = _mm256_loadu_ps(&src[12*YMM_LEN]); _mm256_storeu_ps(&dst[12*YMM_LEN],ymm12); const __m256 ymm13 = _mm256_loadu_ps(&src[13*YMM_LEN]); _mm256_storeu_ps(&dst[13*YMM_LEN],ymm13); const __m256 ymm14 = _mm256_loadu_ps(&src[14*YMM_LEN]); _mm256_storeu_ps(&dst[14*YMM_LEN],ymm14); const __m256 ymm15 = _mm256_loadu_ps(&src[15*YMM_LEN]); _mm256_storeu_ps(&dst[15*YMM_LEN],ymm155); return; } else if(len > MEMMOVE_128ELEMS) { int32_t i; #pragma code_align(32) for(i = 0; i != ROUND_TO_EIGHT(len,8); i += 64) { #if (GMS_MAN_PREFETCH) == 1 _mm_prefetch((const char*)&src[i+0], _MM_HINT_T0); _mm_prefetch((const char*)&src[i+2*YMM_LEN],_MM_HINT_T0); _mm_prefetch((const char*)&src[i+4*YMM_LEN],_MM_HINT_T0); #endif const __m256 ymm0 = _mm256_loadu_ps(&src[i+0]); _mm256_storeu_ps(&dst[i+0],ymm0); const __m256 ymm1 = _mm256_loadu_ps(&src[i+1*YMM_LEN]); _mm256_storeu_ps(&dst[i+1*YMM_LEN],ymm1); const __m256 ymm2 = _mm256_loadu_ps(&src[i+2*YMM_LEN]); _mm256_storeu_ps(&dst[i+2*YMM_LEN],ymm2); const _mm256 ymm3 = _mm256_loadu_ps(&src[i+3*YMM_LEN]); _mm256_storeu_ps(&dst[i+3*YMM_LEN],ymm3); const __m256 ymm4 = _mm256_loadu_ps(&src[i+4*YMM_LEN]); _mm256_storeu_ps(&dst[i+4*YMM_LEN],ymm4); const __m256 ymm5 = _mm256_loadu_ps(&src[i+5*YMM_LEN]); _mm256_storeu_ps(&dst[i+5*YMM_LEN],ymm5); const __m256 ymm6 = _mm256_loadu_ps(&src[i+6*YMM_LEN]); _mm256_storeu_ps(&dst[i+6*YMM_LEN],ymm6); const __m256 ymm7 = _mm256_loadu_ps(&src[i+7*YMM_LEN]); _mm256_storeu_ps(&dst[i+7*YMM_LEN],ymm7); } #pragma loop_count min(1),avg(4),max(7) for(; i != len; ++i) { dst[i] = src[i]; } return; } #elif defined __GNUC__ && !defined __INTEL_COMPILER if ((reinterpret_cast<uintptr_t>(dst)& 0x1F) != 0ULL && (reinterpret_cast<uintptr_t>(src)& 0x1F) != 0ULL) { if(len <= MEMMOVE_1ELEM) { return; } else if(len <= MEMMOVE_16ELEMS) { const __m256 ymm0 = _mm256_loadu_ps(&src[0]); _mm256_storeu_ps(&dst[0],ymm0); const __m256 ymm1 = _mm256_loadu_ps(&src[1*YMM_LEN]); _mm256_storeu_ps(&dst[1*YMM_LEN],ymm1); return; } else if(len <= MEMMOVE_32ELEMS) { const __m256 ymm0 = _mm256_loadu_ps(&src[0]); _mm256_storeu_ps(&dst[0],ymm0); const __m256 ymm1 = _mm256_loadu_ps(&src[1*YMM_LEN]); _mm256_storeu_ps(&dst[1*YMM_LEN],ymm1); const __m256 ymm2 = _mm256_loadu_ps(&src[2*YMM_LEN]); _mm256_storeu_ps(&dst[2*YMM_LEN],ymm2); const _mm256 ymm3 = _mm256_loadu_ps(&src[3*YMM_LEN]); _mm256_storeu_ps(&dst[3*YMM_LEN],ymm3); return; } else if(len <= MEMMOVE_64ELEMS) { const __m256 ymm0 = _mm256_loadu_ps(&src[0]); _mm256_storeu_ps(&dst[0],ymm0); const __m256 ymm1 = _mm256_loadu_ps(&src[1*YMM_LEN]); _mm256_storeu_ps(&dst[1*YMM_LEN],ymm1); const __m256 ymm2 = _mm256_loadu_ps(&src[2*YMM_LEN]); _mm256_storeu_ps(&dst[2*YMM_LEN],ymm2); const _mm256 ymm3 = _mm256_loadu_ps(&src[3*YMM_LEN]); _mm256_storeu_ps(&dst[3*YMM_LEN],ymm3); const __m256 ymm4 = _mm256_loadu_ps(&src[4*YMM_LEN]); _mm256_storeu_ps(&dst[4*YMM_LEN],ymm4); const __m256 ymm5 = _mm256_loadu_ps(&src[5*YMM_LEN]); _mm256_storeu_ps(&dst[5*YMM_LEN],ymm5); const __m256 ymm6 = _mm256_loadu_ps(&src[6*YMM_LEN]); _mm256_storeu_ps(&dst[6*YMM_LEN],ymm6); const __m256 ymm7 = _mm256_loadu_ps(&src[7*YMM_LEN]); _mm256_storeu_ps(&dst[7*YMM_LEN],ymm7); return; } else if(len <= MEMMOVE_128ELEMS) { #if (GMS_MAN_PREFETCH) == 1 _mm_prefetch((const char*)&src[0], _MM_HINT_T0); _mm_prefetch((const char*)&src[2*YMM_LEN],_MM_HINT_T0); _mm_prefetch((const char*)&src[4*YMM_LEN],_MM_HINT_T0); _mm_prefetch((const char*)&src[6*YMM_LEN],_MM_HINT_T0); _mm_prefetch((const char*)&src[8*YMM_LEN],_MM_HINT_T0); #endif const __m256 ymm0 = _mm256_loadu_ps(&src[0]); _mm256_storeu_ps(&dst[0],ymm0); const __m256 ymm1 = _mm256_loadu_ps(&src[1*YMM_LEN]); _mm256_storeu_ps(&dst[1*YMM_LEN],ymm1); const __m256 ymm2 = _mm256_loadu_ps(&src[2*YMM_LEN]); _mm256_storeu_ps(&dst[2*YMM_LEN],ymm2); const _mm256 ymm3 = _mm256_loadu_ps(&src[3*YMM_LEN]); _mm256_storeu_ps(&dst[3*YMM_LEN],ymm3); const __m256 ymm4 = _mm256_loadu_ps(&src[4*YMM_LEN]); _mm256_storeu_ps(&dst[4*YMM_LEN],ymm4); const __m256 ymm5 = _mm256_loadu_ps(&src[5*YMM_LEN]); _mm256_storeu_ps(&dst[5*YMM_LEN],ymm5); const __m256 ymm6 = _mm256_loadu_ps(&src[6*YMM_LEN]); _mm256_storeu_ps(&dst[6*YMM_LEN],ymm6); const __m256 ymm7 = _mm256_loadu_ps(&src[7*YMM_LEN]); _mm256_storeu_ps(&dst[7*YMM_LEN],ymm7); const __m256 ymm8 = _mm256_loadu_ps(&src[8*YMM_LEN]); _mm256_storeu_ps(&dst[8*YMM_LEN],ymm8); const __m256 ymm9 = _mm256_loadu_ps(&src[9*YMM_LEN]); _mm256_storeu_ps(&dst[9*YMM_LEN],ymm9); const __m256 ymm10 = _mm256_loadu_ps(&src[10*YMM_LEN]); _mm256_storeu_ps(&dst[10*YMM_LEN],ymm10); const __m256 ymm11 = _mm256_loadu_ps(&src[11*YMM_LEN]); _mm256_storeu_ps(&dst[11*YMM_LEN],ymm11); const __m256 ymm12 = _mm256_loadu_ps(&src[12*YMM_LEN]); _mm256_storeu_ps(&dst[12*YMM_LEN],ymm12); const __m256 ymm13 = _mm256_loadu_ps(&src[13*YMM_LEN]); _mm256_storeu_ps(&dst[13*YMM_LEN],ymm13); const __m256 ymm14 = _mm256_loadu_ps(&src[14*YMM_LEN]); _mm256_storeu_ps(&dst[14*YMM_LEN],ymm14); const __m256 ymm15 = _mm256_loadu_ps(&src[15*YMM_LEN]); _mm256_storeu_ps(&dst[15*YMM_LEN],ymm155); return; } else if(len > MEMMOVE_128ELEMS) { int32_t i; for(i = 0; i != ROUND_TO_EIGHT(len,8); i += 64) { #if (GMS_MAN_PREFETCH) == 1 _mm_prefetch((const char*)&src[i+0], _MM_HINT_T0); _mm_prefetch((const char*)&src[i+2*YMM_LEN],_MM_HINT_T0); _mm_prefetch((const char*)&src[i+4*YMM_LEN],_MM_HINT_T0); #endif const __m256 ymm0 = _mm256_loadu_ps(&src[i+0]); _mm256_storeu_ps(&dst[i+0],ymm0); const __m256 ymm1 = _mm256_loadu_ps(&src[i+1*YMM_LEN]); _mm256_storeu_ps(&dst[i+1*YMM_LEN],ymm1); const __m256 ymm2 = _mm256_loadu_ps(&src[i+2*YMM_LEN]); _mm256_storeu_ps(&dst[i+2*YMM_LEN],ymm2); const _mm256 ymm3 = _mm256_loadu_ps(&src[i+3*YMM_LEN]); _mm256_storeu_ps(&dst[i+3*YMM_LEN],ymm3); const __m256 ymm4 = _mm256_loadu_ps(&src[i+4*YMM_LEN]); _mm256_storeu_ps(&dst[i+4*YMM_LEN],ymm4); const __m256 ymm5 = _mm256_loadu_ps(&src[i+5*YMM_LEN]); _mm256_storeu_ps(&dst[i+5*YMM_LEN],ymm5); const __m256 ymm6 = _mm256_loadu_ps(&src[i+6*YMM_LEN]); _mm256_storeu_ps(&dst[i+6*YMM_LEN],ymm6); const __m256 ymm7 = _mm256_loadu_ps(&src[i+7*YMM_LEN]); _mm256_storeu_ps(&dst[i+7*YMM_LEN],ymm7); } for(; i != len; ++i) { dst[i] = src[i]; } return; } } else { if(len <= MEMMOVE_1ELEM) { return; } else if(len <= MEMMOVE_16ELEMS) { const __m256 ymm0 = _mm256_load_ps(&src[0]); _mm256_store_ps(&dst[0],ymm0); const __m256 ymm1 = _mm256_load_ps(&src[1*YMM_LEN]); _mm256_store_ps(&dst[1*YMM_LEN],ymm1); return; } else if(len <= MEMMOVE_32ELEMS) { const __m256 ymm0 = _mm256_load_ps(&src[0]); _mm256_store_ps(&dst[0],ymm0); const __m256 ymm1 = _mm256_load_ps(&src[1*YMM_LEN]); _mm256_store_ps(&dst[1*YMM_LEN],ymm1); const __m256 ymm2 = _mm256_load_ps(&src[2*YMM_LEN]); _mm256_store_ps(&dst[2*YMM_LEN],ymm2); const _mm256 ymm3 = _mm256_load_ps(&src[3*YMM_LEN]); _mm256_store_ps(&dst[3*YMM_LEN],ymm3); return; } else if(len <= MEMMOVE_64ELEMS) { const __m256 ymm0 = _mm256_load_ps(&src[0]); _mm256_store_ps(&dst[0],ymm0); const __m256 ymm1 = _mm256_load_ps(&src[1*YMM_LEN]); _mm256_store_ps(&dst[1*YMM_LEN],ymm1); const __m256 ymm2 = _mm256_load_ps(&src[2*YMM_LEN]); _mm256_store_ps(&dst[2*YMM_LEN],ymm2); const _mm256 ymm3 = _mm256_load_ps(&src[3*YMM_LEN]); _mm256_store_ps(&dst[3*YMM_LEN],ymm3); const __m256 ymm4 = _mm256_load_ps(&src[4*YMM_LEN]); _mm256_store_ps(&dst[4*YMM_LEN],ymm4); const __m256 ymm5 = _mm256_load_ps(&src[5*YMM_LEN]); _mm256_store_ps(&dst[5*YMM_LEN],ymm5); const __m256 ymm6 = _mm256_load_ps(&src[6*YMM_LEN]); _mm256_store_ps(&dst[6*YMM_LEN],ymm6); const __m256 ymm7 = _mm256_load_ps(&src[7*YMM_LEN]); _mm256_store_ps(&dst[7*YMM_LEN],ymm7); return; } else if(len <= MEMMOVE_128ELEMS) { #if (GMS_MAN_PREFETCH) == 1 _mm_prefetch((const char*)&src[0], _MM_HINT_T0); _mm_prefetch((const char*)&src[2*YMM_LEN],_MM_HINT_T0); _mm_prefetch((const char*)&src[4*YMM_LEN],_MM_HINT_T0); _mm_prefetch((const char*)&src[6*YMM_LEN],_MM_HINT_T0); _mm_prefetch((const char*)&src[8*YMM_LEN],_MM_HINT_T0); #endif const __m256 ymm0 = _mm256_load_ps(&src[0]); _mm256_store_ps(&dst[0],ymm0); const __m256 ymm1 = _mm256_load_ps(&src[1*YMM_LEN]); _mm256_store_ps(&dst[1*YMM_LEN],ymm1); const __m256 ymm2 = _mm256_load_ps(&src[2*YMM_LEN]); _mm256_store_ps(&dst[2*YMM_LEN],ymm2); const _mm256 ymm3 = _mm256_load_ps(&src[3*YMM_LEN]); _mm256_store_ps(&dst[3*YMM_LEN],ymm3); const __m256 ymm4 = _mm256_load_ps(&src[4*YMM_LEN]); _mm256_store_ps(&dst[4*YMM_LEN],ymm4); const __m256 ymm5 = _mm256_load_ps(&src[5*YMM_LEN]); _mm256_store_ps(&dst[5*YMM_LEN],ymm5); const __m256 ymm6 = _mm256_load_ps(&src[6*YMM_LEN]); _mm256_store_ps(&dst[6*YMM_LEN],ymm6); const __m256 ymm7 = _mm256_load_ps(&src[7*YMM_LEN]); _mm256_store_ps(&dst[7*YMM_LEN],ymm7); const __m256 ymm8 = _mm256_load_ps(&src[8*YMM_LEN]); _mm256_store_ps(&dst[8*YMM_LEN],ymm8); const __m256 ymm9 = _mm256_load_ps(&src[9*YMM_LEN]); _mm256_store_ps(&dst[9*YMM_LEN],ymm9); const __m256 ymm10 = _mm256_load_ps(&src[10*YMM_LEN]); _mm256_store_ps(&dst[10*YMM_LEN],ymm10); const __m256 ymm11 = _mm256_load_ps(&src[11*YMM_LEN]); _mm256_store_ps(&dst[11*YMM_LEN],ymm11); const __m256 ymm12 = _mm256_load_ps(&src[12*YMM_LEN]); _mm256_store_ps(&dst[12*YMM_LEN],ymm12); const __m256 ymm13 = _mm256_load_ps(&src[13*YMM_LEN]); _mm256_store_ps(&dst[13*YMM_LEN],ymm13); const __m256 ymm14 = _mm256_load_ps(&src[14*YMM_LEN]); _mm256_store_ps(&dst[14*YMM_LEN],ymm14); const __m256 ymm15 = _mm256_load_ps(&src[15*YMM_LEN]); _mm256_store_ps(&dst[15*YMM_LEN],ymm155); return; } else if(len > MEMMOVE_128ELEMS) { int32_t i; src = (float*)__builtin_assume_aligned(src,32); dst = (const float*)__builtin_assume_aligned(dst,32); for(i = 0; i != ROUND_TO_EIGHT(len,8); i += 64) { #if (GMS_MAN_PREFETCH) == 1 _mm_prefetch((const char*)&src[i+0], _MM_HINT_T0); _mm_prefetch((const char*)&src[i+2*YMM_LEN],_MM_HINT_T0); _mm_prefetch((const char*)&src[i+4*YMM_LEN],_MM_HINT_T0); #endif const __m256 ymm0 = _mm256_load_ps(&src[i+0]); _mm256_store_ps(&dst[i+0],ymm0); const __m256 ymm1 = _mm256_load_ps(&src[i+1*YMM_LEN]); _mm256_store_ps(&dst[i+1*YMM_LEN],ymm1); const __m256 ymm2 = _mm256_load_ps(&src[i+2*YMM_LEN]); _mm256_store_ps(&dst[i+2*YMM_LEN],ymm2); const _mm256 ymm3 = _mm256_load_ps(&src[i+3*YMM_LEN]); _mm256_store_ps(&dst[i+3*YMM_LEN],ymm3); const __m256 ymm4 = _mm256_load_ps(&src[i+4*YMM_LEN]); _mm256_store_ps(&dst[i+4*YMM_LEN],ymm4); const __m256 ymm5 = _mm256_load_ps(&src[i+5*YMM_LEN]); _mm256_store_ps(&dst[i+5*YMM_LEN],ymm5); const __m256 ymm6 = _mm256_load_ps(&src[i+6*YMM_LEN]); _mm256_store_ps(&dst[i+6*YMM_LEN],ymm6); const __m256 ymm7 = _mm256_load_ps(&src[i+7*YMM_LEN]); _mm256_storeups(&dst[i+7*YMM_LEN],ymm7); } for(; i != len; ++i) { dst[i] = src[i]; } return; } #endif } #if defined __AVX512F__ __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512_memcpy_ps( #if defined __ICC || defined __INTEL_COMPILER float * __restrict dst, const float * __restrict src, #elif defined __GNUC__ && !defined __INTEL_COMPILER float * __restrict __ATTR_ALIGN__(64) dst, const float * __restrict __ATTR_ALIGN__(64) src, #endif const int32_t len) { #endif #if defined __ICC || defined __INTEL_COMPILER if(len <= MEMMOVE_1ELEM) { return; } else if(len <= MEMMOVE_16ELEMS) { const __m512 zmm0 = _mm512_loadu_ps(&src[0]); _mm512_storeu_ps(&dst[0],zmm0); return; } else if(len <= MEMMOVE_32ELEMS) { const __m512 zmm0 = _mm512_loadu_ps(&src[0]); _mm512_storeu_ps(&dst[0],zmm0); const __m512 zmm1 = _mm512_loadu_ps(&src[1*ZMM_LEN]); _mm512_storeu_ps(&dst[1*ZMM_LEN],zmm1); return; } else if(len <= MEMMOVE_64ELEMS) { const __m512 zmm0 = _mm512_loadu_ps(&src[0]); _mm512_storeu_ps(&dst[0],zmm0); const __m512 zmm1 = _mm512_loadu_ps(&src[1*ZMM_LEN]); _mm512_storeu_ps(&dst[1*ZMM_LEN],zmm1); const __m512 zmm2 = _mm512_loadu_ps(&src[2*ZMM_LEN]); _mm512_storeu_ps(&dst[2*ZMM_LEN],zmm2); const __m512 zmm3 = _mm512_loadu_ps(&src[3*ZMM_LEN]); _mm512_storeu_ps(&dst[3*ZMM_LEN],zmm3); return; } else if(len <= MEMMOVE_128ELEMS) { const __m512 zmm0 = _mm512_loadu_ps(&src[0]); _mm512_storeu_ps(&dst[0],zmm0); const __m512 zmm1 = _mm512_loadu_ps(&src[1*ZMM_LEN]); _mm512_storeu_ps(&dst[1*ZMM_LEN],zmm1); const __m512 zmm2 = _mm512_loadu_ps(&src[2*ZMM_LEN]); _mm512_storeu_ps(&dst[2*ZMM_LEN],zmm2); const __m512 zmm3 = _mm512_loadu_ps(&src[3*ZMM_LEN]); _mm512_storeu_ps(&dst[3*ZMM_LEN],zmm3); const __m512 zmm4 = _mm512_loadu_ps(&src[4*ZMM_LEN]); _mm512_storeu_ps(&dst[4*ZMM_LEN],zmm4); const __m512 zmm5 = _mm512_loadu_ps(&src[5*ZMM_LEN]); _mm512_storeu_ps(&dst[5*ZMM_LEN],zmm5); const __m512 zmm6 = _mm512_loadu_ps(&src[6*ZMM_LEN]); _mm512_storeu_ps(&dst[6*ZMM_LEN],zmm6); const __m512 zmm7 = _m512_loadu_ps(&src[7*ZMM_LEN]); _mm512_storeu_ps(&dst[7*ZMM_LEN],zmm7); return; } else if(len <= MEMMOVE_256ELEMS) { #if (GMS_MAN_PREFETCH) == 1 _mm_prefetch((const char *)&src[0], _MM_HINT_T0); _mm_prefetch((const char *)&src[1*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[2*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[3*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[4*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[5*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[6*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[7*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[8*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[9*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[10*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[11*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[12*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[13*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[14*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[15*ZMM_LEN], _MM_HINT_T0); #endif const __m512 zmm0 = _mm512_loadu_ps(&src[0]); _mm512_storeu_ps(&dst[0],zmm0); const __m512 zmm1 = _mm512_loadu_ps(&src[1*ZMM_LEN]); _mm512_storeu_ps(&dst[1*ZMM_LEN],zmm1); const __m512 zmm2 = _mm512_loadu_ps(&src[2*ZMM_LEN]); _mm512_storeu_ps(&dst[2*ZMM_LEN],zmm2); const __m512 zmm3 = _mm512_loadu_ps(&src[3*ZMM_LEN]); _mm512_storeu_ps(&dst[3*ZMM_LEN],zmm3); const __m512 zmm4 = _mm512_loadu_ps(&src[4*ZMM_LEN]); _mm512_storeu_ps(&dst[4*ZMM_LEN],zmm4); const __m512 zmm5 = _mm512_loadu_ps(&src[5*ZMM_LEN]); _mm512_storeu_ps(&dst[5*ZMM_LEN],zmm5); const __m512 zmm6 = _mm512_loadu_ps(&src[6*ZMM_LEN]); _mm512_storeu_ps(&dst[6*ZMM_LEN],zmm6); const __m512 zmm7 = _mm512_loadu_ps(&src[7*ZMM_LEN]); _mm512_storeu_ps(&dst[7*ZMM_LEN],zmm7); const __m512 zmm8 = _mm512_loadu_ps(&src[8*ZMM_LEN]); _mm512_storeu_ps(&dst[8*ZMM_LEN],zmm8); const __m512 zmm9 = _mm512_loadu_ps(&src[9*ZMM_LEN]); _mm512_storeu_ps(&dst[9*ZMM_LEN],zmm9); const __m512 zmm10 = _mm512_loadu_ps(&src[10*ZMM_LEN]); _mm512_storeu_ps(&dst[10*ZMM_LEN],zmm10); const __m512 zmm11 = _mm512_loadu_ps(&src[11*ZMM_LEN]); _mm512_storeu_ps(&dst[11*ZMM_LEN],zmm11); const __m512 zmm12 = _mm512_loadu_ps(&src[12*ZMM_LEN]); _mm512_storeu_ps(&dst[12*ZMM_LEN],zmm12); const __m512 zmm13 = _mm512_loadu_ps(&src[13*ZMM_LEN]); _mm512_storeu_ps(&dst[13*ZMM_LEN],zmm13); const __m512 zmm14 = _mm512_loadu_ps(&src[14*ZMM_LEN]); _mm512_storeu_ps(&dst[14*ZMM_LEN],zmm14); const __m512 zmm15 = _mm512_loadu_ps(&src[15*ZMM_LEN]); _mm512_storeu_ps(&dst[15*ZMM_LEN],zmm15); return; } else if(len > MEMMOVE_256ELEMS) { int32_t i; #pragma code_align(32) for(i = 0; i != ROUND_TO_SIXTEEN(len,16); i += 128) { #if (GMS_MAN_PREFETCH) == 1 _mm_prefetch((const char *)&src[i+0], _MM_HINT_T0); _mm_prefetch((const char *)&src[i+1*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[i+2*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[i+3*ZMM_LEN], _MM_HINT_T0); #endif const __m512 zmm0 = _mm512_loadu_ps(&src[i+0]); _mm512_storeu_ps(&dst[0],zmm0); const __m512 zmm1 = _mm512_loadu_ps(&src[i+1*ZMM_LEN]); _mm512_storeu_ps(&dst[1*ZMM_LEN],zmm1); const __m512 zmm2 = _mm512_loadu_ps(&src[i+2*ZMM_LEN]); _mm512_storeu_ps(&dst[2*ZMM_LEN],zmm2); const __m512 zmm3 = _mm512_loadu_ps(&src[i+3*ZMM_LEN]); _mm512_storeu_ps(&dst[3*ZMM_LEN],zmm3); const __m512 zmm4 = _mm512_loadu_ps(&src[i+4*ZMM_LEN]); _mm512_storeu_ps(&dst[4*ZMM_LEN],zmm4); const __m512 zmm5 = _mm512_loadu_ps(&src[i+5*ZMM_LEN]); _mm512_storeu_ps(&dst[5*ZMM_LEN],zmm5); const __m512 zmm6 = _mm512_loadu_ps(&src[i+6*ZMM_LEN]); _mm512_storeu_ps(&dst[6*ZMM_LEN],zmm6); const __m512 zmm7 = _mm512_loadu_ps(&src[i+7*ZMM_LEN]); _mm512_storeu_ps(&dst[7*ZMM_LEN],zmm7); } #pragma loop_count min(1),avg(8),max(15) for(; i != len; ++i) { dst[i] = src[i]; } return; } #elif defined __GNUC__ && !defined __INTEL_COMPILER if ((reinterpret_cast<uintptr_t>(dst)& 0x3F) != 0ULL && (reinterpret_cast<uintptr_t>(src)& 0x3F) != 0ULL) { if(len <= MEMMOVE_1ELEM) { return; } else if(len <= MEMMOVE_16ELEMS) { const __m512 zmm0 = _mm512_loadu_ps(&src[0]); _mm512_storeu_ps(&dst[0],zmm0); return; } else if(len <= MEMMOVE_32ELEMS) { const __m512 zmm0 = _mm512_loadu_ps(&src[0]); _mm512_storeu_ps(&dst[0],zmm0); const __m512 zmm1 = _mm512_loadu_ps(&src[1*ZMM_LEN]); _mm512_storeu_ps(&dst[1*ZMM_LEN],zmm1); return; } else if(len <= MEMMOVE_64ELEMS) { const __m512 zmm0 = _mm512_loadu_ps(&src[0]); _mm512_storeu_ps(&dst[0],zmm0); const __m512 zmm1 = _mm512_loadu_ps(&src[1*ZMM_LEN]); _mm512_storeu_ps(&dst[1*ZMM_LEN],zmm1); const __m512 zmm2 = _mm512_loadu_ps(&src[2*ZMM_LEN]); _mm512_storeu_ps(&dst[2*ZMM_LEN],zmm2); const __m512 zmm3 = _mm512_loadu_ps(&src[3*ZMM_LEN]); _mm512_storeu_ps(&dst[3*ZMM_LEN],zmm3); return; } else if(len <= MEMMOVE_128ELEMS) { const __m512 zmm0 = _mm512_loadu_ps(&src[0]); _mm512_storeu_ps(&dst[0],zmm0); const __m512 zmm1 = _mm512_loadu_ps(&src[1*ZMM_LEN]); _mm512_storeu_ps(&dst[1*ZMM_LEN],zmm1); const __m512 zmm2 = _mm512_loadu_ps(&src[2*ZMM_LEN]); _mm512_storeu_ps(&dst[2*ZMM_LEN],zmm2); const __m512 zmm3 = _mm512_loadu_ps(&src[3*ZMM_LEN]); _mm512_storeu_ps(&dst[3*ZMM_LEN],zmm3); const __m512 zmm4 = _mm512_loadu_ps(&src[4*ZMM_LEN]); _mm512_storeu_ps(&dst[4*ZMM_LEN],zmm4); const __m512 zmm5 = _mm512_loadu_ps(&src[5*ZMM_LEN]); _mm512_storeu_ps(&dst[5*ZMM_LEN],zmm5); const __m512 zmm6 = _mm512_loadu_ps(&src[6*ZMM_LEN]); _mm512_storeu_ps(&dst[6*ZMM_LEN],zmm6); const __m512 zmm7 = _m512_loadu_ps(&src[7*ZMM_LEN]); _mm512_storeu_ps(&dst[7*ZMM_LEN],zmm7); return; } else if(len <= MEMMOVE_256ELEMS) { #if (GMS_MAN_PREFETCH) == 1 _mm_prefetch((const char *)&src[0], _MM_HINT_T0); _mm_prefetch((const char *)&src[1*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[2*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[3*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[4*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[5*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[6*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[7*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[8*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[9*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[10*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[11*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[12*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[13*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[14*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[15*ZMM_LEN], _MM_HINT_T0); #endif const __m512 zmm0 = _mm512_loadu_ps(&src[0]); _mm512_storeu_ps(&dst[0],zmm0); const __m512 zmm1 = _mm512_loadu_ps(&src[1*ZMM_LEN]); _mm512_storeu_ps(&dst[1*ZMM_LEN],zmm1); const __m512 zmm2 = _mm512_loadu_ps(&src[2*ZMM_LEN]); _mm512_storeu_ps(&dst[2*ZMM_LEN],zmm2); const __m512 zmm3 = _mm512_loadu_ps(&src[3*ZMM_LEN]); _mm512_storeu_ps(&dst[3*ZMM_LEN],zmm3); const __m512 zmm4 = _mm512_loadu_ps(&src[4*ZMM_LEN]); _mm512_storeu_ps(&dst[4*ZMM_LEN],zmm4); const __m512 zmm5 = _mm512_loadu_ps(&src[5*ZMM_LEN]); _mm512_storeu_ps(&dst[5*ZMM_LEN],zmm5); const __m512 zmm6 = _mm512_loadu_ps(&src[6*ZMM_LEN]); _mm512_storeu_ps(&dst[6*ZMM_LEN],zmm6); const __m512 zmm7 = _mm512_loadu_ps(&src[7*ZMM_LEN]); _mm512_storeu_ps(&dst[7*ZMM_LEN],zmm7); const __m512 zmm8 = _mm512_loadu_ps(&src[8*ZMM_LEN]); _mm512_storeu_ps(&dst[8*ZMM_LEN],zmm8); const __m512 zmm9 = _mm512_loadu_ps(&src[9*ZMM_LEN]); _mm512_storeu_ps(&dst[9*ZMM_LEN],zmm9); const __m512 zmm10 = _mm512_loadu_ps(&src[10*ZMM_LEN]); _mm512_storeu_ps(&dst[10*ZMM_LEN],zmm10); const __m512 zmm11 = _mm512_loadu_ps(&src[11*ZMM_LEN]); _mm512_storeu_ps(&dst[11*ZMM_LEN],zmm11); const __m512 zmm12 = _mm512_loadu_ps(&src[12*ZMM_LEN]); _mm512_storeu_ps(&dst[12*ZMM_LEN],zmm12); const __m512 zmm13 = _mm512_loadu_ps(&src[13*ZMM_LEN]); _mm512_storeu_ps(&dst[13*ZMM_LEN],zmm13); const __m512 zmm14 = _mm512_loadu_ps(&src[14*ZMM_LEN]); _mm512_storeu_ps(&dst[14*ZMM_LEN],zmm14); const __m512 zmm15 = _mm512_loadu_ps(&src[15*ZMM_LEN]); _mm512_storeu_ps(&dst[15*ZMM_LEN],zmm15); return; } else if(len > MEMMOVE_256ELEMS) { int32_t i; for(i = 0; i != ROUND_TO_SIXTEEN(len,16); i += 128) { #if (GMS_MAN_PREFETCH) == 1 _mm_prefetch((const char *)&src[i+0], _MM_HINT_T0); _mm_prefetch((const char *)&src[i+1*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[i+2*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[i+3*ZMM_LEN], _MM_HINT_T0); #endif const __m512 zmm0 = _mm512_loadu_ps(&src[i+0]); _mm512_storeu_ps(&dst[0],zmm0); const __m512 zmm1 = _mm512_loadu_ps(&src[i+1*ZMM_LEN]); _mm512_storeu_ps(&dst[1*ZMM_LEN],zmm1); const __m512 zmm2 = _mm512_loadu_ps(&src[i+2*ZMM_LEN]); _mm512_storeu_ps(&dst[2*ZMM_LEN],zmm2); const __m512 zmm3 = _mm512_loadu_ps(&src[i+3*ZMM_LEN]); _mm512_storeu_ps(&dst[3*ZMM_LEN],zmm3); const __m512 zmm4 = _mm512_loadu_ps(&src[i+4*ZMM_LEN]); _mm512_storeu_ps(&dst[4*ZMM_LEN],zmm4); const __m512 zmm5 = _mm512_loadu_ps(&src[i+5*ZMM_LEN]); _mm512_storeu_ps(&dst[5*ZMM_LEN],zmm5); const __m512 zmm6 = _mm512_loadu_ps(&src[i+6*ZMM_LEN]); _mm512_storeu_ps(&dst[6*ZMM_LEN],zmm6); const __m512 zmm7 = _mm512_loadu_ps(&src[i+7*ZMM_LEN]); _mm512_storeu_ps(&dst[7*ZMM_LEN],zmm7); } for(; i != len; ++i) { dst[i] = src[i]; } return; } else { if(len <= MEMMOVE_1ELEM) { return; } else if(len <= MEMMOVE_16ELEMS) { const __m512 zmm0 = _mm512_load_ps(&src[0]); _mm512_store_ps(&dst[0],zmm0); return; } else if(len <= MEMMOVE_32ELEMS) { const __m512 zmm0 = _mm512_load_ps(&src[0]); _mm512_store_ps(&dst[0],zmm0); const __m512 zmm1 = _mm512_load_ps(&src[1*ZMM_LEN]); _mm512_store_ps(&dst[1*ZMM_LEN],zmm1); return; } else if(len <= MEMMOVE_64ELEMS) { const __m512 zmm0 = _mm512_load_ps(&src[0]); _mm512_store_ps(&dst[0],zmm0); const __m512 zmm1 = _mm512_load_ps(&src[1*ZMM_LEN]); _mm512_store_ps(&dst[1*ZMM_LEN],zmm1); const __m512 zmm2 = _mm512_load_ps(&src[2*ZMM_LEN]); _mm512_store_ps(&dst[2*ZMM_LEN],zmm2); const __m512 zmm3 = _mm512_load_ps(&src[3*ZMM_LEN]); _mm512_store_ps(&dst[3*ZMM_LEN],zmm3); return; } else if(len <= MEMMOVE_128ELEMS) { const __m512 zmm0 = _mm512_load_ps(&src[0]); _mm512_store_ps(&dst[0],zmm0); const __m512 zmm1 = _mm512_load_ps(&src[1*ZMM_LEN]); _mm512_store_ps(&dst[1*ZMM_LEN],zmm1); const __m512 zmm2 = _mm512_load_ps(&src[2*ZMM_LEN]); _mm512_store_ps(&dst[2*ZMM_LEN],zmm2); const __m512 zmm3 = _mm512_load_ps(&src[3*ZMM_LEN]); _mm512_store_ps(&dst[3*ZMM_LEN],zmm3); const __m512 zmm4 = _mm512_load_ps(&src[4*ZMM_LEN]); _mm512_store_ps(&dst[4*ZMM_LEN],zmm4); const __m512 zmm5 = _mm512_load_ps(&src[5*ZMM_LEN]); _mm512_store_ps(&dst[5*ZMM_LEN],zmm5); const __m512 zmm6 = _mm512_load_ps(&src[6*ZMM_LEN]); _mm512_store_ps(&dst[6*ZMM_LEN],zmm6); const __m512 zmm7 = _m512_load_ps(&src[7*ZMM_LEN]); _mm512_store_ps(&dst[7*ZMM_LEN],zmm7); return; } else if(len <= MEMMOVE_256ELEMS) { #if (GMS_MAN_PREFETCH) == 1 _mm_prefetch((const char *)&src[0], _MM_HINT_T0); _mm_prefetch((const char *)&src[1*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[2*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[3*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[4*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[5*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[6*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[7*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[8*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[9*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[10*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[11*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[12*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[13*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[14*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[15*ZMM_LEN], _MM_HINT_T0); #endif const __m512 zmm0 = _mm512_load_ps(&src[0]); _mm512_store_ps(&dst[0],zmm0); const __m512 zmm1 = _mm512_load_ps(&src[1*ZMM_LEN]); _mm512_store_ps(&dst[1*ZMM_LEN],zmm1); const __m512 zmm2 = _mm512_load_ps(&src[2*ZMM_LEN]); _mm512_store_ps(&dst[2*ZMM_LEN],zmm2); const __m512 zmm3 = _mm512_load_ps(&src[3*ZMM_LEN]); _mm512_store_ps(&dst[3*ZMM_LEN],zmm3); const __m512 zmm4 = _mm512_load_ps(&src[4*ZMM_LEN]); _mm512_store_ps(&dst[4*ZMM_LEN],zmm4); const __m512 zmm5 = _mm512_load_ps(&src[5*ZMM_LEN]); _mm512_store_ps(&dst[5*ZMM_LEN],zmm5); const __m512 zmm6 = _mm512_load_ps(&src[6*ZMM_LEN]); _mm512_store_ps(&dst[6*ZMM_LEN],zmm6); const __m512 zmm7 = _mm512_load_ps(&src[7*ZMM_LEN]); _mm512_store_ps(&dst[7*ZMM_LEN],zmm7); const __m512 zmm8 = _mm512_load_ps(&src[8*ZMM_LEN]); _mm512_store_ps(&dst[8*ZMM_LEN],zmm8); const __m512 zmm9 = _mm512_load_ps(&src[9*ZMM_LEN]); _mm512_store_ps(&dst[9*ZMM_LEN],zmm9); const __m512 zmm10 = _mm512_load_ps(&src[10*ZMM_LEN]); _mm512_store_ps(&dst[10*ZMM_LEN],zmm10); const __m512 zmm11 = _mm512_load_ps(&src[11*ZMM_LEN]); _mm512_store_ps(&dst[11*ZMM_LEN],zmm11); const __m512 zmm12 = _mm512_load_ps(&src[12*ZMM_LEN]); _mm512_store_ps(&dst[12*ZMM_LEN],zmm12); const __m512 zmm13 = _mm512_load_ps(&src[13*ZMM_LEN]); _mm512_store_ps(&dst[13*ZMM_LEN],zmm13); const __m512 zmm14 = _mm512_load_ps(&src[14*ZMM_LEN]); _mm512_store_ps(&dst[14*ZMM_LEN],zmm14); const __m512 zmm15 = _mm512_load_ps(&src[15*ZMM_LEN]); _mm512_store_ps(&dst[15*ZMM_LEN],zmm15); return; } else if(len > MEMMOVE_256ELEMS) { int32_t i; src = (float*)__builtin_assume_aligned(src,64); dst = (const float*)__builtin_assume_aligned(dst,64); for(i = 0; i != ROUND_TO_SIXTEEN(len,16); i += 128) { #if (GMS_MAN_PREFETCH) == 1 _mm_prefetch((const char *)&src[i+0], _MM_HINT_T0); _mm_prefetch((const char *)&src[i+1*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[i+2*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[i+3*ZMM_LEN], _MM_HINT_T0); #endif const __m512 zmm0 = _mm512_load_ps(&src[i+0]); _mm512_store_ps(&dst[0],zmm0); const __m512 zmm1 = _mm512_load_ps(&src[i+1*ZMM_LEN]); _mm512_store_ps(&dst[1*ZMM_LEN],zmm1); const __m512 zmm2 = _mm512_load_ps(&src[i+2*ZMM_LEN]); _mm512_store_ps(&dst[2*ZMM_LEN],zmm2); const __m512 zmm3 = _mm512_load_ps(&src[i+3*ZMM_LEN]); _mm512_store_ps(&dst[3*ZMM_LEN],zmm3); const __m512 zmm4 = _mm512_load_ps(&src[i+4*ZMM_LEN]); _mm512_store_ps(&dst[4*ZMM_LEN],zmm4); const __m512 zmm5 = _mm512_load_ps(&src[i+5*ZMM_LEN]); _mm512_store_ps(&dst[5*ZMM_LEN],zmm5); const __m512 zmm6 = _mm512_load_ps(&src[i+6*ZMM_LEN]); _mm512_store_ps(&dst[6*ZMM_LEN],zmm6); const __m512 zmm7 = _mm512_load_ps(&src[i+7*ZMM_LEN]); _mm512_store_ps(&dst[7*ZMM_LEN],zmm7); } for(; i != len; ++i) { dst[i] = src[i]; } return; } #endif } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx256_cached_memmove(void * __restrict _Dst, const void * __restrict _Src, const int32_t _nelems) { if (MEMMOVE_1ELEM <= _nelems) { return;} char * __restrict dst = (char *)_Dst; const char * __restrict src = (const char *)_Src; if ( _nelems <= MEMMOVE_16ELEMS) { const __m256 ymm0(_mm256_loadu_ps((float*)&src[0])); _mm256_storeu_ps((float*)&dst[0], ymm0); const __m256 ymm1(_mm256_loadu_ps((float*)&src[1*YMM_LEN])); _mm256_storeu_ps((float*)&dst[1*YMM_LEN], ymm1); return; } else if ( _nelems <= MEMMOVE_32ELEMS) { const __m256 ymm0(_mm256_loadu_ps((float*)&src[0])); _mm256_storeu_ps((float*)&dst[0], ymm0); const __m256 ymm1(_mm256_loadu_ps((float*)&src[1*YMM_LEN])); _mm256_storeu_ps((float*)&dst[1*YMM_LEN],ymm1); const __m256 ymm2(_mm256_loadu_ps((float*)&src[2*YMM_LEN])); _mm256_storeu_ps((float*)&dst[2*YMM_LEN],ymm2); const __m256 ymm3(_mm256_loadu_ps((float*)&src[3*YMM_LEN])); _mm256_storeu_ps((float*)&dst[3*YMM_LEN],ymm3); return; } else if ( _nelems <= MEMMOVE_64ELEMS){ const __m256 ymm0(_mm256_loadu_ps((float*)&src[0])); _mm256_storeu_ps((float*)&dst[0], ymm0); const __m256 ymm1(_mm256_loadu_ps((float*)&src[1*YMM_LEN])); _mm256_storeu_ps((float*)&dst[1*YMM_LEN], ymm1); const __m256 ymm2(_mm256_loadu_ps((float*)&src[2*YMM_LEN])); _mm256_storeu_ps((float*)&dst[2*YMM_LEN], ymm2); const __m256 ymm3(_mm256_loadu_ps((float*)&src[3*YMM_LEN])); _mm256_storeu_ps((float*)&dst[3*YMM_LEN], ymm3); const __m256 ymm4(_mm256_loadu_ps((float*)&src[4*YMM_LEN])); _mm256_storeu_ps((float*)&dst[4*YMM_LEN], ymm4); const __m256 ymm5(_mm256_loadu_ps((float*)&src[5*YMM_LEN])); _mm256_storeu_ps((float*)&dst[5*YMM_LEN], ymm5); const __m256 ymm6(_mm256_loadu_ps((float*)&src[6*YMM_LEN])); _mm256_storeu_ps((float*)&dst[6*YMM_LEN], ymm6); const __m256 ymm7(_mm256_loadu_ps((float*)&src[7*YMM_LEN])); _mm256_storeu_ps((float*)&dst[7*YMM_LEN], ymm7); return; } else if ( _nelems <= MEMMOVE_128ELEMS) { #if (GMS_MAN_PREFETCH) == 1 _mm_prefetch((const char*)&src[0], _MM_HINT_T0); _mm_prefetch((const char*)&src[2*YMM_LEN],_MM_HINT_T0); _mm_prefetch((const char*)&src[4*YMM_LEN],_MM_HINT_T0); _mm_prefetch((const char*)&src[6*YMM_LEN],_MM_HINT_T0); _mm_prefetch((const char*)&src[8*YMM_LEN],_MM_HINT_T0); #endif const __m256 ymm0(_mm256_loadu_ps((float*)&src[0])); _mm256_storeu_ps((float*)&dst[0], ymm0); const __m256 ymm1(_mm256_loadu_ps((float*)&src[1*YMM_LEN])); _mm256_storeu_ps((float*)&dst[1*YMM_LEN], ymm1); const __m256 ymm2(_mm256_loadu_ps((float*)&src[2*YMM_LEN])); _mm256_storeu_ps((float*)&dst[2*YMM_LEN], ymm2); const __m256 ymm3(_mm256_loadu_ps((float*)&src[3*YMM_LEN])); _mm256_storeu_ps((float*)&dst[3*YMM_LEN], ymm3); const __m256 ymm4(_mm256_loadu_ps((float*)&src[4*YMM_LEN])); _mm256_storeu_ps((float*)&dst[4*YMM_LEN], ymm4); const __m256 ymm5(_mm256_loadu_ps((float*)&src[5*YMM_LEN])); _mm256_storeu_ps((float*)&dst[5*YMM_LEN], ymm5); const __m256 ymm6(_mm256_loadu_ps((float*)&src[6*YMM_LEN])); _mm256_storeu_ps((float*)&dst[6*YMM_LEN], ymm6); const __m256 ymm7(_mm256_loadu_ps((float*)&src[7*YMM_LEN])); _mm256_storeu_ps((float*)&dst[7*YMM_LEN], ymm7); const __m256 ymm8(_mm256_loadu_ps((float*)&src[8*YMM_LEN])); _mm256_storeu_ps((float*)&dst[8*YMM_LEN], ymm8); const __m256 ymm9(_mm256_loadu_ps((float*)&src[9*YMM_LEN])); _mm256_storeu_ps((float*)&dst[9*YMM_LEN], ymm9); const __m256 ymm10(_mm256_loadu_ps((float*)&src[10*YMM_LEN])); _mm256_storeu_ps((float*)&dst[10*YMM_LEN],ymm10); const __m256 ymm11(_mm256_loadu_ps((float*)&src[11*YMM_LEN])); _mm256_storeu_ps((float*)&dst[11*YMM_LEN],ymm11); const __m256 ymm12(_mm256_loadu_ps((float*)&src[12*YMM_LEN])); _mm256_storeu_ps((float*)&dst[12*YMM_LEN],ymm12); const __m256 ymm13(_mm256_loadu_ps((float*)&src[13*YMM_LEN])); _mm256_storeu_ps((float*)&dst[13*YMM_LEN],ymm13); const __m256 ymm14(_mm256_loadu_ps((float*)&src[14*YMM_LEN])); _mm256_storeu_ps((float*)&dst[14*YMM_LEN],ymm14); const __m256 ymm15(_mm256_loadu_ps((float*)&src[15*YMM_LEN])); _mm256_storeu_ps((float*)&dst[15*YMM_LEN],ymm15); return; } else if (_nelems <= MAXFLOATSPERPAGE4KiB){ int32_t i; #if defined __ICC || defined __INTEL_COMPILER #pragma loop_count(1024) #endif for (i = 0; i != ROUND_TO_EIGHT(_nelems, 8); i += 64) { #if (GMS_MAN_PREFETCH) == 1 _mm_prefetch((const char*)&src[i], _MM_HINT_T0); #endif const __m256 ymm0(_mm256_loadu_ps((float*)&src[i+0])); _mm256_storeu_ps((float*)&dst[i+0], ymm0); const __m256 ymm1(_mm256_loadu_ps((float*)&src[i+1*YMM_LEN])); _mm256_storeu_ps((float*)&dst[i+1*YMM_LEN], ymm1); const __m256 ymm2(_mm256_loadu_ps((float*)&src[i+2*YMM_LEN])); _mm256_storeu_ps((float*)&dst[i+2*YMM_LEN], ymm2); const __m256 ymm3(_mm256_loadu_ps((float*)&src[i+3*YMM_LEN])); _mm256_storeu_ps((float*)&dst[i+3*YMM_LEN], ymm3); const __m256 ymm4(_mm256_loadu_ps((float*)&src[i+4*YMM_LEN])); _mm256_storeu_ps((float*)&dst[i+4*YMM_LEN], ymm4); const __m256 ymm5(_mm256_loadu_ps((float*)&src[i+5*YMM_LEN])); _mm256_storeu_ps((float*)&dst[i+5*YMM_LEN], ymm5); const __m256 ymm6(_mm256_loadu_ps((float*)&src[i+6*YMM_LEN])); _mm256_storeu_ps((float*)&dst[i+6*YMM_LEN], ymm6); const __m256 ymm7(_mm256_loadu_ps((float*)&src[i+7*YMM_LEN])); _mm256_storeu_ps((float*)&dst[i+7*YMM_LEN], ymm7); } #if defined __ICC || defined __INTEL_COMPILER #pragma loop_count min(1),avg(4),max(7) #endif for (; i != _nelems; ++i) { dst[i] = src[i]; } return; } else if (_nelems > MAXFLOATSPERPAGE4KiB) { int32_t j; for (int32_t k = 0; k != _nelems; k += MAXFLOATSPERPAGE4KiB) { volatile float t = src[k + MAXFLOATSPERPAGE4KiB]; for (j = k + 128; j != k + MAXFLOATSPERPAGE4KiB; j += 64) { _mm_prefetch((const char*)&src[j], _MM_HINT_T0); } for (j = k; j != ROUND_TO_EIGHT(k + MAXFLOATSPERPAGE4KiB, 8); j += 64) { const __m256 ymm0(_mm256_loadu_ps((float*)&src[j+0])); _mm256_storeu_ps((float*)&dst[j+0], ymm0); const __m256 ymm1(_mm256_loadu_ps((float*)&src[j+1*YMM_LEN])); _mm256_storeu_ps((float*)&dst[j+1*YMM_LEN], ymm1); const __m256 ymm2(_mm256_loadu_ps((float*)&src[j+2*YMM_LEN])); _mm256_storeu_ps((float*)&dst[j+2*YMM_LEN], ymm2); const __m256 ymm3(_mm256_loadu_ps((float*)&src[j+3*YMM_LEN])); _mm256_storeu_ps((float*)&dst[j+3*YMM_LEN], ymm3); const __m256 ymm4(_mm256_loadu_ps((float*)&src[j+4*YMM_LEN])); _mm256_storeu_ps((float*)&dst[j+4*YMM_LEN], ymm4); const __m256 ymm5(_mm256_loadu_ps((float*)&src[j+5*YMM_LEN])); _mm256_storeu_ps((float*)&dst[j+5*YMM_LEN], ymm5); const __m256 ymm6(_mm256_loadu_ps((float*)&src[j+6*YMM_LEN])); _mm256_storeu_ps((float*)&dst[j+6*YMM_LEN], ymm6); const __m256 ymm7(_mm256_loadu_ps((float*)&src[j+7*YMM_LEN])); _mm256_storeu_ps((float*)&dst[j+7*YMM_LEN], ymm7); } for (; j != _nelems; ++j) { dst[j] = src[j]; } } return; } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx256_uncached_memmove(void * __restrict _Dst, const void * __restrict _Src, const int32_t _nelems) { if (_nelems <= MEMMOVE_1ELEM) { return;} char * __restrict dst = (char*)_Dst; const char * __restrict src = (const char*)_Src; uintptr_t dst_len = (uintptr_t)dst; int32_t _nbytes = 4*_nelems; int32_t misalign = 0; if (dst_len & 0x1F) { misalign = min_val(0x20 - (dst_len & 0x1F),_nbytes); dst += misalign; dst_len += misalign; _nbytes -= misalign; } if (_nelems <= MEMMOVE_16ELEMS) { const __m256 ymm0(_mm256_loadu_ps((float*)&src[0])); _mm256_stream_ps((float*)&dst[0], ymm0); const __m256 ymm1(_mm256_loadu_ps((float*)&src[1 * YMM_LEN])); _mm256_stream_ps((float*)&dst[1 * YMM_LEN], ymm1); _mm_sfence(); return; } else if (_nelems <= MEMMOVE_32ELEMS) { const __m256 ymm0(_mm256_loadu_ps((float*)&src[0])); _mm256_stream_ps((float*)&dst[0], ymm0); const __m256 ymm1(_mm256_loadu_ps((float*)&src[1 * YMM_LEN])); _mm256_stream_ps((float*)&dst[1 * YMM_LEN], ymm1); const __m256 ymm2(_mm256_loadu_ps((float*)&src[2 * YMM_LEN])); _mm256_stream_ps((float*)&dst[2 * YMM_LEN], ymm2); const __m256 ymm3(_mm256_loadu_ps((float*)&src[3 * YMM_LEN])); _mm256_stream_ps((float*)&dst[3 * YMM_LEN], ymm3); _mm_sfence(); return; } else if (_nelems <= MEMMOVE_64ELEMS){ const __m256 ymm0(_mm256_loadu_ps((float*)&src[0])); _mm256_stream_ps((float*)&dst[0], ymm0); const __m256 ymm1(_mm256_loadu_ps((float*)&src[1 * YMM_LEN])); _mm256_stream_ps((float*)&dst[1 * YMM_LEN], ymm1); const __m256 ymm2(_mm256_loadu_ps((float*)&src[2 * YMM_LEN])); _mm256_stream_ps((float*)&dst[2 * YMM_LEN], ymm2); const __m256 ymm3(_mm256_loadu_ps((float*)&src[3 * YMM_LEN])); _mm256_stream_ps((float*)&dst[3 * YMM_LEN], ymm3); const __m256 ymm4(_mm256_loadu_ps((float*)&src[4 * YMM_LEN])); _mm256_stream_ps((float*)&dst[4 * YMM_LEN], ymm4); const __m256 ymm5(_mm256_loadu_ps((float*)&src[5 * YMM_LEN])); _mm256_stream_ps((float*)&dst[5 * YMM_LEN], ymm5); const __m256 ymm6(_mm256_loadu_ps((float*)&src[6 * YMM_LEN])); _mm256_stream_ps((float*)&dst[6 * YMM_LEN], ymm6); const __m256 ymm7(_mm256_loadu_ps((float*)&src[7 * YMM_LEN])); _mm256_stream_ps((float*)&dst[7 * YMM_LEN], ymm7); _mm_sfence(); return; } else if (_nelems <= MEMMOVE_128ELEMS) { #if (GMS_MAN_PREFETCH) == _mm_prefetch((const char*)&src[0], _MM_HINT_T0); _mm_prefetch((const char*)&src[2 * YMM_LEN], _MM_HINT_T0); _mm_prefetch((const char*)&src[4 * YMM_LEN], _MM_HINT_T0); _mm_prefetch((const char*)&src[6 * YMM_LEN], _MM_HINT_T0); _mm_prefetch((const char*)&src[8 * YMM_LEN], _MM_HINT_T0); #endif const __m256 ymm0(_mm256_loadu_ps((float*)&src[0])); _mm256_stream_ps((float*)&dst[0], ymm0); const __m256 ymm1(_mm256_loadu_ps((float*)&src[1 * YMM_LEN])); _mm256_stream_ps((float*)&dst[1 * YMM_LEN], ymm1); const __m256 ymm2(_mm256_loadu_ps((float*)&src[2 * YMM_LEN])); _mm256_stream_ps((float*)&dst[2 * YMM_LEN], ymm2); const __m256 ymm3(_mm256_loadu_ps((float*)&src[3 * YMM_LEN])); _mm256_stream_ps((float*)&dst[3 * YMM_LEN], ymm3); const __m256 ymm4(_mm256_loadu_ps((float*)&src[4 * YMM_LEN])); _mm256_stream_ps((float*)&dst[4 * YMM_LEN], ymm4); const __m256 ymm5(_mm256_loadu_ps((float*)&src[5 * YMM_LEN])); _mm256_stream_ps((float*)&dst[5 * YMM_LEN], ymm5); const __m256 ymm6(_mm256_loadu_ps((float*)&src[6 * YMM_LEN])); _mm256_stream_ps((float*)&dst[6 * YMM_LEN], ymm6); const __m256 ymm7(_mm256_loadu_ps((float*)&src[7 * YMM_LEN])); _mm256_stream_ps((float*)&dst[7 * YMM_LEN], ymm7); const __m256 ymm8(_mm256_loadu_ps((float*)&src[8 * YMM_LEN])); _mm256_stream_ps((float*)&dst[8 * YMM_LEN], ymm8); const __m256 ymm9(_mm256_loadu_ps((float*)&src[9 * YMM_LEN])); _mm256_stream_ps((float*)&dst[9 * YMM_LEN], ymm9); const __m256 ymm10(_mm256_loadu_ps((float*)&src[10 * YMM_LEN])); _mm256_stream_ps((float*)&dst[10 * YMM_LEN], ymm10); const __m256 ymm11(_mm256_loadu_ps((float*)&src[11 * YMM_LEN])); _mm256_stream_ps((float*)&dst[11 * YMM_LEN], ymm11); const __m256 ymm12(_mm256_loadu_ps((float*)&src[12 * YMM_LEN])); _mm256_stream_ps((float*)&dst[12 * YMM_LEN], ymm12); const __m256 ymm13(_mm256_loadu_ps((float*)&src[13 * YMM_LEN])); _mm256_stream_ps((float*)&dst[13 * YMM_LEN], ymm13); const __m256 ymm14(_mm256_loadu_ps((float*)&src[14 * YMM_LEN])); _mm256_stream_ps((float*)&dst[14 * YMM_LEN], ymm14); const __m256 ymm15(_mm256_loadu_ps((float*)&src[15 * YMM_LEN])); _mm256_stream_ps((float*)&dst[15 * YMM_LEN], ymm15); _mm_sfence(); return; } else if (_nelems <= MAXFLOATSPERPAGE4KiB){ int32_t i; #if defined __ICC || defined __INTEL_COMPILER #pragma loop_count(1024) #endif for (i = 0; i != ROUND_TO_EIGHT(_nelems, 8); i += 64) { _mm_prefetch((const char*)&src[i], _MM_HINT_T0); const __m256 ymm0(_mm256_loadu_ps((float*)&src[i + 0])); _mm256_stream_ps((float*)&dst[i + 0], ymm0); const __m256 ymm1(_mm256_loadu_ps((float*)&src[i + 1 * YMM_LEN])); _mm256_stream_ps((float*)&dst[i + 1 * YMM_LEN], ymm1); const __m256 ymm2(_mm256_loadu_ps((float*)&src[i + 2 * YMM_LEN])); _mm256_stream_ps((float*)&dst[i + 2 * YMM_LEN], ymm2); const __m256 ymm3(_mm256_loadu_ps((float*)&src[i + 3 * YMM_LEN])); _mm256_stream_ps((float*)&dst[i + 3 * YMM_LEN], ymm3); const __m256 ymm4(_mm256_loadu_ps((float*)&src[i + 4 * YMM_LEN])); _mm256_stream_ps((float*)&dst[i + 4 * YMM_LEN], ymm4); const __m256 ymm5(_mm256_loadu_ps((float*)&src[i + 5 * YMM_LEN])); _mm256_stream_ps((float*)&dst[i + 5 * YMM_LEN], ymm5); const __m256 ymm6(_mm256_loadu_ps((float*)&src[i + 6 * YMM_LEN])); _mm256_stream_ps((float*)&dst[i + 6 * YMM_LEN], ymm6); const __m256 ymm7(_mm256_loadu_ps((float*)&src[i + 7 * YMM_LEN])); _mm256_stream_ps((float*)&dst[i + 7 * YMM_LEN], ymm7); } _mm_sfence(); #if defined __ICC || defined __INTEL_COMPILER #pragma loop_count min(1),avg(4),max(7) #endif for (; i != _nelems; ++i) { dst[i] = src[i]; } return; } else if (_nelems > MAXFLOATSPERPAGE4KiB) { int32_t j; for (int32_t k = 0; k != _nelems; k += MAXFLOATSPERPAGE4KiB) { volatile float t = src[k + MAXFLOATSPERPAGE4KiB]; for (j = k + 128; j != k + MAXFLOATSPERPAGE4KiB; j += 64) { _mm_prefetch((const char*)&src[j], _MM_HINT_T0); } for (j = k; j != k + MAXFLOATSPERPAGE4KiB; j += 64) { const __m256 ymm0(_mm256_loadu_ps((float*)&src[j + 0])); _mm256_stream_ps((float*)&dst[j + 0], ymm0); const __m256 ymm1(_mm256_loadu_ps((float*)&src[j + 1 * YMM_LEN])); _mm256_stream_ps((float*)&dst[j + 1 * YMM_LEN], ymm1); const __m256 ymm2(_mm256_loadu_ps((float*)&src[j + 2 * YMM_LEN])); _mm256_stream_ps((float*)&dst[j + 2 * YMM_LEN], ymm2); const __m256 ymm3(_mm256_loadu_ps((float*)&src[j + 3 * YMM_LEN])); _mm256_stream_ps((float*)&dst[j + 3 * YMM_LEN], ymm3); const __m256 ymm4(_mm256_loadu_ps((float*)&src[j + 4 * YMM_LEN])); _mm256_stream_ps((float*)&dst[j + 4 * YMM_LEN], ymm4); const __m256 ymm5(_mm256_loadu_ps((float*)&src[j + 5 * YMM_LEN])); _mm256_stream_ps((float*)&dst[j + 5 * YMM_LEN], ymm5); const __m256 ymm6(_mm256_loadu_ps((float*)&src[j + 6 * YMM_LEN])); _mm256_stream_ps((float*)&dst[j + 6 * YMM_LEN], ymm6); const __m256 ymm7(_mm256_loadu_ps((float*)&src[j + 7 * YMM_LEN])); _mm256_stream_ps((float*)&dst[j + 7 * YMM_LEN], ymm7); } } _mm_sfence(); return; } } #if defined __AVX512F__ __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512_cached_memmove(void * __restrict _Dst, const void * __restrict _Src, const int32_t _nelems) { if (MEMMOVE_1ELEM <= _nelems) { return; } char * __restrict dst = (char *)_Dst; const char * __restrict src = (char *)_Src; if (_nelems <= MEMMOVE_16ELEMS) { const __m512 zmm0(_mm512_loadu_ps((float*)&src[0])); _mm512_storeu_ps((float*)&dst[0],zmm0); return; } else if ( _nelems <= MEMMOVE_32ELEMS) { const __m512 zmm0(_mm512_loadu_ps((float*)&src[0])); _mm512_storeu_ps((float*)&dst[0], zmm0); const __m512 zmm1(_mm512_loadu_ps((float*)&src[1*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[1*ZMM_LEN], zmm1); return; } else if ( _nelems <= MEMMOVE_64ELEMS) { const __m512 zmm0(_mm512_loadu_ps((float*)&src[0])); _mm512_storeu_ps((float*)&dst[0],zmm0); const __m512 zmm1(_mm512_loadu_ps((float*)&src[1*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[1*ZMM_LEN],zmm1); const __m512 zmm2(_mm512_loadu_ps((float*)&src[2*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[2*ZMM_LEN],zmm2); const __m512 zmm3(_mm512_loadu_ps((float*)&src[3*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[3*ZMM_LEN],zmm3); return; } else if ( _nelems <= MEMMOVE_128ELEMS) { const __m512 zmm0(_mm512_loadu_ps((float*)&src[0])); _mm512_storeu_ps((float*)&dst[0], zmm0); const __m512 zmm1(_mm512_loadu_ps((float*)&src[1*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[1*ZMM_LEN], zmm1); const __m512 zmm2(_mm512_loadu_ps((float*)&src[2*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[2*ZMM_LEN], zmm2); const __m512 zmm3(_mm512_loadu_ps((float*)&src[3*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[3*ZMM_LEN], zmm3); const __m512 zmm4(_mm512_loadu_ps((float*)&src[4*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[4*ZMM_LEN], zmm4); const __m512 zmm5(_mm512_loadu_ps((float*)&src[5*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[5*ZMM_LEN], zmm5); const __m512 zmm6(_mm512_loadu_ps((float*)&src[6*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[6*ZMM_LEN], zmm6); const __m512 zmm7(_mm512_loadu_ps((float*)&src[7*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[7*ZMM_LEN], zmm7); return; } else if ( _nelems <= MEMMOVE_256ELEMS) { #if (GMS_MAN_PREFETCH) _mm_prefetch((const char *)&src[0], _MM_HINT_T0); _mm_prefetch((const char *)&src[1*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[2*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[3*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[4*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[5*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[6*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[7*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[8*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[9*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[10*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[11*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[12*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[13*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[14*ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[15*ZMM_LEN], _MM_HINT_T0); #endif const __m512 zmm0(_mm512_loadu_ps((float*)&src[0])); _mm512_storeu_ps((float*)&dst[0], zmm0); const __m512 zmm1(_mm512_loadu_ps((float*)&src[1*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[1*ZMM_LEN], zmm1); const __m512 zmm2(_mm512_loadu_ps((float*)&src[2*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[2*ZMM_LEN], zmm2); const __m512 zmm3(_mm512_loadu_ps((float*)&src[3*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[3*ZMM_LEN], zmm3); const __m512 zmm4(_mm512_loadu_ps((float*)&src[4*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[4*ZMM_LEN], zmm4); const __m512 zmm5(_mm512_loadu_ps((float*)&src[5*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[5*ZMM_LEN], zmm5); const __m512 zmm6(_mm512_loadu_ps((float*)&src[6*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[6*ZMM_LEN], zmm6); const __m512 zmm7(_mm512_loadu_ps((float*)&src[7*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[7*ZMM_LEN], zmm7); const __m512 zmm8(_mm512_loadu_ps((float*)&src[8*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[8*ZMM_LEN], zmm8); const __m512 zmm9(_mm512_loadu_ps((float*)&src[9*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[9*ZMM_LEN], zmm9); const __m512 zmm10(_mm512_loadu_ps((float*)&src[10*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[10*ZMM_LEN], zmm10); const __m512 zmm11(_mm512_loadu_ps((float*)&src[11*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[11*ZMM_LEN], zmm11); const __m512 zmm12(_mm512_loadu_ps((float*)&src[12*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[12*ZMM_LEN], zmm12); const __m512 zmm13(_mm512_loadu_ps((float*)&src[13*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[13*ZMM_LEN], zmm13); const __m512 zmm14(_mm512_loadu_ps((float*)&src[14*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[14*ZMM_LEN], zmm14); const __m512 zmm15(_mm512_loadu_ps((float*)&src[15*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[15*ZMM_LEN], zmm15); return; } else if ( _nelems <= PAGE4KiB) { int32_t i; #if defined __ICC || defined __INTEL_COMPILER #pragma loop_count(1024) #endif for (i = 0; i != ROUND_TO_SIXTEEN(_nelems,16); i += 128) { _mm_prefetch((const char *)&src[i+0], _MM_HINT_T0); const __m512 zmm0(_mm512_loadu_ps((float*)&src[i+0])); _mm512_storeu_ps((float*)&dst[i+0], zmm0); const __m512 zmm1(_mm512_loadu_ps((float*)&src[i+1*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[i+1*ZMM_LEN], zmm1); const __m512 zmm2(_mm512_loadu_ps((float*)&src[i+2*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[i+2*ZMM_LEN], zmm2); const __m512 zmm3(_mm512_loadu_ps((float*)&src[i+3*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[i+3*ZMM_LEN], zmm3); const __m512 zmm4(_mm512_loadu_ps((float*)&src[i+4*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[i+4*ZMM_LEN], zmm4); const __m512 zmm5(_mm512_loadu_ps((float*)&src[i+5*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[i+5*ZMM_LEN], zmm5); const __m512 zmm6(_mm512_loadu_ps((float*)&src[i+6*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[i+6*ZMM_LEN], zmm6); const __m512 zmm7(_mm512_loadu_ps((float*)&src[i+7*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[i+7*ZMM_LEN], zmm7); } #if defined __ICC || defined __INTEL_COMPILER #pragma loop_count min(1),avg(8),max(15) #endif for (; i != _nelems; ++i) { dst[i] = src[i]; } return; } else if (_nelems > MAXFLOATSPERPAGE4KiB) { int32_t j; for (int32_t k = 0; k != _nelems; k += MAXFLOATSPERPAGE4KiB) { volatile float t = src[k + MAXFLOATSPERPAGE4KiB]; for ( j = k + 128; j != k + MAXFLOATSPERPAGE4KiB; j += 128) { _mm_prefetch((const char*)&src[j], _MM_HINT_T0); } for (j = k; j != k + MAXFLOATSPERPAGE4KiB; j += 128) { const __m512 zmm0(_mm512_loadu_ps((float*)&src[j+0])); _mm512_storeu_ps((float*)&dst[j+0], zmm0); const __m512 zmm1(_mm512_loadu_ps((float*)&src[j+1*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[j+1*ZMM_LEN], zmm1); const __m512 zmm2(_mm512_loadu_ps((float*)&src[j+2*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[j+2*ZMM_LEN], zmm2); const __m512 zmm3(_mm512_loadu_ps((float*)&src[j+3*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[j+3*ZMM_LEN], zmm3); const __m512 zmm4(_mm512_loadu_ps((float*)&src[j+4*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[j+4*ZMM_LEN], zmm4); const __m512 zmm5(_mm512_loadu_ps((float*)&src[j+5*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[j+5*ZMM_LEN], zmm5); const __m512 zmm6(_mm512_loadu_ps((float*)&src[j+6*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[j+6*ZMM_LEN], zmm6); const __m512 zmm7(_mm512_loadu_ps((float*)&src[j+7*ZMM_LEN])); _mm512_storeu_ps((float*)&dst[j+7*ZMM_LEN], zmm7); } } return; } } __ATTR_ALWAYS_INLINE__ __ATTR_HOT__ __ATTR_ALIGN__(32) static inline void avx512_uncached_memmove(void * __restrict _Dst, const void * __restrict _Src, const int32_t _nelems) { if (MEMMOVE_1ELEM <= _nelems) { return; } char * __restrict dst = (char*)_Dst; const char * __restrict src = (char*)_Src; uintptr_t dst_val = (uintptr_t)dst; int32_t misalign = 0; int32_t nbytes = 4*_nelems; if (dst_val & 0x3F) { misalign = min_val(0x40 - (dst_val & 0x3F), nbytes); dst += misalign; dst_val += misalign; nbytes -= misalign; } if (_nelems <= MEMMOVE_16ELEMS) { const __m512 zmm0(_mm512_loadu_ps((float*)&src[0])); _mm512_stream_ps((float*)&dst[0], zmm0); _mm_sfence(); return; } else if (_nelems <= MEMMOVE_32ELEMS) { const __m512 zmm0(_mm512_loadu_ps((float*)&src[0])); _mm512_stream_ps((float*)&dst[0], zmm0); const __m512 zmm1(_mm512_loadu_ps((float*)&src[1 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[1 * ZMM_LEN], zmm1); _mm_sfence(); return; } else if (_nelems <= MEMMOVE_64ELEMS) { const __m512 zmm0(_mm512_loadu_ps((float*)&src[0])); _mm512_stream_ps((float*)&dst[0], zmm0); const __m512 zmm1(_mm512_loadu_ps((float*)&src[1 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[1 * ZMM_LEN], zmm1); const __m512 zmm2(_mm512_loadu_ps((float*)&src[2 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[2 * ZMM_LEN], zmm2); const __m512 zmm3(_mm512_loadu_ps((float*)&src[3 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[3 * ZMM_LEN], zmm3); _mm_sfence(); return; } else if (_nelems <= MEMMOVE_128ELEMS) { const __m512 zmm0(_mm512_loadu_ps((float*)&src[0])); _mm512_stream_ps((float*)&dst[0], zmm0); const __m512 zmm1(_mm512_loadu_ps((float*)&src[1 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[1 * ZMM_LEN], zmm1); const __m512 zmm2(_mm512_loadu_ps((float*)&src[2 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[2 * ZMM_LEN], zmm2); const __m512 zmm3(_mm512_loadu_ps((float*)&src[3 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[3 * ZMM_LEN], zmm3); const __m512 zmm4(_mm512_loadu_ps((float*)&src[4 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[4 * ZMM_LEN], zmm4); const __m512 zmm5(_mm512_loadu_ps((float*)&src[5 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[5 * ZMM_LEN], zmm5); const __m512 zmm6(_mm512_loadu_ps((float*)&src[6 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[6 * ZMM_LEN], zmm6); const __m512 zmm7(_mm512_loadu_ps((float*)&src[7 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[7 * ZMM_LEN], zmm7); _mm_sfence(); return; } else if (_nelems <= MEMMOVE_256ELEMS) { #if (GMS_MAN_PREFETCH) == 1 _mm_prefetch((const char *)&src[0], _MM_HINT_T0); _mm_prefetch((const char *)&src[1 * ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[2 * ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[3 * ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[4 * ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[5 * ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[6 * ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[7 * ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[8 * ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[9 * ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[10 * ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[11 * ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[12 * ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[13 * ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[14 * ZMM_LEN], _MM_HINT_T0); _mm_prefetch((const char *)&src[15 * ZMM_LEN], _MM_HINT_T0); #endif const __m512 zmm0(_mm512_loadu_ps((float*)&src[0])); _mm512_stream_ps((float*)&dst[0], zmm0); const __m512 zmm1(_mm512_loadu_ps((float*)&src[1 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[1 * ZMM_LEN], zmm1); const __m512 zmm2(_mm512_loadu_ps((float*)&src[2 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[2 * ZMM_LEN], zmm2); const __m512 zmm3(_mm512_loadu_ps((float*)&src[3 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[3 * ZMM_LEN], zmm3); const __m512 zmm4(_mm512_loadu_ps((float*)&src[4 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[4 * ZMM_LEN], zmm4); const __m512 zmm5(_mm512_loadu_ps((float*)&src[5 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[5 * ZMM_LEN], zmm5); const __m512 zmm6(_mm512_loadu_ps((float*)&src[6 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[6 * ZMM_LEN], zmm6); const __m512 zmm7(_mm512_loadu_ps((float*)&src[7 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[7 * ZMM_LEN], zmm7); const __m512 zmm8(_mm512_loadu_ps((float*)&src[8 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[8 * ZMM_LEN], zmm8); const __m512 zmm9(_mm512_loadu_ps((float*)&src[9 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[9 * ZMM_LEN], zmm9); const __m512 zmm10(_mm512_loadu_ps((float*)&src[10 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[10 * ZMM_LEN], zmm10); const __m512 zmm11(_mm512_loadu_ps((float*)&src[11 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[11 * ZMM_LEN], zmm11); const __m512 zmm12(_mm512_loadu_ps((float*)&src[12 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[12 * ZMM_LEN], zmm12); const __m512 zmm13(_mm512_loadu_ps((float*)&src[13 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[13 * ZMM_LEN], zmm13); const __m512 zmm14(_mm512_loadu_ps((float*)&src[14 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[14 * ZMM_LEN], zmm14); const __m512 zmm15(_mm512_loadu_ps((float*)&src[15 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[15 * ZMM_LEN], zmm15); _mm_sfence(); return; } else if (_nelems <= PAGE4KiB) { int32_t i; #if defined __ICC || defined __INTEL_COMPILER #pragma loop_count(1024) #endif for (i = 0; i != ROUND_TO_SIXTEEN(_nelems, 16); i += 128) { _mm_prefetch((const char *)&src[i + 0], _MM_HINT_T0); const __m512 zmm0(_mm512_loadu_ps((float*)&src[i + 0])); _mm512_stream_ps((float*)&dst[i + 0], zmm0); const __m512 zmm1(_mm512_loadu_ps((float*)&src[i + 1 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[i + 1 * ZMM_LEN], zmm1); const __m512 zmm2(_mm512_loadu_ps((float*)&src[i + 2 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[i + 2 * ZMM_LEN], zmm2); const __m512 zmm3(_mm512_loadu_ps((float*)&src[i + 3 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[i + 3 * ZMM_LEN], zmm3); const __m512 zmm4(_mm512_loadu_ps((float*)&src[i + 4 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[i + 4 * ZMM_LEN], zmm4); const __m512 zmm5(_mm512_loadu_ps((float*)&src[i + 5 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[i + 5 * ZMM_LEN], zmm5); const __m512 zmm6(_mm512_loadu_ps((float*)&src[i + 6 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[i + 6 * ZMM_LEN], zmm6); const __m512 zmm7(_mm512_loadu_ps((float*)&src[i + 7 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[i + 7 * ZMM_LEN], zmm7); } _mm_sfence(); #if defined __ICC || defined __INTEL_COMPILER #pragma loop_count min(1),avg(8),max(15) #endif for (; i != _nelems; ++i) { dst[i] = src[i]; } return; } else if (_nelems > MAXFLOATSPERPAGE4KiB) { int32_t j; for (int32_t k = 0; k != _nelems; k += MAXFLOATSPERPAGE4KiB) { volatile float t = src[k + MAXFLOATSPERPAGE4KiB]; for (j = k + 128; j != k + MAXFLOATSPERPAGE4KiB; j += 128) { _mm_prefetch((const char*)&src[j], _MM_HINT_T0); } for (j = k; j != k + MAXFLOATSPERPAGE4KiB; j += 128) { const __m512 zmm0(_mm512_loadu_ps((float*)&src[j + 0])); _mm512_stream_ps((float*)&dst[j + 0], zmm0); const __m512 zmm1(_mm512_loadu_ps((float*)&src[j + 1 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[j + 1 * ZMM_LEN], zmm1); const __m512 zmm2(_mm512_loadu_ps((float*)&src[j + 2 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[j + 2 * ZMM_LEN], zmm2); const __m512 zmm3(_mm512_loadu_ps((float*)&src[j + 3 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[j + 3 * ZMM_LEN], zmm3); const __m512 zmm4(_mm512_loadu_ps((float*)&src[j + 4 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[j + 4 * ZMM_LEN], zmm4); const __m512 zmm5(_mm512_loadu_ps((float*)&src[j + 5 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[j + 5 * ZMM_LEN], zmm5); const __m512 zmm6(_mm512_loadu_ps((float*)&src[j + 6 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[j + 6 * ZMM_LEN], zmm6); const __m512 zmm7(_mm512_loadu_ps((float*)&src[j + 7 * ZMM_LEN])); _mm512_stream_ps((float*)&dst[j + 7 * ZMM_LEN], zmm7); } } _mm_sfence(); return; } } #endif } // common } // gms #endif /*__GMS_SIMD_MEMOPS_H__*/
PGraph.h
// SPDX-License-Identifier: BSD-2-Clause #ifndef _PGRAPH_H_ #define _PGRAPH_H_ #include <stdlib.h> #include <stdint.h> #include <string.h> #include <math.h> #include <HostLink.h> #include <config.h> #include <POLite.h> #include <POLite/Seq.h> #include <POLite/Graph.h> #include <POLite/Placer.h> #include <POLite/Bitmap.h> #include <POLite/ProgRouters.h> #include <type_traits> #include <tinsel-interface.h> // Nodes of a POETS graph are devices typedef NodeId PDeviceId; // This structure holds a group of receiving edges on a thread. // All of the edges originate from the same output pin. template <typename E> struct PReceiverGroup { // Thread id where all the receivers reside uint32_t threadId; // A sequence of receiving devices on that thread SmallSeq<PInEdge<E>> receivers; }; // This structure holds info about an edge destination struct PEdgeDest { // Index of edge in outgoing edge list uint32_t index; // Destination device PDeviceId dest; // Address where destination is located PDeviceAddr addr; }; // Comparison function for PEdgeDest // (Useful to sort destinations by thread id of destination) inline int cmpEdgeDest(const void* e0, const void* e1) { PEdgeDest* d0 = (PEdgeDest*) e0; PEdgeDest* d1 = (PEdgeDest*) e1; return getThreadId(d0->addr) < getThreadId(d1->addr); } // POETS graph template <typename DeviceType, typename S, typename E, typename M> class PGraph { private: // Align address to 2^n byte boundary inline uint32_t align(uint32_t n, uint32_t addr) { if ((addr & (1<<n)-1) == 0) return addr; return ((addr >> n) + 1) << n; } // Align address to 32-bit word boundary uint32_t wordAlign(uint32_t addr) { return align(2, addr); } // Align address to cache-line boundary uint32_t cacheAlign(uint32_t addr) { return align(TinselLogBytesPerLine, addr); } // Helper function inline uint32_t min(uint32_t x, uint32_t y) { return x < y ? x : y; } // Number of FPGA boards available uint32_t meshLenX; uint32_t meshLenY; // Number of FPGA boards to use uint32_t numBoardsX; uint32_t numBoardsY; // Multicast routing tables: // Sequence of outgoing edges for every (device, pin) pair Seq<POutEdge>*** outTable; // Sequence of in-edge headers, for each thread Seq<PInHeader<E>>** inTableHeaders; // Remaining in-edges that don't fit in the header table, for each thread Seq<PInEdge<E>>** inTableRest; // Bitmap denoting used space in header table, for each thread Bitmap** inTableBitmaps; // Programmable routing tables ProgRouterMesh* progRouterTables; // Receiver groups (used internally by some methods, but declared once // to avoid repeated allocation) PReceiverGroup<E> groups[TinselThreadsPerMailbox]; // Generic constructor void constructor(uint32_t lenX, uint32_t lenY) { meshLenX = lenX; meshLenY = lenY; char* str = getenv("POLITE_BOARDS_X"); int nx = str ? atoi(str) : meshLenX; str = getenv("POLITE_BOARDS_Y"); int ny = str ? atoi(str) : meshLenY; setNumBoards(nx, ny); numDevices = 0; devices = NULL; toDeviceAddr = NULL; numDevicesOnThread = NULL; fromDeviceAddr = NULL; vertexMem = NULL; vertexMemSize = NULL; vertexMemBase = NULL; inEdgeHeaderMem = NULL; inEdgeHeaderMemSize = NULL; inEdgeHeaderMemBase = NULL; inEdgeRestMem = NULL; inEdgeRestMemSize = NULL; inEdgeRestMemBase = NULL; outEdgeMem = NULL; outEdgeMemSize = NULL; outEdgeMemBase = NULL; mapVerticesToDRAM = false; mapInEdgeHeadersToDRAM = true; mapInEdgeRestToDRAM = true; mapOutEdgesToDRAM = true; outTable = NULL; inTableHeaders = NULL; inTableRest = NULL; inTableBitmaps = NULL; progRouterTables = NULL; chatty = 0; str = getenv("POLITE_CHATTY"); if (str != NULL) { chatty = !strcmp(str, "0") ? 0 : 1; } } public: // Number of devices uint32_t numDevices; // Graph containing device ids and connections Graph graph; // Edge labels: has same structure as graph.outgoing Seq<Seq<E>*> edgeLabels; // Mapping from device id to device state // (Not valid until the mapper is called) PState<S>** devices; // Mapping from thread id to number of devices on that thread // (Not valid until the mapper is called) uint32_t* numDevicesOnThread; // Mapping from device id to device address and back // (Not valid until the mapper is called) PDeviceAddr* toDeviceAddr; // Device id -> device address PDeviceId** fromDeviceAddr; // Device address -> device id // Each thread's vertex mem and thread mem regions // (Not valid until the mapper is called) uint8_t** vertexMem; uint8_t** threadMem; uint32_t* vertexMemSize; uint32_t* threadMemSize; uint32_t* vertexMemBase; uint32_t* threadMemBase; // Each thread's in-edge and out-edge regions // (Not valid until the mapper is called) uint8_t** inEdgeHeaderMem; uint8_t** inEdgeRestMem; uint32_t* inEdgeHeaderMemSize; uint32_t* inEdgeRestMemSize; uint32_t* inEdgeHeaderMemBase; uint32_t* inEdgeRestMemBase; uint8_t** outEdgeMem; uint32_t* outEdgeMemSize; uint32_t* outEdgeMemBase; // Where to map the various regions // (If false, map to SRAM instead) bool mapVerticesToDRAM; bool mapInEdgeHeadersToDRAM; bool mapInEdgeRestToDRAM; bool mapOutEdgesToDRAM; // Allow mapper to print useful information to stdout uint32_t chatty; // Setter for number of boards to use void setNumBoards(uint32_t x, uint32_t y) { if (x > meshLenX || y > meshLenY) { printf("Mapper: %d x %d boards requested, %d x %d available\n", numBoardsX, numBoardsY, meshLenX, meshLenY); exit(EXIT_FAILURE); } numBoardsX = x; numBoardsY = y; } // Create new device inline PDeviceId newDevice() { edgeLabels.append(new SmallSeq<E>); numDevices++; return graph.newNode(); } // Add a connection between devices inline void addEdge(PDeviceId from, PinId pin, PDeviceId to) { if (pin >= POLITE_NUM_PINS) { printf("addEdge: pin exceeds POLITE_NUM_PINS\n"); exit(EXIT_FAILURE); } graph.addEdge(from, pin, to); E edge; edgeLabels.elems[from]->append(edge); } // Add labelled edge using given output pin void addLabelledEdge(E edge, PDeviceId x, PinId pin, PDeviceId y) { graph.addEdge(x, pin, y); edgeLabels.elems[x]->append(edge); } // Allocate SRAM and DRAM partitions void allocatePartitions() { // Decide a maximum partition size that is reasonable // SRAM: Partition size minus 2048 bytes for the stack uint32_t maxSRAMSize = (1<<TinselLogBytesPerSRAMPartition) - 2048; // DRAM: Partition size minus 65536 bytes for the stack uint32_t maxDRAMSize = (1<<TinselLogBytesPerDRAMPartition) - 65536; // Allocate partition sizes and bases vertexMem = (uint8_t**) calloc(TinselMaxThreads, sizeof(uint8_t*)); vertexMemSize = (uint32_t*) calloc(TinselMaxThreads, sizeof(uint32_t)); vertexMemBase = (uint32_t*) calloc(TinselMaxThreads, sizeof(uint32_t)); threadMem = (uint8_t**) calloc(TinselMaxThreads, sizeof(uint8_t*)); threadMemSize = (uint32_t*) calloc(TinselMaxThreads, sizeof(uint32_t)); threadMemBase = (uint32_t*) calloc(TinselMaxThreads, sizeof(uint32_t)); inEdgeHeaderMem = (uint8_t**) calloc(TinselMaxThreads, sizeof(uint8_t*)); inEdgeHeaderMemSize = (uint32_t*) calloc(TinselMaxThreads, sizeof(uint32_t)); inEdgeHeaderMemBase = (uint32_t*) calloc(TinselMaxThreads, sizeof(uint32_t)); inEdgeRestMem = (uint8_t**) calloc(TinselMaxThreads, sizeof(uint8_t*)); inEdgeRestMemSize = (uint32_t*) calloc(TinselMaxThreads, sizeof(uint32_t)); inEdgeRestMemBase = (uint32_t*) calloc(TinselMaxThreads, sizeof(uint32_t)); outEdgeMem = (uint8_t**) calloc(TinselMaxThreads, sizeof(uint8_t*)); outEdgeMemSize = (uint32_t*) calloc(TinselMaxThreads, sizeof(uint32_t)); outEdgeMemBase = (uint32_t*) calloc(TinselMaxThreads, sizeof(uint32_t)); // Compute partition sizes for each thread for (uint32_t threadId = 0; threadId < TinselMaxThreads; threadId++) { // This variable is used to count the size of the *initialised* // partition. The total partition size is larger as it includes // uninitialised portions. uint32_t sizeVMem = 0; uint32_t sizeEIHeaderMem = 0; uint32_t sizeEIRestMem = 0; uint32_t sizeEOMem = 0; uint32_t sizeTMem = 0; // Add space for thread structure (always stored in SRAM) sizeTMem = cacheAlign(sizeof(PThread<DeviceType, S, E, M>)); // Add space for devices uint32_t numDevs = numDevicesOnThread[threadId]; for (uint32_t devNum = 0; devNum < numDevs; devNum++) { // Add space for device sizeVMem = sizeVMem + sizeof(PState<S>); } // Add space for incoming edge tables if (inTableHeaders[threadId]) { sizeEIHeaderMem = inTableHeaders[threadId]->numElems * sizeof(PInHeader<E>); sizeEIHeaderMem = wordAlign(sizeEIHeaderMem); } if (inTableRest[threadId]) { sizeEIRestMem = inTableRest[threadId]->numElems * sizeof(PInEdge<E>); sizeEIRestMem = wordAlign(sizeEIRestMem); } // Add space for outgoing edge table for (uint32_t devNum = 0; devNum < numDevs; devNum++) { PDeviceId id = fromDeviceAddr[threadId][devNum]; for (uint32_t p = 0; p < POLITE_NUM_PINS; p++) { Seq<POutEdge>* edges = outTable[id][p]; sizeEOMem += sizeof(POutEdge) * edges->numElems; } } sizeEOMem = wordAlign(sizeEOMem); // The total partition size including uninitialised portions uint32_t totalSizeVMem = sizeVMem + wordAlign(sizeof(PLocalDeviceId) * numDevs); // Check that total size is reasonable uint32_t totalSizeSRAM = sizeTMem; uint32_t totalSizeDRAM = 0; if (mapVerticesToDRAM) totalSizeDRAM += totalSizeVMem; else totalSizeSRAM += totalSizeVMem; if (mapInEdgeHeadersToDRAM) totalSizeDRAM += sizeEIHeaderMem; else totalSizeSRAM += sizeEIHeaderMem; if (mapInEdgeRestToDRAM) totalSizeDRAM += sizeEIRestMem; else totalSizeSRAM += sizeEIRestMem; if (mapOutEdgesToDRAM) totalSizeDRAM += sizeEOMem; else totalSizeSRAM += sizeEOMem; if (totalSizeDRAM > maxDRAMSize) { printf("Error: max DRAM partition size exceeded\n"); exit(EXIT_FAILURE); } if (totalSizeSRAM > maxSRAMSize) { printf("Error: max SRAM partition size exceeded\n"); exit(EXIT_FAILURE); } // Allocate space for the initialised portion of the partition assert((sizeVMem%4) == 0); assert((sizeTMem%4) == 0); assert((sizeEIHeaderMem%4) == 0); assert((sizeEIRestMem%4) == 0); assert((sizeEOMem%4) == 0); vertexMem[threadId] = (uint8_t*) calloc(sizeVMem, 1); vertexMemSize[threadId] = sizeVMem; threadMem[threadId] = (uint8_t*) calloc(sizeTMem, 1); threadMemSize[threadId] = sizeTMem; inEdgeHeaderMem[threadId] = (uint8_t*) calloc(sizeEIHeaderMem, 1); inEdgeHeaderMemSize[threadId] = sizeEIHeaderMem; inEdgeRestMem[threadId] = (uint8_t*) calloc(sizeEIRestMem, 1); inEdgeRestMemSize[threadId] = sizeEIRestMem; outEdgeMem[threadId] = (uint8_t*) calloc(sizeEOMem, 1); outEdgeMemSize[threadId] = sizeEOMem; // Tinsel address of base of partition uint32_t partId = threadId & (TinselThreadsPerDRAM-1); uint32_t sramBase = (1 << TinselLogBytesPerSRAM) + (partId << TinselLogBytesPerSRAMPartition); uint32_t dramBase = TinselBytesPerDRAM - ((partId+1) << TinselLogBytesPerDRAMPartition); // Use partition-interleaved region for DRAM dramBase |= 0x80000000; threadMemBase[threadId] = sramBase; sramBase += threadMemSize[threadId]; // Determine base addresses of each region if (mapVerticesToDRAM) { vertexMemBase[threadId] = dramBase; dramBase += totalSizeVMem; } else { vertexMemBase[threadId] = sramBase; sramBase += totalSizeVMem; } if (mapInEdgeHeadersToDRAM) { inEdgeHeaderMemBase[threadId] = dramBase; dramBase += sizeEIHeaderMem; } else { inEdgeHeaderMemBase[threadId] = sramBase; sramBase += sizeEIHeaderMem; } if (mapInEdgeRestToDRAM) { inEdgeRestMemBase[threadId] = dramBase; dramBase += sizeEIRestMem; } else { inEdgeRestMemBase[threadId] = sramBase; sramBase += sizeEIRestMem; } if (mapOutEdgesToDRAM) { outEdgeMemBase[threadId] = dramBase; dramBase += sizeEOMem; } else { outEdgeMemBase[threadId] = sramBase; sramBase += sizeEOMem; } } } // Initialise partitions void initialisePartitions() { for (uint32_t threadId = 0; threadId < TinselMaxThreads; threadId++) { // Next pointers for each partition uint32_t nextVMem = 0; uint32_t nextOutIndex = 0; // Pointer to thread structure PThread<DeviceType, S, E, M>* thread = (PThread<DeviceType, S, E, M>*) &threadMem[threadId][0]; // Set number of devices on thread thread->numDevices = numDevicesOnThread[threadId]; // Set number of devices in graph thread->numVertices = numDevices; // Set tinsel address of array of device states thread->devices = vertexMemBase[threadId]; // Set tinsel address of base of edge tables thread->outTableBase = outEdgeMemBase[threadId]; thread->inTableHeaderBase = inEdgeHeaderMemBase[threadId]; thread->inTableRestBase = inEdgeRestMemBase[threadId]; // Add space for each device on thread uint32_t numDevs = numDevicesOnThread[threadId]; for (uint32_t devNum = 0; devNum < numDevs; devNum++) { PState<S>* dev = (PState<S>*) &vertexMem[threadId][nextVMem]; PDeviceId id = fromDeviceAddr[threadId][devNum]; devices[id] = dev; // Add space for device nextVMem = nextVMem + sizeof(PState<S>); } // Initialise each device and the thread's out edges for (uint32_t devNum = 0; devNum < numDevs; devNum++) { PDeviceId id = fromDeviceAddr[threadId][devNum]; PState<S>* dev = devices[id]; // Initialise POutEdge* outEdgeArray = (POutEdge*) outEdgeMem[threadId]; for (uint32_t p = 0; p < POLITE_NUM_PINS; p++) { dev->pinBase[p] = nextOutIndex; Seq<POutEdge>* edges = outTable[id][p]; for (uint32_t i = 0; i < edges->numElems; i++) { outEdgeArray[nextOutIndex] = edges->elems[i]; nextOutIndex++; } } } // Intialise thread's in edges PInHeader<E>* inEdgeHeaderArray = (PInHeader<E>*) inEdgeHeaderMem[threadId]; Seq<PInHeader<E>>* headers = inTableHeaders[threadId]; if (headers) for (uint32_t i = 0; i < headers->numElems; i++) { inEdgeHeaderArray[i] = headers->elems[i]; } PInEdge<E>* inEdgeRestArray = (PInEdge<E>*) inEdgeRestMem[threadId]; Seq<PInEdge<E>>* edges = inTableRest[threadId]; if (edges) for (uint32_t i = 0; i < edges->numElems; i++) { inEdgeRestArray[i] = edges->elems[i]; } // At this point, check that next pointers line up with heap sizes if (nextVMem != vertexMemSize[threadId]) { printf("Error: vertex mem size does not match pre-computed size\n"); exit(EXIT_FAILURE); } if ((nextOutIndex * sizeof(POutEdge)) != outEdgeMemSize[threadId]) { printf("Error: out edge mem size does not match pre-computed size\n"); exit(EXIT_FAILURE); } // Set tinsel address of senders array thread->senders = vertexMemBase[threadId] + nextVMem; } } // Allocate mapping structures void allocateMapping() { devices = (PState<S>**) calloc(numDevices, sizeof(PState<S>*)); toDeviceAddr = (PDeviceAddr*) calloc(numDevices, sizeof(PDeviceAddr)); fromDeviceAddr = (PDeviceId**) calloc(TinselMaxThreads, sizeof(PDeviceId*)); numDevicesOnThread = (uint32_t*) calloc(TinselMaxThreads, sizeof(uint32_t)); } // Allocate routing tables // (Only valid after mapper is called) void allocateRoutingTables() { // Receiver-side tables (headers) inTableHeaders = (Seq<PInHeader<E>>**) calloc(TinselMaxThreads,sizeof(Seq<PInHeader<E>>*)); for (uint32_t t = 0; t < TinselMaxThreads; t++) { if (numDevicesOnThread[t] != 0) inTableHeaders[t] = new SmallSeq<PInHeader<E>>; } // Receiver-side tables (rest) inTableRest = (Seq<PInEdge<E>>**) calloc(TinselMaxThreads,sizeof(Seq<PInEdge<E>>*)); for (uint32_t t = 0; t < TinselMaxThreads; t++) { if (numDevicesOnThread[t] != 0) inTableRest[t] = new SmallSeq<PInEdge<E>>; } // Receiver-side tables (bitmaps) inTableBitmaps = (Bitmap**) calloc(TinselMaxThreads,sizeof(Bitmap*)); for (uint32_t t = 0; t < TinselMaxThreads; t++) { if (numDevicesOnThread[t] != 0) inTableBitmaps[t] = new Bitmap; } // Sender-side tables outTable = (Seq<POutEdge>***) calloc(numDevices, sizeof(Seq<POutEdge>**)); for (uint32_t d = 0; d < numDevices; d++) { outTable[d] = (Seq<POutEdge>**) calloc(POLITE_NUM_PINS, sizeof(Seq<POutEdge>*)); for (uint32_t p = 0; p < POLITE_NUM_PINS; p++) outTable[d][p] = new SmallSeq<POutEdge>; } } // Determine local-multicast routing key for given set of receivers // (The key must be the same for all receivers) uint32_t findKey(uint32_t numGroups) { // Fast path (single receiver) if (numGroups == 1) { Bitmap* bm = inTableBitmaps[groups[0].threadId]; return bm->grabNextBit(); } // Determine starting index for key search uint32_t index = 0; for (uint32_t i = 0; i < numGroups; i++) { PReceiverGroup<E>* g = &groups[i]; Bitmap* bm = inTableBitmaps[g->threadId]; if (bm->firstFree > index) index = bm->firstFree; } // Find key that is available for all receivers uint64_t mask; retry: mask = 0ul; for (uint32_t i = 0; i < numGroups; i++) { PReceiverGroup<E>* g = &groups[i]; Bitmap* bm = inTableBitmaps[g->threadId]; mask |= bm->getWord(index); if (~mask == 0ul) { index++; goto retry; } } // Mark key as taken in each bitmap uint32_t bit = __builtin_ctzll(~mask); for (uint32_t i = 0; i < numGroups; i++) { PReceiverGroup<E>* g = &groups[i]; Bitmap* bm = inTableBitmaps[g->threadId]; bm->setBit(index, bit); } return 64*index + bit; } // Add entries to the input tables for the given receivers // (Only valid after mapper is called) uint32_t addInTableEntries(uint32_t numGroups) { uint32_t key = findKey(numGroups); if (key >= 0xffff) { printf("Routing key exceeds 16 bits\n"); exit(EXIT_FAILURE); } // Populate inTableHeaders and inTableRest using the key for (uint32_t i = 0; i < numGroups; i++) { PReceiverGroup<E>* g = &groups[i]; uint32_t numEdges = g->receivers.numElems; PInEdge<E>* edgePtr = g->receivers.elems; if (numEdges > 0) { // Determine thread id of receiver uint32_t t = g->threadId; // Extend table Seq<PInHeader<E>>* headers = inTableHeaders[t]; if (key >= headers->numElems) headers->extendBy(key + 1 - headers->numElems); // Fill in header PInHeader<E>* header = &inTableHeaders[t]->elems[key]; header->numReceivers = numEdges; if (inTableRest[t]->numElems > 0xffff) { printf("In-table index exceeds 16 bits\n"); exit(EXIT_FAILURE); } header->restIndex = inTableRest[t]->numElems; uint32_t numHeaderEdges = numEdges < POLITE_EDGES_PER_HEADER ? numEdges : POLITE_EDGES_PER_HEADER; for (uint32_t j = 0; j < numHeaderEdges; j++) { header->edges[j] = *edgePtr; edgePtr++; } numEdges -= numHeaderEdges; // Overflow into rest memory if header not big enough for (uint32_t j = 0; j < numEdges; j++) { inTableRest[t]->append(*edgePtr); edgePtr++; } } } return key; } // Split edge list into board-local and non-board-local destinations // And sort each list by destination thread id // (Only valid after mapper is called) void splitDests(PDeviceId devId, PinId pinId, Seq<PEdgeDest>* local, Seq<PEdgeDest>* nonLocal) { local->clear(); nonLocal->clear(); PDeviceAddr devAddr = toDeviceAddr[devId]; uint32_t devBoard = getThreadId(devAddr) >> TinselLogThreadsPerBoard; // Split destinations into local/non-local Seq<PDeviceId>* dests = graph.outgoing->elems[devId]; Seq<PinId>* pinIds = graph.pins->elems[devId]; for (uint32_t d = 0; d < dests->numElems; d++) { if (pinIds->elems[d] == pinId) { PEdgeDest e; e.index = d; e.dest = dests->elems[d]; e.addr = toDeviceAddr[e.dest]; uint32_t destBoard = getThreadId(e.addr) >> TinselLogThreadsPerBoard; if (devBoard == destBoard) local->append(e); else nonLocal->append(e); } } // Sort local list qsort(local->elems, local->numElems, sizeof(PEdgeDest), cmpEdgeDest); // Sort non-local list qsort(nonLocal->elems, nonLocal->numElems, sizeof(PEdgeDest), cmpEdgeDest); } // Compute table updates for destinations for given device // (Only valid after mapper is called) void computeTables(Seq<PEdgeDest>* dests, uint32_t d, Seq<PRoutingDest>* out) { out->clear(); uint32_t index = 0; while (index < dests->numElems) { // New set of receiver groups on same mailbox uint32_t threadMaskLow = 0; uint32_t threadMaskHigh = 0; uint32_t nextGroup = 0; // Current mailbox & thread being considered PDeviceAddr mbox = getThreadId(dests->elems[index].addr) >> TinselLogThreadsPerMailbox; uint32_t thread = getThreadId(dests->elems[index].addr) & ((1<<TinselLogThreadsPerMailbox)-1); // Determine edges targetting same mailbox while (index < dests->numElems) { PEdgeDest* edge = &dests->elems[index]; // Determine destination mailbox address and mailbox-local thread uint32_t destMailbox = getThreadId(edge->addr) >> TinselLogThreadsPerMailbox; uint32_t destThread = getThreadId(edge->addr) & ((1<<TinselLogThreadsPerMailbox)-1); // Does destination match current destination? if (destMailbox == mbox) { if (destThread == thread) { // Add to current receiver group PInEdge<E> in; in.devId = getLocalDeviceId(edge->addr); Seq<E>* edges = edgeLabels.elems[d]; if (! std::is_same<E, None>::value) in.edge = edges->elems[edge->index]; // Update current receiver group groups[nextGroup].receivers.append(in); groups[nextGroup].threadId = getThreadId(edge->addr); if (thread < 32) threadMaskLow |= 1 << thread; if (thread >= 32) threadMaskHigh |= 1 << (thread-32); index++; } else { // Start new receiver group thread = destThread; nextGroup++; assert(nextGroup < TinselThreadsPerMailbox); } } else break; } // Add input table entries uint32_t key = addInTableEntries(nextGroup+1); // Add output entry PRoutingDest dest; dest.kind = PRDestKindMRM; dest.mbox = mbox; dest.mrm.key = key; dest.mrm.threadMaskLow = threadMaskLow; dest.mrm.threadMaskHigh = threadMaskHigh; out->append(dest); // Clear receiver groups, for a new iteration for (uint32_t i = 0; i <= nextGroup; i++) groups[i].receivers.clear(); } } // Compute routing tables // (Only valid after mapper is called) void computeRoutingTables() { // Edge destinations (local to sender board, or not) Seq<PEdgeDest> local; Seq<PEdgeDest> nonLocal; // Routing destinations Seq<PRoutingDest> dests; // Allocate per-board programmable routing tables progRouterTables = new ProgRouterMesh(numBoardsX, numBoardsY); // For each device for (uint32_t d = 0; d < numDevices; d++) { // For each pin for (uint32_t p = 0; p < POLITE_NUM_PINS; p++) { // Split edge lists into local/non-local and sort by target thread id splitDests(d, p, &local, &nonLocal); // Deal with board-local connections computeTables(&local, d, &dests); for (uint32_t i = 0; i < dests.numElems; i++) { PRoutingDest dest = dests.elems[i]; POutEdge edge; edge.mbox = dest.mbox; edge.key = dest.mrm.key; edge.threadMaskLow = dest.mrm.threadMaskLow; edge.threadMaskHigh = dest.mrm.threadMaskHigh; outTable[d][p]->append(edge); } // Deal with non-board-local connections computeTables(&nonLocal, d, &dests); uint32_t src = getThreadId(toDeviceAddr[d]) >> TinselLogThreadsPerMailbox; uint32_t key = progRouterTables->addDestsFromBoard(src, &dests); POutEdge edge; edge.mbox = tinselUseRoutingKey(); edge.key = 0; edge.threadMaskLow = key; edge.threadMaskHigh = 0; outTable[d][p]->append(edge); // Add output list terminator POutEdge term; term.key = InvalidKey; outTable[d][p]->append(term); } } } // Release all structures void releaseAll() { if (devices != NULL) { free(devices); free(toDeviceAddr); free(numDevicesOnThread); for (uint32_t t = 0; t < TinselMaxThreads; t++) if (fromDeviceAddr[t] != NULL) free(fromDeviceAddr[t]); free(fromDeviceAddr); for (uint32_t t = 0; t < TinselMaxThreads; t++) if (vertexMem[t] != NULL) free(vertexMem[t]); free(vertexMem); free(vertexMemSize); free(vertexMemBase); for (uint32_t t = 0; t < TinselMaxThreads; t++) if (threadMem[t] != NULL) free(threadMem[t]); free(threadMem); free(threadMemSize); free(threadMemBase); for (uint32_t t = 0; t < TinselMaxThreads; t++) if (inEdgeHeaderMem[t] != NULL) free(inEdgeHeaderMem[t]); free(inEdgeHeaderMem); free(inEdgeHeaderMemSize); free(inEdgeHeaderMemBase); for (uint32_t t = 0; t < TinselMaxThreads; t++) if (inEdgeRestMem[t] != NULL) free(inEdgeRestMem[t]); free(inEdgeRestMem); free(inEdgeRestMemSize); free(inEdgeRestMemBase); for (uint32_t t = 0; t < TinselMaxThreads; t++) if (outEdgeMem[t] != NULL) free(outEdgeMem[t]); free(outEdgeMem); free(outEdgeMemSize); free(outEdgeMemBase); } if (inTableHeaders != NULL) { for (uint32_t t = 0; t < TinselMaxThreads; t++) if (inTableHeaders[t] != NULL) delete inTableHeaders[t]; free(inTableHeaders); inTableHeaders = NULL; } if (inTableRest != NULL) { for (uint32_t t = 0; t < TinselMaxThreads; t++) if (inTableRest[t] != NULL) delete inTableRest[t]; free(inTableRest); inTableRest = NULL; } if (inTableBitmaps != NULL) { for (uint32_t t = 0; t < TinselMaxThreads; t++) if (inTableBitmaps[t] != NULL) delete inTableBitmaps[t]; free(inTableBitmaps); inTableBitmaps = NULL; } if (outTable != NULL) { for (uint32_t d = 0; d < numDevices; d++) { if (outTable[d] == NULL) continue; for (uint32_t p = 0; p < POLITE_NUM_PINS; p++) delete outTable[d][p]; free(outTable[d]); } free(outTable); outTable = NULL; } if (progRouterTables != NULL) delete progRouterTables; } // Implement mapping to tinsel threads void map() { // Let's measure some times struct timeval placementStart, placementFinish; struct timeval routingStart, routingFinish; struct timeval initStart, initFinish; // Release all mapping and heap structures releaseAll(); // Reallocate mapping structures allocateMapping(); // Start placement timer gettimeofday(&placementStart, NULL); // Partition into subgraphs, one per board Placer boards(&graph, numBoardsX, numBoardsY); // Place subgraphs onto 2D mesh const uint32_t placerEffort = 8; boards.place(placerEffort); // For each board #pragma omp parallel for collapse(2) for (uint32_t boardY = 0; boardY < numBoardsY; boardY++) { for (uint32_t boardX = 0; boardX < numBoardsX; boardX++) { // Partition into subgraphs, one per mailbox PartitionId b = boards.mapping[boardY][boardX]; Placer boxes(&boards.subgraphs[b], TinselMailboxMeshXLen, TinselMailboxMeshYLen); boxes.place(placerEffort); // For each mailbox for (uint32_t boxX = 0; boxX < TinselMailboxMeshXLen; boxX++) { for (uint32_t boxY = 0; boxY < TinselMailboxMeshYLen; boxY++) { // Partition into subgraphs, one per thread uint32_t numThreads = 1<<TinselLogThreadsPerMailbox; PartitionId t = boxes.mapping[boxY][boxX]; Placer threads(&boxes.subgraphs[t], numThreads, 1); // For each thread for (uint32_t threadNum = 0; threadNum < numThreads; threadNum++) { // Determine tinsel thread id uint32_t threadId = boardY; threadId = (threadId << TinselMeshXBits) | boardX; threadId = (threadId << TinselMailboxMeshYBits) | boxY; threadId = (threadId << TinselMailboxMeshXBits) | boxX; threadId = (threadId << (TinselLogCoresPerMailbox + TinselLogThreadsPerCore)) | threadNum; // Get subgraph Graph* g = &threads.subgraphs[threadNum]; // Populate fromDeviceAddr mapping uint32_t numDevs = g->incoming->numElems; numDevicesOnThread[threadId] = numDevs; fromDeviceAddr[threadId] = (PDeviceId*) malloc(sizeof(PDeviceId) * numDevs); for (uint32_t devNum = 0; devNum < numDevs; devNum++) fromDeviceAddr[threadId][devNum] = g->labels->elems[devNum]; // Populate toDeviceAddr mapping assert(numDevs < maxLocalDeviceId()); for (uint32_t devNum = 0; devNum < numDevs; devNum++) { PDeviceAddr devAddr = makeDeviceAddr(threadId, devNum); toDeviceAddr[g->labels->elems[devNum]] = devAddr; } } } } } } // Stop placement timer and start routing timer gettimeofday(&placementFinish, NULL); gettimeofday(&routingStart, NULL); // Compute send and receive side routing tables allocateRoutingTables(); computeRoutingTables(); // Stop routing timer and start init timer gettimeofday(&routingFinish, NULL); gettimeofday(&initStart, NULL); // Reallocate and initialise heap structures allocatePartitions(); initialisePartitions(); // Display times, if chatty gettimeofday(&initFinish, NULL); if (chatty > 0) { struct timeval diff; timersub(&placementFinish, &placementStart, &diff); double duration = (double) diff.tv_sec + (double) diff.tv_usec / 1000000.0; printf("POLite mapper profile:\n"); printf(" Partitioning and placement: %lfs\n", duration); timersub(&routingFinish, &routingStart, &diff); duration = (double) diff.tv_sec + (double) diff.tv_usec / 1000000.0; printf(" Routing table construction: %lfs\n", duration); timersub(&initFinish, &initStart, &diff); duration = (double) diff.tv_sec + (double) diff.tv_usec / 1000000.0; printf(" Thread state initialisation: %lfs\n", duration); } } // Constructor PGraph() { char* str = getenv("HOSTLINK_BOXES_X"); int x = str ? atoi(str) : 1; x = x * TinselMeshXLenWithinBox; str = getenv("HOSTLINK_BOXES_Y"); int y = str ? atoi(str) : 1; y = y * TinselMeshYLenWithinBox; constructor(x, y); } PGraph(uint32_t numBoxesX, uint32_t numBoxesY) { int x = numBoxesX * TinselMeshXLenWithinBox; int y = numBoxesY * TinselMeshYLenWithinBox; constructor(x, y); } // Deconstructor ~PGraph() { releaseAll(); for (uint32_t i = 0; i < edgeLabels.numElems; i++) delete edgeLabels.elems[i]; } // Write partition to tinsel machine void writeRAM(HostLink* hostLink, uint8_t** heap, uint32_t* heapSize, uint32_t* heapBase) { // Number of bytes written by each thread uint32_t* writeCount = (uint32_t*) calloc(TinselMaxThreads, sizeof(uint32_t)); // Number of threads completed by each core uint32_t*** threadCount = (uint32_t***) calloc(meshLenX, sizeof(uint32_t**)); for (uint32_t x = 0; x < meshLenX; x++) { threadCount[x] = (uint32_t**) calloc(meshLenY, sizeof(uint32_t*)); for (uint32_t y = 0; y < meshLenY; y++) threadCount[x][y] = (uint32_t*) calloc(TinselCoresPerBoard, sizeof(uint32_t)); } // Initialise write addresses for (int x = 0; x < meshLenX; x++) for (int y = 0; y < meshLenY; y++) for (int c = 0; c < TinselCoresPerBoard; c++) hostLink->setAddr(x, y, c, heapBase[hostLink->toAddr(x, y, c, 0)]); // Write heaps uint32_t done = false; while (! done) { done = true; for (int x = 0; x < meshLenX; x++) { for (int y = 0; y < meshLenY; y++) { for (int c = 0; c < TinselCoresPerBoard; c++) { uint32_t t = threadCount[x][y][c]; if (t < TinselThreadsPerCore) { done = false; uint32_t threadId = hostLink->toAddr(x, y, c, t); uint32_t written = writeCount[threadId]; if (written == heapSize[threadId]) { threadCount[x][y][c] = t+1; if ((t+1) < TinselThreadsPerCore) hostLink->setAddr(x, y, c, heapBase[hostLink->toAddr(x, y, c, t+1)]); } else { uint32_t send = min((heapSize[threadId] - written)>>2, 15); hostLink->store(x, y, c, send, (uint32_t*) &heap[threadId][written]); writeCount[threadId] = written + send * sizeof(uint32_t); } } } } } } // Release memory free(writeCount); for (uint32_t x = 0; x < meshLenX; x++) { for (uint32_t y = 0; y < meshLenY; y++) free(threadCount[x][y]); free(threadCount[x]); } free(threadCount); } // Write graph to tinsel machine void write(HostLink* hostLink) { // Start timer struct timeval start, finish; gettimeofday(&start, NULL); bool useSendBufferOld = hostLink->useSendBuffer; hostLink->useSendBuffer = true; writeRAM(hostLink, vertexMem, vertexMemSize, vertexMemBase); writeRAM(hostLink, threadMem, threadMemSize, threadMemBase); writeRAM(hostLink, inEdgeHeaderMem, inEdgeHeaderMemSize, inEdgeHeaderMemBase); writeRAM(hostLink, inEdgeRestMem, inEdgeRestMemSize, inEdgeRestMemBase); writeRAM(hostLink, outEdgeMem, outEdgeMemSize, outEdgeMemBase); progRouterTables->write(hostLink); hostLink->flush(); hostLink->useSendBuffer = useSendBufferOld; // Display time if chatty gettimeofday(&finish, NULL); if (chatty > 0) { struct timeval diff; timersub(&finish, &start, &diff); double duration = (double) diff.tv_sec + (double) diff.tv_usec / 1000000.0; printf("POLite graph upload time: %lfs\n", duration); } } // Determine fan-in of given device uint32_t fanIn(PDeviceId id) { return graph.fanIn(id); } // Determine fan-out of given device uint32_t fanOut(PDeviceId id) { return graph.fanOut(id); } }; // Read performance stats and store in file inline void politeSaveStats(HostLink* hostLink, const char* filename) { #ifdef POLITE_DUMP_STATS // Open file for performance counters FILE* statsFile = fopen(filename, "wt"); if (statsFile == NULL) { printf("Error creating stats file\n"); exit(EXIT_FAILURE); } uint32_t meshLenX = hostLink->meshXLen; uint32_t meshLenY = hostLink->meshYLen; // Number of caches uint32_t numLines = meshLenX * meshLenY * TinselDCachesPerDRAM * TinselDRAMsPerBoard; // Add on number of cores numLines += meshLenX * meshLenY * TinselCoresPerBoard; // Add on number of threads #ifdef POLITE_COUNT_MSGS numLines += meshLenX * meshLenY * TinselThreadsPerBoard; #endif hostLink->dumpStdOut(statsFile, numLines); fclose(statsFile); #endif } #endif
sub_model_part_skin_detection_process.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Jordi Cotela // #if !defined(KRATOS_SUB_MODEL_PART_SKIN_DETECTION_PROCESS_H_INCLUDED) #define KRATOS_SUB_MODEL_PART_SKIN_DETECTION_PROCESS_H_INCLUDED // System includes #include <string> #include <iostream> // Project includes #include "skin_detection_process.h" namespace Kratos { ///@addtogroup KratosCore ///@{ ///@name Kratos Classes ///@{ /// Create a SubModelPart covering a part of the outside skin of the computation domain where a condition is met. /** For example, create the outer skin for the part of the domain belonging to a given SubModelPart. */ template<SizeType TDim> class KRATOS_API(KRATOS_CORE) SubModelPartSkinDetectionProcess: public SkinDetectionProcess<TDim> { KRATOS_DEFINE_LOCAL_FLAG( NODE_SELECTED ); // Internal class used to select which faces to create. class FaceSelector { public: KRATOS_CLASS_POINTER_DEFINITION(FaceSelector); virtual ~FaceSelector() = default; virtual void Prepare(ModelPart& rMainModelPart) const = 0; virtual bool IsSelected(const Geometry<Node<3>>::PointsArrayType&) const = 0; }; // Select faces where all nodes belong to given SubModelPart. class SelectIfAllNodesOnSubModelPart: public FaceSelector { std::string mName; public: SelectIfAllNodesOnSubModelPart(const std::string& rName): mName(rName) {} void Prepare(ModelPart& rMainModelPart) const override { ModelPart& r_model_part = rMainModelPart.GetSubModelPart(mName); auto node_begin = r_model_part.NodesBegin(); const int num_nodes = r_model_part.NumberOfNodes(); #pragma omp parallel for for (int k = 0; k < num_nodes; k++) { (node_begin+k)->Set(SubModelPartSkinDetectionProcess::NODE_SELECTED); } } bool IsSelected(const Geometry<Node<3>>::PointsArrayType& rNodes) const override { bool select = true; for (auto i_node = rNodes.begin(); i_node != rNodes.end(); ++i_node) { select &= i_node->Is(SubModelPartSkinDetectionProcess::NODE_SELECTED); } return select; } }; public: ///@name Type Definitions ///@{ /// Pointer definition of SubModelPartSkinDetectionProcess KRATOS_CLASS_POINTER_DEFINITION(SubModelPartSkinDetectionProcess); using typename SkinDetectionProcess<TDim>::HashMapVectorIntType; using typename SkinDetectionProcess<TDim>::HashMapVectorIntIdsType; using typename SkinDetectionProcess<TDim>::VectorIndexType; using ConditionCheckType = bool(const Geometry<Node<3>>::PointsArrayType&); ///@} ///@name Life Cycle ///@{ /// Constructor SubModelPartSkinDetectionProcess(ModelPart& rModelPart, Parameters Settings); /// Deleted default constructor. SubModelPartSkinDetectionProcess() = delete; /// Deleted copy constructor. SubModelPartSkinDetectionProcess(SubModelPartSkinDetectionProcess const &rOther) = delete; /// Destructor. ~SubModelPartSkinDetectionProcess() override = default; ///@} ///@name Operators ///@{ /// Deleted sssignment operator. SubModelPartSkinDetectionProcess &operator=(SubModelPartSkinDetectionProcess const &rOther) = delete; ///@} ///@name Operations ///@{ void Execute() override; ///@} ///@name Input and output ///@{ std::string Info() const override { return "SkinDetectionProcess"; } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << "SkinDetectionProcess"; } /// Print object's data. void PrintData(std::ostream& rOStream) const override { } ///@} protected: ///@name Protected Operations ///@{ void CreateConditions( ModelPart& rMainModelPart, ModelPart& rSkinModelPart, HashMapVectorIntType& rInverseFaceMap, HashMapVectorIntIdsType& rPropertiesFaceMap, std::unordered_set<IndexType>& rNodesInTheSkin, const std::string& rConditionName) const override; /** * @brief This method provides the defaults parameters to avoid conflicts between the different constructors */ const Parameters GetDefaultParameters() const override; ///@} private: ///@name Member Variables ///@{ typename FaceSelector::Pointer mpFaceSelector; ///@} ///@name Private Operations ///@{ static bool FaceIsNeeded(const Geometry<Node<3>>::PointsArrayType&) { return true; } ///@} }; // Class SubModelPartSkinDetectionProcess ///@} ///@name Input and output ///@{ /// input stream function template<SizeType TDim> inline std::istream &operator>>(std::istream &rIStream, SubModelPartSkinDetectionProcess<TDim> &rThis); /// output stream function template<SizeType TDim> inline std::ostream &operator<<(std::ostream &rOStream, const SubModelPartSkinDetectionProcess<TDim> &rThis) { rThis.PrintInfo(rOStream); rOStream << std::endl; rThis.PrintData(rOStream); return rOStream; } ///@} ///@} } // namespace Kratos. #endif // KRATOS_SUB_MODEL_PART_SKIN_DETECTION_PROCESS_H_INCLUDED defined
c-parser.c
/* Parser for C and Objective-C. Copyright (C) 1987-2018 Free Software Foundation, Inc. Parser actions based on the old Bison parser; structure somewhat influenced by and fragments based on the C++ parser. 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/>. */ /* TODO: Make sure all relevant comments, and all relevant code from all actions, brought over from old parser. Verify exact correspondence of syntax accepted. Add testcases covering every input symbol in every state in old and new parsers. Include full syntax for GNU C, including erroneous cases accepted with error messages, in syntax productions in comments. Make more diagnostics in the front end generally take an explicit location rather than implicitly using input_location. */ #include "config.h" #define INCLUDE_UNIQUE_PTR #include "system.h" #include "coretypes.h" #include "target.h" #include "function.h" #include "c-tree.h" #include "timevar.h" #include "stringpool.h" #include "cgraph.h" #include "attribs.h" #include "stor-layout.h" #include "varasm.h" #include "trans-mem.h" #include "c-family/c-pragma.h" #include "c-lang.h" #include "c-family/c-objc.h" #include "plugin.h" #include "omp-general.h" #include "omp-offload.h" #include "builtins.h" #include "gomp-constants.h" #include "c-family/c-indentation.h" #include "gimple-expr.h" #include "context.h" #include "gcc-rich-location.h" #include "c-parser.h" #include "gimple-parser.h" #include "read-rtl-function.h" #include "run-rtl-passes.h" #include "intl.h" #include "c-family/name-hint.h" #include "tree-iterator.h" /* We need to walk over decls with incomplete struct/union/enum types after parsing the whole translation unit. In finish_decl(), if the decl is static, has incomplete struct/union/enum type, it is appeneded to incomplete_record_decls. In c_parser_translation_unit(), we iterate over incomplete_record_decls and report error if any of the decls are still incomplete. */ vec<tree> incomplete_record_decls; void set_c_expr_source_range (c_expr *expr, location_t start, location_t finish) { expr->src_range.m_start = start; expr->src_range.m_finish = finish; if (expr->value) set_source_range (expr->value, start, finish); } void set_c_expr_source_range (c_expr *expr, source_range src_range) { expr->src_range = src_range; if (expr->value) set_source_range (expr->value, src_range); } /* Initialization routine for this file. */ void c_parse_init (void) { /* The only initialization required is of the reserved word identifiers. */ unsigned int i; tree id; int mask = 0; /* Make sure RID_MAX hasn't grown past the 8 bits used to hold the keyword in the c_token structure. */ gcc_assert (RID_MAX <= 255); mask |= D_CXXONLY; if (!flag_isoc99) mask |= D_C99; if (flag_no_asm) { mask |= D_ASM | D_EXT; if (!flag_isoc99) mask |= D_EXT89; } if (!c_dialect_objc ()) mask |= D_OBJC | D_CXX_OBJC; ridpointers = ggc_cleared_vec_alloc<tree> ((int) RID_MAX); for (i = 0; i < num_c_common_reswords; i++) { /* If a keyword is disabled, do not enter it into the table and so create a canonical spelling that isn't a keyword. */ if (c_common_reswords[i].disable & mask) { if (warn_cxx_compat && (c_common_reswords[i].disable & D_CXXWARN)) { id = get_identifier (c_common_reswords[i].word); C_SET_RID_CODE (id, RID_CXX_COMPAT_WARN); C_IS_RESERVED_WORD (id) = 1; } continue; } id = get_identifier (c_common_reswords[i].word); C_SET_RID_CODE (id, c_common_reswords[i].rid); C_IS_RESERVED_WORD (id) = 1; ridpointers [(int) c_common_reswords[i].rid] = id; } for (i = 0; i < NUM_INT_N_ENTS; i++) { /* We always create the symbols but they aren't always supported. */ char name[50]; sprintf (name, "__int%d", int_n_data[i].bitsize); id = get_identifier (name); C_SET_RID_CODE (id, RID_FIRST_INT_N + i); C_IS_RESERVED_WORD (id) = 1; } } /* A parser structure recording information about the state and context of parsing. Includes lexer information with up to two tokens of look-ahead; more are not needed for C. */ struct GTY(()) c_parser { /* The look-ahead tokens. */ c_token * GTY((skip)) tokens; /* Buffer for look-ahead tokens. */ c_token tokens_buf[4]; /* How many look-ahead tokens are available (0 - 4, or more if parsing from pre-lexed tokens). */ unsigned int tokens_avail; /* True if a syntax error is being recovered from; false otherwise. c_parser_error sets this flag. It should clear this flag when enough tokens have been consumed to recover from the error. */ BOOL_BITFIELD error : 1; /* True if we're processing a pragma, and shouldn't automatically consume CPP_PRAGMA_EOL. */ BOOL_BITFIELD in_pragma : 1; /* True if we're parsing the outermost block of an if statement. */ BOOL_BITFIELD in_if_block : 1; /* True if we want to lex an untranslated string. */ BOOL_BITFIELD lex_untranslated_string : 1; /* Objective-C specific parser/lexer information. */ /* True if we are in a context where the Objective-C "PQ" keywords are considered keywords. */ BOOL_BITFIELD objc_pq_context : 1; /* True if we are parsing a (potential) Objective-C foreach statement. This is set to true after we parsed 'for (' and while we wait for 'in' or ';' to decide if it's a standard C for loop or an Objective-C foreach loop. */ BOOL_BITFIELD objc_could_be_foreach_context : 1; /* The following flag is needed to contextualize Objective-C lexical analysis. In some cases (e.g., 'int NSObject;'), it is undesirable to bind an identifier to an Objective-C class, even if a class with that name exists. */ BOOL_BITFIELD objc_need_raw_identifier : 1; /* Nonzero if we're processing a __transaction statement. The value is 1 | TM_STMT_ATTR_*. */ unsigned int in_transaction : 4; /* True if we are in a context where the Objective-C "Property attribute" keywords are valid. */ BOOL_BITFIELD objc_property_attr_context : 1; /* Location of the last consumed token. */ location_t last_token_location; }; /* Return a pointer to the Nth token in PARSERs tokens_buf. */ c_token * c_parser_tokens_buf (c_parser *parser, unsigned n) { return &parser->tokens_buf[n]; } /* Return the error state of PARSER. */ bool c_parser_error (c_parser *parser) { return parser->error; } /* Set the error state of PARSER to ERR. */ void c_parser_set_error (c_parser *parser, bool err) { parser->error = err; } /* The actual parser and external interface. ??? Does this need to be garbage-collected? */ static GTY (()) c_parser *the_parser; /* Read in and lex a single token, storing it in *TOKEN. */ static void c_lex_one_token (c_parser *parser, c_token *token) { timevar_push (TV_LEX); token->type = c_lex_with_flags (&token->value, &token->location, &token->flags, (parser->lex_untranslated_string ? C_LEX_STRING_NO_TRANSLATE : 0)); token->id_kind = C_ID_NONE; token->keyword = RID_MAX; token->pragma_kind = PRAGMA_NONE; switch (token->type) { case CPP_NAME: { tree decl; bool objc_force_identifier = parser->objc_need_raw_identifier; if (c_dialect_objc ()) parser->objc_need_raw_identifier = false; if (C_IS_RESERVED_WORD (token->value)) { enum rid rid_code = C_RID_CODE (token->value); if (rid_code == RID_CXX_COMPAT_WARN) { warning_at (token->location, OPT_Wc___compat, "identifier %qE conflicts with C++ keyword", token->value); } else if (rid_code >= RID_FIRST_ADDR_SPACE && rid_code <= RID_LAST_ADDR_SPACE) { addr_space_t as; as = (addr_space_t) (rid_code - RID_FIRST_ADDR_SPACE); targetm.addr_space.diagnose_usage (as, token->location); token->id_kind = C_ID_ADDRSPACE; token->keyword = rid_code; break; } else if (c_dialect_objc () && OBJC_IS_PQ_KEYWORD (rid_code)) { /* We found an Objective-C "pq" keyword (in, out, inout, bycopy, byref, oneway). They need special care because the interpretation depends on the context. */ if (parser->objc_pq_context) { token->type = CPP_KEYWORD; token->keyword = rid_code; break; } else if (parser->objc_could_be_foreach_context && rid_code == RID_IN) { /* We are in Objective-C, inside a (potential) foreach context (which means after having parsed 'for (', but before having parsed ';'), and we found 'in'. We consider it the keyword which terminates the declaration at the beginning of a foreach-statement. Note that this means you can't use 'in' for anything else in that context; in particular, in Objective-C you can't use 'in' as the name of the running variable in a C for loop. We could potentially try to add code here to disambiguate, but it seems a reasonable limitation. */ token->type = CPP_KEYWORD; token->keyword = rid_code; break; } /* Else, "pq" keywords outside of the "pq" context are not keywords, and we fall through to the code for normal tokens. */ } else if (c_dialect_objc () && OBJC_IS_PATTR_KEYWORD (rid_code)) { /* We found an Objective-C "property attribute" keyword (getter, setter, readonly, etc). These are only valid in the property context. */ if (parser->objc_property_attr_context) { token->type = CPP_KEYWORD; token->keyword = rid_code; break; } /* Else they are not special keywords. */ } else if (c_dialect_objc () && (OBJC_IS_AT_KEYWORD (rid_code) || OBJC_IS_CXX_KEYWORD (rid_code))) { /* We found one of the Objective-C "@" keywords (defs, selector, synchronized, etc) or one of the Objective-C "cxx" keywords (class, private, protected, public, try, catch, throw) without a preceding '@' sign. Do nothing and fall through to the code for normal tokens (in C++ we would still consider the CXX ones keywords, but not in C). */ ; } else { token->type = CPP_KEYWORD; token->keyword = rid_code; break; } } decl = lookup_name (token->value); if (decl) { if (TREE_CODE (decl) == TYPE_DECL) { token->id_kind = C_ID_TYPENAME; break; } } else if (c_dialect_objc ()) { tree objc_interface_decl = objc_is_class_name (token->value); /* Objective-C class names are in the same namespace as variables and typedefs, and hence are shadowed by local declarations. */ if (objc_interface_decl && (!objc_force_identifier || global_bindings_p ())) { token->value = objc_interface_decl; token->id_kind = C_ID_CLASSNAME; break; } } token->id_kind = C_ID_ID; } break; case CPP_AT_NAME: /* This only happens in Objective-C; it must be a keyword. */ token->type = CPP_KEYWORD; switch (C_RID_CODE (token->value)) { /* Replace 'class' with '@class', 'private' with '@private', etc. This prevents confusion with the C++ keyword 'class', and makes the tokens consistent with other Objective-C 'AT' keywords. For example '@class' is reported as RID_AT_CLASS which is consistent with '@synchronized', which is reported as RID_AT_SYNCHRONIZED. */ case RID_CLASS: token->keyword = RID_AT_CLASS; break; case RID_PRIVATE: token->keyword = RID_AT_PRIVATE; break; case RID_PROTECTED: token->keyword = RID_AT_PROTECTED; break; case RID_PUBLIC: token->keyword = RID_AT_PUBLIC; break; case RID_THROW: token->keyword = RID_AT_THROW; break; case RID_TRY: token->keyword = RID_AT_TRY; break; case RID_CATCH: token->keyword = RID_AT_CATCH; break; case RID_SYNCHRONIZED: token->keyword = RID_AT_SYNCHRONIZED; break; default: token->keyword = C_RID_CODE (token->value); } break; case CPP_COLON: case CPP_COMMA: case CPP_CLOSE_PAREN: case CPP_SEMICOLON: /* These tokens may affect the interpretation of any identifiers following, if doing Objective-C. */ if (c_dialect_objc ()) parser->objc_need_raw_identifier = false; break; case CPP_PRAGMA: /* We smuggled the cpp_token->u.pragma value in an INTEGER_CST. */ token->pragma_kind = (enum pragma_kind) TREE_INT_CST_LOW (token->value); token->value = NULL; break; default: break; } timevar_pop (TV_LEX); } /* Return a pointer to the next token from PARSER, reading it in if necessary. */ c_token * c_parser_peek_token (c_parser *parser) { if (parser->tokens_avail == 0) { c_lex_one_token (parser, &parser->tokens[0]); parser->tokens_avail = 1; } return &parser->tokens[0]; } /* Return a pointer to the next-but-one token from PARSER, reading it in if necessary. The next token is already read in. */ c_token * c_parser_peek_2nd_token (c_parser *parser) { if (parser->tokens_avail >= 2) return &parser->tokens[1]; gcc_assert (parser->tokens_avail == 1); gcc_assert (parser->tokens[0].type != CPP_EOF); gcc_assert (parser->tokens[0].type != CPP_PRAGMA_EOL); c_lex_one_token (parser, &parser->tokens[1]); parser->tokens_avail = 2; return &parser->tokens[1]; } /* Return a pointer to the Nth token from PARSER, reading it in if necessary. The N-1th token is already read in. */ c_token * c_parser_peek_nth_token (c_parser *parser, unsigned int n) { /* N is 1-based, not zero-based. */ gcc_assert (n > 0); if (parser->tokens_avail >= n) return &parser->tokens[n - 1]; gcc_assert (parser->tokens_avail == n - 1); c_lex_one_token (parser, &parser->tokens[n - 1]); parser->tokens_avail = n; return &parser->tokens[n - 1]; } bool c_keyword_starts_typename (enum rid keyword) { switch (keyword) { case RID_UNSIGNED: case RID_LONG: case RID_SHORT: case RID_SIGNED: case RID_COMPLEX: case RID_INT: case RID_CHAR: case RID_FLOAT: case RID_DOUBLE: case RID_VOID: case RID_DFLOAT32: case RID_DFLOAT64: case RID_DFLOAT128: CASE_RID_FLOATN_NX: case RID_BOOL: case RID_ENUM: case RID_STRUCT: case RID_UNION: case RID_TYPEOF: case RID_CONST: case RID_ATOMIC: case RID_VOLATILE: case RID_RESTRICT: case RID_ATTRIBUTE: case RID_FRACT: case RID_ACCUM: case RID_SAT: case RID_AUTO_TYPE: case RID_ALIGNAS: return true; default: if (keyword >= RID_FIRST_INT_N && keyword < RID_FIRST_INT_N + NUM_INT_N_ENTS && int_n_enabled_p[keyword - RID_FIRST_INT_N]) return true; return false; } } /* Return true if TOKEN can start a type name, false otherwise. */ bool c_token_starts_typename (c_token *token) { switch (token->type) { case CPP_NAME: switch (token->id_kind) { case C_ID_ID: return false; case C_ID_ADDRSPACE: return true; case C_ID_TYPENAME: return true; case C_ID_CLASSNAME: gcc_assert (c_dialect_objc ()); return true; default: gcc_unreachable (); } case CPP_KEYWORD: return c_keyword_starts_typename (token->keyword); case CPP_LESS: if (c_dialect_objc ()) return true; return false; default: return false; } } /* Return true if the next token from PARSER can start a type name, false otherwise. LA specifies how to do lookahead in order to detect unknown type names. If unsure, pick CLA_PREFER_ID. */ static inline bool c_parser_next_tokens_start_typename (c_parser *parser, enum c_lookahead_kind la) { c_token *token = c_parser_peek_token (parser); if (c_token_starts_typename (token)) return true; /* Try a bit harder to detect an unknown typename. */ if (la != cla_prefer_id && token->type == CPP_NAME && token->id_kind == C_ID_ID /* Do not try too hard when we could have "object in array". */ && !parser->objc_could_be_foreach_context && (la == cla_prefer_type || c_parser_peek_2nd_token (parser)->type == CPP_NAME || c_parser_peek_2nd_token (parser)->type == CPP_MULT) /* Only unknown identifiers. */ && !lookup_name (token->value)) return true; return false; } /* Return true if TOKEN is a type qualifier, false otherwise. */ static bool c_token_is_qualifier (c_token *token) { switch (token->type) { case CPP_NAME: switch (token->id_kind) { case C_ID_ADDRSPACE: return true; default: return false; } case CPP_KEYWORD: switch (token->keyword) { case RID_CONST: case RID_VOLATILE: case RID_RESTRICT: case RID_ATTRIBUTE: case RID_ATOMIC: return true; default: return false; } case CPP_LESS: return false; default: gcc_unreachable (); } } /* Return true if the next token from PARSER is a type qualifier, false otherwise. */ static inline bool c_parser_next_token_is_qualifier (c_parser *parser) { c_token *token = c_parser_peek_token (parser); return c_token_is_qualifier (token); } /* Return true if TOKEN can start declaration specifiers, false otherwise. */ static bool c_token_starts_declspecs (c_token *token) { switch (token->type) { case CPP_NAME: switch (token->id_kind) { case C_ID_ID: return false; case C_ID_ADDRSPACE: return true; case C_ID_TYPENAME: return true; case C_ID_CLASSNAME: gcc_assert (c_dialect_objc ()); return true; default: gcc_unreachable (); } case CPP_KEYWORD: switch (token->keyword) { case RID_STATIC: case RID_EXTERN: case RID_REGISTER: case RID_TYPEDEF: case RID_INLINE: case RID_NORETURN: case RID_AUTO: case RID_THREAD: case RID_UNSIGNED: case RID_LONG: case RID_SHORT: case RID_SIGNED: case RID_COMPLEX: case RID_INT: case RID_CHAR: case RID_FLOAT: case RID_DOUBLE: case RID_VOID: case RID_DFLOAT32: case RID_DFLOAT64: case RID_DFLOAT128: CASE_RID_FLOATN_NX: case RID_BOOL: case RID_ENUM: case RID_STRUCT: case RID_UNION: case RID_TYPEOF: case RID_CONST: case RID_VOLATILE: case RID_RESTRICT: case RID_ATTRIBUTE: case RID_FRACT: case RID_ACCUM: case RID_SAT: case RID_ALIGNAS: case RID_ATOMIC: case RID_AUTO_TYPE: return true; default: if (token->keyword >= RID_FIRST_INT_N && token->keyword < RID_FIRST_INT_N + NUM_INT_N_ENTS && int_n_enabled_p[token->keyword - RID_FIRST_INT_N]) return true; return false; } case CPP_LESS: if (c_dialect_objc ()) return true; return false; default: return false; } } /* Return true if TOKEN can start declaration specifiers or a static assertion, false otherwise. */ static bool c_token_starts_declaration (c_token *token) { if (c_token_starts_declspecs (token) || token->keyword == RID_STATIC_ASSERT) return true; else return false; } /* Return true if the next token from PARSER can start declaration specifiers, false otherwise. */ bool c_parser_next_token_starts_declspecs (c_parser *parser) { c_token *token = c_parser_peek_token (parser); /* In Objective-C, a classname normally starts a declspecs unless it is immediately followed by a dot. In that case, it is the Objective-C 2.0 "dot-syntax" for class objects, ie, calls the setter/getter on the class. c_token_starts_declspecs() can't differentiate between the two cases because it only checks the current token, so we have a special check here. */ if (c_dialect_objc () && token->type == CPP_NAME && token->id_kind == C_ID_CLASSNAME && c_parser_peek_2nd_token (parser)->type == CPP_DOT) return false; return c_token_starts_declspecs (token); } /* Return true if the next tokens from PARSER can start declaration specifiers or a static assertion, false otherwise. */ bool c_parser_next_tokens_start_declaration (c_parser *parser) { c_token *token = c_parser_peek_token (parser); /* Same as above. */ if (c_dialect_objc () && token->type == CPP_NAME && token->id_kind == C_ID_CLASSNAME && c_parser_peek_2nd_token (parser)->type == CPP_DOT) return false; /* Labels do not start declarations. */ if (token->type == CPP_NAME && c_parser_peek_2nd_token (parser)->type == CPP_COLON) return false; if (c_token_starts_declaration (token)) return true; if (c_parser_next_tokens_start_typename (parser, cla_nonabstract_decl)) return true; return false; } /* Consume the next token from PARSER. */ void c_parser_consume_token (c_parser *parser) { gcc_assert (parser->tokens_avail >= 1); gcc_assert (parser->tokens[0].type != CPP_EOF); gcc_assert (!parser->in_pragma || parser->tokens[0].type != CPP_PRAGMA_EOL); gcc_assert (parser->error || parser->tokens[0].type != CPP_PRAGMA); parser->last_token_location = parser->tokens[0].location; if (parser->tokens != &parser->tokens_buf[0]) parser->tokens++; else if (parser->tokens_avail == 2) parser->tokens[0] = parser->tokens[1]; parser->tokens_avail--; } /* Expect the current token to be a #pragma. Consume it and remember that we've begun parsing a pragma. */ static void c_parser_consume_pragma (c_parser *parser) { gcc_assert (!parser->in_pragma); gcc_assert (parser->tokens_avail >= 1); gcc_assert (parser->tokens[0].type == CPP_PRAGMA); if (parser->tokens != &parser->tokens_buf[0]) parser->tokens++; else if (parser->tokens_avail == 2) parser->tokens[0] = parser->tokens[1]; parser->tokens_avail--; parser->in_pragma = true; } /* Update the global input_location from TOKEN. */ static inline void c_parser_set_source_position_from_token (c_token *token) { if (token->type != CPP_EOF) { input_location = token->location; } } /* Helper function for c_parser_error. Having peeked a token of kind TOK1_KIND that might signify a conflict marker, peek successor tokens to determine if we actually do have a conflict marker. Specifically, we consider a run of 7 '<', '=' or '>' characters at the start of a line as a conflict marker. These come through the lexer as three pairs and a single, e.g. three CPP_LSHIFT ("<<") and a CPP_LESS ('<'). If it returns true, *OUT_LOC is written to with the location/range of the marker. */ static bool c_parser_peek_conflict_marker (c_parser *parser, enum cpp_ttype tok1_kind, location_t *out_loc) { c_token *token2 = c_parser_peek_2nd_token (parser); if (token2->type != tok1_kind) return false; c_token *token3 = c_parser_peek_nth_token (parser, 3); if (token3->type != tok1_kind) return false; c_token *token4 = c_parser_peek_nth_token (parser, 4); if (token4->type != conflict_marker_get_final_tok_kind (tok1_kind)) return false; /* It must be at the start of the line. */ location_t start_loc = c_parser_peek_token (parser)->location; if (LOCATION_COLUMN (start_loc) != 1) return false; /* We have a conflict marker. Construct a location of the form: <<<<<<< ^~~~~~~ with start == caret, finishing at the end of the marker. */ location_t finish_loc = get_finish (token4->location); *out_loc = make_location (start_loc, start_loc, finish_loc); return true; } /* Issue a diagnostic of the form FILE:LINE: MESSAGE before TOKEN where TOKEN is the next token in the input stream of PARSER. MESSAGE (specified by the caller) is usually of the form "expected OTHER-TOKEN". Use RICHLOC as the location of the diagnostic. Do not issue a diagnostic if still recovering from an error. Return true iff an error was actually emitted. ??? This is taken from the C++ parser, but building up messages in this way is not i18n-friendly and some other approach should be used. */ static bool c_parser_error_richloc (c_parser *parser, const char *gmsgid, rich_location *richloc) { c_token *token = c_parser_peek_token (parser); if (parser->error) return false; parser->error = true; if (!gmsgid) return false; /* If this is actually a conflict marker, report it as such. */ if (token->type == CPP_LSHIFT || token->type == CPP_RSHIFT || token->type == CPP_EQ_EQ) { location_t loc; if (c_parser_peek_conflict_marker (parser, token->type, &loc)) { error_at (loc, "version control conflict marker in file"); return true; } } c_parse_error (gmsgid, /* Because c_parse_error does not understand CPP_KEYWORD, keywords are treated like identifiers. */ (token->type == CPP_KEYWORD ? CPP_NAME : token->type), /* ??? The C parser does not save the cpp flags of a token, we need to pass 0 here and we will not get the source spelling of some tokens but rather the canonical spelling. */ token->value, /*flags=*/0, richloc); return true; } /* As c_parser_error_richloc, but issue the message at the location of PARSER's next token, or at input_location if the next token is EOF. */ bool c_parser_error (c_parser *parser, const char *gmsgid) { c_token *token = c_parser_peek_token (parser); c_parser_set_source_position_from_token (token); rich_location richloc (line_table, input_location); return c_parser_error_richloc (parser, gmsgid, &richloc); } /* Some tokens naturally come in pairs e.g.'(' and ')'. This class is for tracking such a matching pair of symbols. In particular, it tracks the location of the first token, so that if the second token is missing, we can highlight the location of the first token when notifying the user about the problem. */ template <typename traits_t> class token_pair { public: /* token_pair's ctor. */ token_pair () : m_open_loc (UNKNOWN_LOCATION) {} /* If the next token is the opening symbol for this pair, consume it and return true. Otherwise, issue an error and return false. In either case, record the location of the opening token. */ bool require_open (c_parser *parser) { c_token *token = c_parser_peek_token (parser); if (token) m_open_loc = token->location; return c_parser_require (parser, traits_t::open_token_type, traits_t::open_gmsgid); } /* Consume the next token from PARSER, recording its location as that of the opening token within the pair. */ void consume_open (c_parser *parser) { c_token *token = c_parser_peek_token (parser); gcc_assert (token->type == traits_t::open_token_type); m_open_loc = token->location; c_parser_consume_token (parser); } /* If the next token is the closing symbol for this pair, consume it and return true. Otherwise, issue an error, highlighting the location of the corresponding opening token, and return false. */ bool require_close (c_parser *parser) const { return c_parser_require (parser, traits_t::close_token_type, traits_t::close_gmsgid, m_open_loc); } /* Like token_pair::require_close, except that tokens will be skipped until the desired token is found. An error message is still produced if the next token is not as expected. */ void skip_until_found_close (c_parser *parser) const { c_parser_skip_until_found (parser, traits_t::close_token_type, traits_t::close_gmsgid, m_open_loc); } private: location_t m_open_loc; }; /* Traits for token_pair<T> for tracking matching pairs of parentheses. */ struct matching_paren_traits { static const enum cpp_ttype open_token_type = CPP_OPEN_PAREN; static const char * const open_gmsgid; static const enum cpp_ttype close_token_type = CPP_CLOSE_PAREN; static const char * const close_gmsgid; }; const char * const matching_paren_traits::open_gmsgid = "expected %<(%>"; const char * const matching_paren_traits::close_gmsgid = "expected %<)%>"; /* "matching_parens" is a token_pair<T> class for tracking matching pairs of parentheses. */ typedef token_pair<matching_paren_traits> matching_parens; /* Traits for token_pair<T> for tracking matching pairs of braces. */ struct matching_brace_traits { static const enum cpp_ttype open_token_type = CPP_OPEN_BRACE; static const char * const open_gmsgid; static const enum cpp_ttype close_token_type = CPP_CLOSE_BRACE; static const char * const close_gmsgid; }; const char * const matching_brace_traits::open_gmsgid = "expected %<{%>"; const char * const matching_brace_traits::close_gmsgid = "expected %<}%>"; /* "matching_braces" is a token_pair<T> class for tracking matching pairs of braces. */ typedef token_pair<matching_brace_traits> matching_braces; /* Get a description of the matching symbol to TYPE e.g. "(" for CPP_CLOSE_PAREN. */ static const char * get_matching_symbol (enum cpp_ttype type) { switch (type) { default: gcc_unreachable (); return ""; case CPP_CLOSE_PAREN: return "("; case CPP_CLOSE_BRACE: return "{"; } } /* If the next token is of the indicated TYPE, consume it. Otherwise, issue the error MSGID. If MSGID is NULL then a message has already been produced and no message will be produced this time. Returns true if found, false otherwise. If MATCHING_LOCATION is not UNKNOWN_LOCATION, then highlight it within any error as the location of an "opening" token matching the close token TYPE (e.g. the location of the '(' when TYPE is CPP_CLOSE_PAREN). If TYPE_IS_UNIQUE is true (the default) then msgid describes exactly one type (e.g. "expected %<)%>") and thus it may be reasonable to attempt to generate a fix-it hint for the problem. Otherwise msgid describes multiple token types (e.g. "expected %<;%>, %<,%> or %<)%>"), and thus we shouldn't attempt to generate a fix-it hint. */ bool c_parser_require (c_parser *parser, enum cpp_ttype type, const char *msgid, location_t matching_location, bool type_is_unique) { if (c_parser_next_token_is (parser, type)) { c_parser_consume_token (parser); return true; } else { location_t next_token_loc = c_parser_peek_token (parser)->location; gcc_rich_location richloc (next_token_loc); /* Potentially supply a fix-it hint, suggesting to add the missing token immediately after the *previous* token. This may move the primary location within richloc. */ if (!parser->error && type_is_unique) maybe_suggest_missing_token_insertion (&richloc, type, parser->last_token_location); /* If matching_location != UNKNOWN_LOCATION, highlight it. Attempt to consolidate diagnostics by printing it as a secondary range within the main diagnostic. */ bool added_matching_location = false; if (matching_location != UNKNOWN_LOCATION) added_matching_location = richloc.add_location_if_nearby (matching_location); if (c_parser_error_richloc (parser, msgid, &richloc)) /* If we weren't able to consolidate matching_location, then print it as a secondary diagnostic. */ if (matching_location != UNKNOWN_LOCATION && !added_matching_location) inform (matching_location, "to match this %qs", get_matching_symbol (type)); return false; } } /* If the next token is the indicated keyword, consume it. Otherwise, issue the error MSGID. Returns true if found, false otherwise. */ static bool c_parser_require_keyword (c_parser *parser, enum rid keyword, const char *msgid) { if (c_parser_next_token_is_keyword (parser, keyword)) { c_parser_consume_token (parser); return true; } else { c_parser_error (parser, msgid); return false; } } /* Like c_parser_require, except that tokens will be skipped until the desired token is found. An error message is still produced if the next token is not as expected. If MSGID is NULL then a message has already been produced and no message will be produced this time. If MATCHING_LOCATION is not UNKNOWN_LOCATION, then highlight it within any error as the location of an "opening" token matching the close token TYPE (e.g. the location of the '(' when TYPE is CPP_CLOSE_PAREN). */ void c_parser_skip_until_found (c_parser *parser, enum cpp_ttype type, const char *msgid, location_t matching_location) { unsigned nesting_depth = 0; if (c_parser_require (parser, type, msgid, matching_location)) return; /* Skip tokens until the desired token is found. */ while (true) { /* Peek at the next token. */ c_token *token = c_parser_peek_token (parser); /* If we've reached the token we want, consume it and stop. */ if (token->type == type && !nesting_depth) { c_parser_consume_token (parser); break; } /* If we've run out of tokens, stop. */ if (token->type == CPP_EOF) return; if (token->type == CPP_PRAGMA_EOL && parser->in_pragma) return; if (token->type == CPP_OPEN_BRACE || token->type == CPP_OPEN_PAREN || token->type == CPP_OPEN_SQUARE) ++nesting_depth; else if (token->type == CPP_CLOSE_BRACE || token->type == CPP_CLOSE_PAREN || token->type == CPP_CLOSE_SQUARE) { if (nesting_depth-- == 0) break; } /* Consume this token. */ c_parser_consume_token (parser); } parser->error = false; } /* Skip tokens until the end of a parameter is found, but do not consume the comma, semicolon or closing delimiter. */ static void c_parser_skip_to_end_of_parameter (c_parser *parser) { unsigned nesting_depth = 0; while (true) { c_token *token = c_parser_peek_token (parser); if ((token->type == CPP_COMMA || token->type == CPP_SEMICOLON) && !nesting_depth) break; /* If we've run out of tokens, stop. */ if (token->type == CPP_EOF) return; if (token->type == CPP_PRAGMA_EOL && parser->in_pragma) return; if (token->type == CPP_OPEN_BRACE || token->type == CPP_OPEN_PAREN || token->type == CPP_OPEN_SQUARE) ++nesting_depth; else if (token->type == CPP_CLOSE_BRACE || token->type == CPP_CLOSE_PAREN || token->type == CPP_CLOSE_SQUARE) { if (nesting_depth-- == 0) break; } /* Consume this token. */ c_parser_consume_token (parser); } parser->error = false; } /* Expect to be at the end of the pragma directive and consume an end of line marker. */ static void c_parser_skip_to_pragma_eol (c_parser *parser, bool error_if_not_eol = true) { gcc_assert (parser->in_pragma); parser->in_pragma = false; if (error_if_not_eol && c_parser_peek_token (parser)->type != CPP_PRAGMA_EOL) c_parser_error (parser, "expected end of line"); cpp_ttype token_type; do { c_token *token = c_parser_peek_token (parser); token_type = token->type; if (token_type == CPP_EOF) break; c_parser_consume_token (parser); } while (token_type != CPP_PRAGMA_EOL); parser->error = false; } /* Skip tokens until we have consumed an entire block, or until we have consumed a non-nested ';'. */ static void c_parser_skip_to_end_of_block_or_statement (c_parser *parser) { unsigned nesting_depth = 0; bool save_error = parser->error; while (true) { c_token *token; /* Peek at the next token. */ token = c_parser_peek_token (parser); switch (token->type) { case CPP_EOF: return; case CPP_PRAGMA_EOL: if (parser->in_pragma) return; break; case CPP_SEMICOLON: /* If the next token is a ';', we have reached the end of the statement. */ if (!nesting_depth) { /* Consume the ';'. */ c_parser_consume_token (parser); goto finished; } break; case CPP_CLOSE_BRACE: /* If the next token is a non-nested '}', then we have reached the end of the current block. */ if (nesting_depth == 0 || --nesting_depth == 0) { c_parser_consume_token (parser); goto finished; } break; case CPP_OPEN_BRACE: /* If it the next token is a '{', then we are entering a new block. Consume the entire block. */ ++nesting_depth; break; case CPP_PRAGMA: /* If we see a pragma, consume the whole thing at once. We have some safeguards against consuming pragmas willy-nilly. Normally, we'd expect to be here with parser->error set, which disables these safeguards. But it's possible to get here for secondary error recovery, after parser->error has been cleared. */ c_parser_consume_pragma (parser); c_parser_skip_to_pragma_eol (parser); parser->error = save_error; continue; default: break; } c_parser_consume_token (parser); } finished: parser->error = false; } /* CPP's options (initialized by c-opts.c). */ extern cpp_options *cpp_opts; /* Save the warning flags which are controlled by __extension__. */ static inline int disable_extension_diagnostics (void) { int ret = (pedantic | (warn_pointer_arith << 1) | (warn_traditional << 2) | (flag_iso << 3) | (warn_long_long << 4) | (warn_cxx_compat << 5) | (warn_overlength_strings << 6) /* warn_c90_c99_compat has three states: -1/0/1, so we must play tricks to properly restore it. */ | ((warn_c90_c99_compat == 1) << 7) | ((warn_c90_c99_compat == -1) << 8) /* Similarly for warn_c99_c11_compat. */ | ((warn_c99_c11_compat == 1) << 9) | ((warn_c99_c11_compat == -1) << 10) ); cpp_opts->cpp_pedantic = pedantic = 0; warn_pointer_arith = 0; cpp_opts->cpp_warn_traditional = warn_traditional = 0; flag_iso = 0; cpp_opts->cpp_warn_long_long = warn_long_long = 0; warn_cxx_compat = 0; warn_overlength_strings = 0; warn_c90_c99_compat = 0; warn_c99_c11_compat = 0; return ret; } /* Restore the warning flags which are controlled by __extension__. FLAGS is the return value from disable_extension_diagnostics. */ static inline void restore_extension_diagnostics (int flags) { cpp_opts->cpp_pedantic = pedantic = flags & 1; warn_pointer_arith = (flags >> 1) & 1; cpp_opts->cpp_warn_traditional = warn_traditional = (flags >> 2) & 1; flag_iso = (flags >> 3) & 1; cpp_opts->cpp_warn_long_long = warn_long_long = (flags >> 4) & 1; warn_cxx_compat = (flags >> 5) & 1; warn_overlength_strings = (flags >> 6) & 1; /* See above for why is this needed. */ warn_c90_c99_compat = (flags >> 7) & 1 ? 1 : ((flags >> 8) & 1 ? -1 : 0); warn_c99_c11_compat = (flags >> 9) & 1 ? 1 : ((flags >> 10) & 1 ? -1 : 0); } /* Helper data structure for parsing #pragma acc routine. */ struct oacc_routine_data { bool error_seen; /* Set if error has been reported. */ bool fndecl_seen; /* Set if one fn decl/definition has been seen already. */ tree clauses; location_t loc; }; static void c_parser_external_declaration (c_parser *); static void c_parser_asm_definition (c_parser *); static void c_parser_declaration_or_fndef (c_parser *, bool, bool, bool, bool, bool, tree *, vec<c_token>, struct oacc_routine_data * = NULL, bool * = NULL); static void c_parser_static_assert_declaration_no_semi (c_parser *); static void c_parser_static_assert_declaration (c_parser *); static struct c_typespec c_parser_enum_specifier (c_parser *); static struct c_typespec c_parser_struct_or_union_specifier (c_parser *); static tree c_parser_struct_declaration (c_parser *); static struct c_typespec c_parser_typeof_specifier (c_parser *); static tree c_parser_alignas_specifier (c_parser *); static struct c_declarator *c_parser_direct_declarator (c_parser *, bool, c_dtr_syn, bool *); static struct c_declarator *c_parser_direct_declarator_inner (c_parser *, bool, struct c_declarator *); static struct c_arg_info *c_parser_parms_declarator (c_parser *, bool, tree); static struct c_arg_info *c_parser_parms_list_declarator (c_parser *, tree, tree); static struct c_parm *c_parser_parameter_declaration (c_parser *, tree); static tree c_parser_simple_asm_expr (c_parser *); static tree c_parser_attributes (c_parser *); static struct c_expr c_parser_initializer (c_parser *); static struct c_expr c_parser_braced_init (c_parser *, tree, bool, struct obstack *); static void c_parser_initelt (c_parser *, struct obstack *); static void c_parser_initval (c_parser *, struct c_expr *, struct obstack *); static tree c_parser_compound_statement (c_parser *); static void c_parser_compound_statement_nostart (c_parser *); static void c_parser_label (c_parser *); static void c_parser_statement (c_parser *, bool *, location_t * = NULL); static void c_parser_statement_after_labels (c_parser *, bool *, vec<tree> * = NULL); static tree c_parser_c99_block_statement (c_parser *, bool *, location_t * = NULL); static void c_parser_if_statement (c_parser *, bool *, vec<tree> *); static void c_parser_switch_statement (c_parser *, bool *); static void c_parser_while_statement (c_parser *, bool, unsigned short, bool *); static void c_parser_do_statement (c_parser *, bool, unsigned short); static void c_parser_for_statement (c_parser *, bool, unsigned short, bool *); static tree c_parser_asm_statement (c_parser *); static tree c_parser_asm_operands (c_parser *); static tree c_parser_asm_goto_operands (c_parser *); static tree c_parser_asm_clobbers (c_parser *); static struct c_expr c_parser_expr_no_commas (c_parser *, struct c_expr *, tree = NULL_TREE); static struct c_expr c_parser_conditional_expression (c_parser *, struct c_expr *, tree); static struct c_expr c_parser_binary_expression (c_parser *, struct c_expr *, tree); static struct c_expr c_parser_cast_expression (c_parser *, struct c_expr *); static struct c_expr c_parser_unary_expression (c_parser *); static struct c_expr c_parser_sizeof_expression (c_parser *); static struct c_expr c_parser_alignof_expression (c_parser *); static struct c_expr c_parser_postfix_expression (c_parser *); static struct c_expr c_parser_postfix_expression_after_paren_type (c_parser *, struct c_type_name *, location_t); static struct c_expr c_parser_postfix_expression_after_primary (c_parser *, location_t loc, struct c_expr); static tree c_parser_transaction (c_parser *, enum rid); static struct c_expr c_parser_transaction_expression (c_parser *, enum rid); static tree c_parser_transaction_cancel (c_parser *); static struct c_expr c_parser_expression (c_parser *); static struct c_expr c_parser_expression_conv (c_parser *); static vec<tree, va_gc> *c_parser_expr_list (c_parser *, bool, bool, vec<tree, va_gc> **, location_t *, tree *, vec<location_t> *, unsigned int * = NULL); static void c_parser_oacc_declare (c_parser *); static void c_parser_oacc_enter_exit_data (c_parser *, bool); static void c_parser_oacc_update (c_parser *); static void c_parser_omp_construct (c_parser *, bool *); static void c_parser_omp_threadprivate (c_parser *); static void c_parser_omp_barrier (c_parser *); static void c_parser_omp_flush (c_parser *); static tree c_parser_omp_for_loop (location_t, c_parser *, enum tree_code, tree, tree *, bool *); static void c_parser_omp_taskwait (c_parser *); static void c_parser_omp_taskyield (c_parser *); static void c_parser_omp_cancel (c_parser *); enum pragma_context { pragma_external, pragma_struct, pragma_param, pragma_stmt, pragma_compound }; static bool c_parser_pragma (c_parser *, enum pragma_context, bool *); static void c_parser_omp_cancellation_point (c_parser *, enum pragma_context); static bool c_parser_omp_target (c_parser *, enum pragma_context, bool *); static void c_parser_omp_end_declare_target (c_parser *); static void c_parser_omp_declare (c_parser *, enum pragma_context); static bool c_parser_omp_ordered (c_parser *, enum pragma_context, bool *); static void c_parser_oacc_routine (c_parser *, enum pragma_context); /* These Objective-C parser functions are only ever called when compiling Objective-C. */ static void c_parser_objc_class_definition (c_parser *, tree); static void c_parser_objc_class_instance_variables (c_parser *); static void c_parser_objc_class_declaration (c_parser *); static void c_parser_objc_alias_declaration (c_parser *); static void c_parser_objc_protocol_definition (c_parser *, tree); static bool c_parser_objc_method_type (c_parser *); static void c_parser_objc_method_definition (c_parser *); static void c_parser_objc_methodprotolist (c_parser *); static void c_parser_objc_methodproto (c_parser *); static tree c_parser_objc_method_decl (c_parser *, bool, tree *, tree *); static tree c_parser_objc_type_name (c_parser *); static tree c_parser_objc_protocol_refs (c_parser *); static void c_parser_objc_try_catch_finally_statement (c_parser *); static void c_parser_objc_synchronized_statement (c_parser *); static tree c_parser_objc_selector (c_parser *); static tree c_parser_objc_selector_arg (c_parser *); static tree c_parser_objc_receiver (c_parser *); static tree c_parser_objc_message_args (c_parser *); static tree c_parser_objc_keywordexpr (c_parser *); static void c_parser_objc_at_property_declaration (c_parser *); static void c_parser_objc_at_synthesize_declaration (c_parser *); static void c_parser_objc_at_dynamic_declaration (c_parser *); static bool c_parser_objc_diagnose_bad_element_prefix (c_parser *, struct c_declspecs *); static void c_parser_parse_rtl_body (c_parser *parser, char *start_with_pass); /* Parse a translation unit (C90 6.7, C99 6.9, C11 6.9). translation-unit: external-declarations external-declarations: external-declaration external-declarations external-declaration GNU extensions: translation-unit: empty */ static void c_parser_translation_unit (c_parser *parser) { if (c_parser_next_token_is (parser, CPP_EOF)) { pedwarn (c_parser_peek_token (parser)->location, OPT_Wpedantic, "ISO C forbids an empty translation unit"); } else { void *obstack_position = obstack_alloc (&parser_obstack, 0); mark_valid_location_for_stdc_pragma (false); do { ggc_collect (); c_parser_external_declaration (parser); obstack_free (&parser_obstack, obstack_position); } while (c_parser_next_token_is_not (parser, CPP_EOF)); } unsigned int i; tree decl; FOR_EACH_VEC_ELT (incomplete_record_decls, i, decl) if (DECL_SIZE (decl) == NULL_TREE && TREE_TYPE (decl) != error_mark_node) error ("storage size of %q+D isn%'t known", decl); } /* Parse an external declaration (C90 6.7, C99 6.9, C11 6.9). external-declaration: function-definition declaration GNU extensions: external-declaration: asm-definition ; __extension__ external-declaration Objective-C: external-declaration: objc-class-definition objc-class-declaration objc-alias-declaration objc-protocol-definition objc-method-definition @end */ static void c_parser_external_declaration (c_parser *parser) { int ext; switch (c_parser_peek_token (parser)->type) { case CPP_KEYWORD: switch (c_parser_peek_token (parser)->keyword) { case RID_EXTENSION: ext = disable_extension_diagnostics (); c_parser_consume_token (parser); c_parser_external_declaration (parser); restore_extension_diagnostics (ext); break; case RID_ASM: c_parser_asm_definition (parser); break; case RID_AT_INTERFACE: case RID_AT_IMPLEMENTATION: gcc_assert (c_dialect_objc ()); c_parser_objc_class_definition (parser, NULL_TREE); break; case RID_AT_CLASS: gcc_assert (c_dialect_objc ()); c_parser_objc_class_declaration (parser); break; case RID_AT_ALIAS: gcc_assert (c_dialect_objc ()); c_parser_objc_alias_declaration (parser); break; case RID_AT_PROTOCOL: gcc_assert (c_dialect_objc ()); c_parser_objc_protocol_definition (parser, NULL_TREE); break; case RID_AT_PROPERTY: gcc_assert (c_dialect_objc ()); c_parser_objc_at_property_declaration (parser); break; case RID_AT_SYNTHESIZE: gcc_assert (c_dialect_objc ()); c_parser_objc_at_synthesize_declaration (parser); break; case RID_AT_DYNAMIC: gcc_assert (c_dialect_objc ()); c_parser_objc_at_dynamic_declaration (parser); break; case RID_AT_END: gcc_assert (c_dialect_objc ()); c_parser_consume_token (parser); objc_finish_implementation (); break; default: goto decl_or_fndef; } break; case CPP_SEMICOLON: pedwarn (c_parser_peek_token (parser)->location, OPT_Wpedantic, "ISO C does not allow extra %<;%> outside of a function"); c_parser_consume_token (parser); break; case CPP_PRAGMA: mark_valid_location_for_stdc_pragma (true); c_parser_pragma (parser, pragma_external, NULL); mark_valid_location_for_stdc_pragma (false); break; case CPP_PLUS: case CPP_MINUS: if (c_dialect_objc ()) { c_parser_objc_method_definition (parser); break; } /* Else fall through, and yield a syntax error trying to parse as a declaration or function definition. */ /* FALLTHRU */ default: decl_or_fndef: /* A declaration or a function definition (or, in Objective-C, an @interface or @protocol with prefix attributes). We can only tell which after parsing the declaration specifiers, if any, and the first declarator. */ c_parser_declaration_or_fndef (parser, true, true, true, false, true, NULL, vNULL); break; } } static void c_finish_omp_declare_simd (c_parser *, tree, tree, vec<c_token>); static void c_finish_oacc_routine (struct oacc_routine_data *, tree, bool); /* Build and add a DEBUG_BEGIN_STMT statement with location LOC. */ static void add_debug_begin_stmt (location_t loc) { /* Don't add DEBUG_BEGIN_STMTs outside of functions, see PR84721. */ if (!MAY_HAVE_DEBUG_MARKER_STMTS || !building_stmt_list_p ()) return; tree stmt = build0 (DEBUG_BEGIN_STMT, void_type_node); SET_EXPR_LOCATION (stmt, loc); add_stmt (stmt); } /* Parse a declaration or function definition (C90 6.5, 6.7.1, C99 6.7, 6.9.1, C11 6.7, 6.9.1). If FNDEF_OK is true, a function definition is accepted; otherwise (old-style parameter declarations) only other declarations are accepted. If STATIC_ASSERT_OK is true, a static assertion is accepted; otherwise (old-style parameter declarations) it is not. If NESTED is true, we are inside a function or parsing old-style parameter declarations; any functions encountered are nested functions and declaration specifiers are required; otherwise we are at top level and functions are normal functions and declaration specifiers may be optional. If EMPTY_OK is true, empty declarations are OK (subject to all other constraints); otherwise (old-style parameter declarations) they are diagnosed. If START_ATTR_OK is true, the declaration specifiers may start with attributes; otherwise they may not. OBJC_FOREACH_OBJECT_DECLARATION can be used to get back the parsed declaration when parsing an Objective-C foreach statement. FALLTHRU_ATTR_P is used to signal whether this function parsed "__attribute__((fallthrough));". declaration: declaration-specifiers init-declarator-list[opt] ; static_assert-declaration function-definition: declaration-specifiers[opt] declarator declaration-list[opt] compound-statement declaration-list: declaration declaration-list declaration init-declarator-list: init-declarator init-declarator-list , init-declarator init-declarator: declarator simple-asm-expr[opt] attributes[opt] declarator simple-asm-expr[opt] attributes[opt] = initializer GNU extensions: nested-function-definition: declaration-specifiers declarator declaration-list[opt] compound-statement attribute ; Objective-C: attributes objc-class-definition attributes objc-category-definition attributes objc-protocol-definition The simple-asm-expr and attributes are GNU extensions. This function does not handle __extension__; that is handled in its callers. ??? Following the old parser, __extension__ may start external declarations, declarations in functions and declarations at the start of "for" loops, but not old-style parameter declarations. C99 requires declaration specifiers in a function definition; the absence is diagnosed through the diagnosis of implicit int. In GNU C we also allow but diagnose declarations without declaration specifiers, but only at top level (elsewhere they conflict with other syntax). In Objective-C, declarations of the looping variable in a foreach statement are exceptionally terminated by 'in' (for example, 'for (NSObject *object in array) { ... }'). OpenMP: declaration: threadprivate-directive GIMPLE: gimple-function-definition: declaration-specifiers[opt] __GIMPLE (gimple-or-rtl-pass-list) declarator declaration-list[opt] compound-statement rtl-function-definition: declaration-specifiers[opt] __RTL (gimple-or-rtl-pass-list) declarator declaration-list[opt] compound-statement */ static void c_parser_declaration_or_fndef (c_parser *parser, bool fndef_ok, bool static_assert_ok, bool empty_ok, bool nested, bool start_attr_ok, tree *objc_foreach_object_declaration, vec<c_token> omp_declare_simd_clauses, struct oacc_routine_data *oacc_routine_data, bool *fallthru_attr_p) { struct c_declspecs *specs; tree prefix_attrs; tree all_prefix_attrs; bool diagnosed_no_specs = false; location_t here = c_parser_peek_token (parser)->location; add_debug_begin_stmt (c_parser_peek_token (parser)->location); if (static_assert_ok && c_parser_next_token_is_keyword (parser, RID_STATIC_ASSERT)) { c_parser_static_assert_declaration (parser); return; } specs = build_null_declspecs (); /* Try to detect an unknown type name when we have "A B" or "A *B". */ if (c_parser_peek_token (parser)->type == CPP_NAME && c_parser_peek_token (parser)->id_kind == C_ID_ID && (c_parser_peek_2nd_token (parser)->type == CPP_NAME || c_parser_peek_2nd_token (parser)->type == CPP_MULT) && (!nested || !lookup_name (c_parser_peek_token (parser)->value))) { tree name = c_parser_peek_token (parser)->value; /* Issue a warning about NAME being an unknown type name, perhaps with some kind of hint. If the user forgot a "struct" etc, suggest inserting it. Otherwise, attempt to look for misspellings. */ gcc_rich_location richloc (here); if (tag_exists_p (RECORD_TYPE, name)) { /* This is not C++ with its implicit typedef. */ richloc.add_fixit_insert_before ("struct "); error_at (&richloc, "unknown type name %qE;" " use %<struct%> keyword to refer to the type", name); } else if (tag_exists_p (UNION_TYPE, name)) { richloc.add_fixit_insert_before ("union "); error_at (&richloc, "unknown type name %qE;" " use %<union%> keyword to refer to the type", name); } else if (tag_exists_p (ENUMERAL_TYPE, name)) { richloc.add_fixit_insert_before ("enum "); error_at (&richloc, "unknown type name %qE;" " use %<enum%> keyword to refer to the type", name); } else { name_hint hint = lookup_name_fuzzy (name, FUZZY_LOOKUP_TYPENAME, here); if (hint) { richloc.add_fixit_replace (hint.suggestion ()); error_at (&richloc, "unknown type name %qE; did you mean %qs?", name, hint.suggestion ()); } else error_at (here, "unknown type name %qE", name); } /* Parse declspecs normally to get a correct pointer type, but avoid a further "fails to be a type name" error. Refuse nested functions since it is not how the user likely wants us to recover. */ c_parser_peek_token (parser)->type = CPP_KEYWORD; c_parser_peek_token (parser)->keyword = RID_VOID; c_parser_peek_token (parser)->value = error_mark_node; fndef_ok = !nested; } c_parser_declspecs (parser, specs, true, true, start_attr_ok, true, true, cla_nonabstract_decl); if (parser->error) { c_parser_skip_to_end_of_block_or_statement (parser); return; } if (nested && !specs->declspecs_seen_p) { c_parser_error (parser, "expected declaration specifiers"); c_parser_skip_to_end_of_block_or_statement (parser); return; } finish_declspecs (specs); bool auto_type_p = specs->typespec_word == cts_auto_type; if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { if (auto_type_p) error_at (here, "%<__auto_type%> in empty declaration"); else if (specs->typespec_kind == ctsk_none && attribute_fallthrough_p (specs->attrs)) { if (fallthru_attr_p != NULL) *fallthru_attr_p = true; tree fn = build_call_expr_internal_loc (here, IFN_FALLTHROUGH, void_type_node, 0); add_stmt (fn); } else if (empty_ok) shadow_tag (specs); else { shadow_tag_warned (specs, 1); pedwarn (here, 0, "empty declaration"); } c_parser_consume_token (parser); if (oacc_routine_data) c_finish_oacc_routine (oacc_routine_data, NULL_TREE, false); return; } /* Provide better error recovery. Note that a type name here is usually better diagnosed as a redeclaration. */ if (empty_ok && specs->typespec_kind == ctsk_tagdef && c_parser_next_token_starts_declspecs (parser) && !c_parser_next_token_is (parser, CPP_NAME)) { c_parser_error (parser, "expected %<;%>, identifier or %<(%>"); parser->error = false; shadow_tag_warned (specs, 1); return; } else if (c_dialect_objc () && !auto_type_p) { /* Prefix attributes are an error on method decls. */ switch (c_parser_peek_token (parser)->type) { case CPP_PLUS: case CPP_MINUS: if (c_parser_objc_diagnose_bad_element_prefix (parser, specs)) return; if (specs->attrs) { warning_at (c_parser_peek_token (parser)->location, OPT_Wattributes, "prefix attributes are ignored for methods"); specs->attrs = NULL_TREE; } if (fndef_ok) c_parser_objc_method_definition (parser); else c_parser_objc_methodproto (parser); return; break; default: break; } /* This is where we parse 'attributes @interface ...', 'attributes @implementation ...', 'attributes @protocol ...' (where attributes could be, for example, __attribute__ ((deprecated)). */ switch (c_parser_peek_token (parser)->keyword) { case RID_AT_INTERFACE: { if (c_parser_objc_diagnose_bad_element_prefix (parser, specs)) return; c_parser_objc_class_definition (parser, specs->attrs); return; } break; case RID_AT_IMPLEMENTATION: { if (c_parser_objc_diagnose_bad_element_prefix (parser, specs)) return; if (specs->attrs) { warning_at (c_parser_peek_token (parser)->location, OPT_Wattributes, "prefix attributes are ignored for implementations"); specs->attrs = NULL_TREE; } c_parser_objc_class_definition (parser, NULL_TREE); return; } break; case RID_AT_PROTOCOL: { if (c_parser_objc_diagnose_bad_element_prefix (parser, specs)) return; c_parser_objc_protocol_definition (parser, specs->attrs); return; } break; case RID_AT_ALIAS: case RID_AT_CLASS: case RID_AT_END: case RID_AT_PROPERTY: if (specs->attrs) { c_parser_error (parser, "unexpected attribute"); specs->attrs = NULL; } break; default: break; } } else if (attribute_fallthrough_p (specs->attrs)) warning_at (here, OPT_Wattributes, "%<fallthrough%> attribute not followed by %<;%>"); pending_xref_error (); prefix_attrs = specs->attrs; all_prefix_attrs = prefix_attrs; specs->attrs = NULL_TREE; while (true) { struct c_declarator *declarator; bool dummy = false; timevar_id_t tv; tree fnbody = NULL_TREE; /* Declaring either one or more declarators (in which case we should diagnose if there were no declaration specifiers) or a function definition (in which case the diagnostic for implicit int suffices). */ declarator = c_parser_declarator (parser, specs->typespec_kind != ctsk_none, C_DTR_NORMAL, &dummy); if (declarator == NULL) { if (omp_declare_simd_clauses.exists ()) c_finish_omp_declare_simd (parser, NULL_TREE, NULL_TREE, omp_declare_simd_clauses); if (oacc_routine_data) c_finish_oacc_routine (oacc_routine_data, NULL_TREE, false); c_parser_skip_to_end_of_block_or_statement (parser); return; } if (auto_type_p && declarator->kind != cdk_id) { error_at (here, "%<__auto_type%> requires a plain identifier" " as declarator"); c_parser_skip_to_end_of_block_or_statement (parser); return; } if (c_parser_next_token_is (parser, CPP_EQ) || c_parser_next_token_is (parser, CPP_COMMA) || c_parser_next_token_is (parser, CPP_SEMICOLON) || c_parser_next_token_is_keyword (parser, RID_ASM) || c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE) || c_parser_next_token_is_keyword (parser, RID_IN)) { tree asm_name = NULL_TREE; tree postfix_attrs = NULL_TREE; if (!diagnosed_no_specs && !specs->declspecs_seen_p) { diagnosed_no_specs = true; pedwarn (here, 0, "data definition has no type or storage class"); } /* Having seen a data definition, there cannot now be a function definition. */ fndef_ok = false; if (c_parser_next_token_is_keyword (parser, RID_ASM)) asm_name = c_parser_simple_asm_expr (parser); if (c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) { postfix_attrs = c_parser_attributes (parser); if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) { /* This means there is an attribute specifier after the declarator in a function definition. Provide some more information for the user. */ error_at (here, "attributes should be specified before the " "declarator in a function definition"); c_parser_skip_to_end_of_block_or_statement (parser); return; } } if (c_parser_next_token_is (parser, CPP_EQ)) { tree d; struct c_expr init; location_t init_loc; c_parser_consume_token (parser); if (auto_type_p) { init_loc = c_parser_peek_token (parser)->location; rich_location richloc (line_table, init_loc); start_init (NULL_TREE, asm_name, global_bindings_p (), &richloc); /* A parameter is initialized, which is invalid. Don't attempt to instrument the initializer. */ int flag_sanitize_save = flag_sanitize; if (nested && !empty_ok) flag_sanitize = 0; init = c_parser_expr_no_commas (parser, NULL); flag_sanitize = flag_sanitize_save; if (TREE_CODE (init.value) == COMPONENT_REF && DECL_C_BIT_FIELD (TREE_OPERAND (init.value, 1))) error_at (here, "%<__auto_type%> used with a bit-field" " initializer"); init = convert_lvalue_to_rvalue (init_loc, init, true, true); tree init_type = TREE_TYPE (init.value); /* As with typeof, remove all qualifiers from atomic types. */ if (init_type != error_mark_node && TYPE_ATOMIC (init_type)) init_type = c_build_qualified_type (init_type, TYPE_UNQUALIFIED); bool vm_type = variably_modified_type_p (init_type, NULL_TREE); if (vm_type) init.value = save_expr (init.value); finish_init (); specs->typespec_kind = ctsk_typeof; specs->locations[cdw_typedef] = init_loc; specs->typedef_p = true; specs->type = init_type; if (vm_type) { bool maybe_const = true; tree type_expr = c_fully_fold (init.value, false, &maybe_const); specs->expr_const_operands &= maybe_const; if (specs->expr) specs->expr = build2 (COMPOUND_EXPR, TREE_TYPE (type_expr), specs->expr, type_expr); else specs->expr = type_expr; } d = start_decl (declarator, specs, true, chainon (postfix_attrs, all_prefix_attrs)); if (!d) d = error_mark_node; if (omp_declare_simd_clauses.exists ()) c_finish_omp_declare_simd (parser, d, NULL_TREE, omp_declare_simd_clauses); } else { /* The declaration of the variable is in effect while its initializer is parsed. */ d = start_decl (declarator, specs, true, chainon (postfix_attrs, all_prefix_attrs)); if (!d) d = error_mark_node; if (omp_declare_simd_clauses.exists ()) c_finish_omp_declare_simd (parser, d, NULL_TREE, omp_declare_simd_clauses); init_loc = c_parser_peek_token (parser)->location; rich_location richloc (line_table, init_loc); start_init (d, asm_name, global_bindings_p (), &richloc); /* A parameter is initialized, which is invalid. Don't attempt to instrument the initializer. */ int flag_sanitize_save = flag_sanitize; if (TREE_CODE (d) == PARM_DECL) flag_sanitize = 0; init = c_parser_initializer (parser); flag_sanitize = flag_sanitize_save; finish_init (); } if (oacc_routine_data) c_finish_oacc_routine (oacc_routine_data, d, false); if (d != error_mark_node) { maybe_warn_string_init (init_loc, TREE_TYPE (d), init); finish_decl (d, init_loc, init.value, init.original_type, asm_name); } } else { if (auto_type_p) { error_at (here, "%<__auto_type%> requires an initialized " "data declaration"); c_parser_skip_to_end_of_block_or_statement (parser); return; } tree d = start_decl (declarator, specs, false, chainon (postfix_attrs, all_prefix_attrs)); if (d && TREE_CODE (d) == FUNCTION_DECL && declarator->kind == cdk_function && DECL_ARGUMENTS (d) == NULL_TREE && DECL_INITIAL (d) == NULL_TREE) DECL_ARGUMENTS (d) = declarator->u.arg_info->parms; if (omp_declare_simd_clauses.exists ()) { tree parms = NULL_TREE; if (d && TREE_CODE (d) == FUNCTION_DECL) { struct c_declarator *ce = declarator; while (ce != NULL) if (ce->kind == cdk_function) { parms = ce->u.arg_info->parms; break; } else ce = ce->declarator; } if (parms) temp_store_parm_decls (d, parms); c_finish_omp_declare_simd (parser, d, parms, omp_declare_simd_clauses); if (parms) temp_pop_parm_decls (); } if (oacc_routine_data) c_finish_oacc_routine (oacc_routine_data, d, false); if (d) finish_decl (d, UNKNOWN_LOCATION, NULL_TREE, NULL_TREE, asm_name); if (c_parser_next_token_is_keyword (parser, RID_IN)) { if (d) *objc_foreach_object_declaration = d; else *objc_foreach_object_declaration = error_mark_node; } } if (c_parser_next_token_is (parser, CPP_COMMA)) { if (auto_type_p) { error_at (here, "%<__auto_type%> may only be used with" " a single declarator"); c_parser_skip_to_end_of_block_or_statement (parser); return; } c_parser_consume_token (parser); if (c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) all_prefix_attrs = chainon (c_parser_attributes (parser), prefix_attrs); else all_prefix_attrs = prefix_attrs; continue; } else if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { c_parser_consume_token (parser); return; } else if (c_parser_next_token_is_keyword (parser, RID_IN)) { /* This can only happen in Objective-C: we found the 'in' that terminates the declaration inside an Objective-C foreach statement. Do not consume the token, so that the caller can use it to determine that this indeed is a foreach context. */ return; } else { c_parser_error (parser, "expected %<,%> or %<;%>"); c_parser_skip_to_end_of_block_or_statement (parser); return; } } else if (auto_type_p) { error_at (here, "%<__auto_type%> requires an initialized data declaration"); c_parser_skip_to_end_of_block_or_statement (parser); return; } else if (!fndef_ok) { c_parser_error (parser, "expected %<=%>, %<,%>, %<;%>, " "%<asm%> or %<__attribute__%>"); c_parser_skip_to_end_of_block_or_statement (parser); return; } /* Function definition (nested or otherwise). */ if (nested) { pedwarn (here, OPT_Wpedantic, "ISO C forbids nested functions"); c_push_function_context (); } if (!start_function (specs, declarator, all_prefix_attrs)) { /* At this point we've consumed: declaration-specifiers declarator and the next token isn't CPP_EQ, CPP_COMMA, CPP_SEMICOLON, RID_ASM, RID_ATTRIBUTE, or RID_IN, but the declaration-specifiers declarator aren't grokkable as a function definition, so we have an error. */ gcc_assert (!c_parser_next_token_is (parser, CPP_SEMICOLON)); if (c_parser_next_token_starts_declspecs (parser)) { /* If we have declaration-specifiers declarator decl-specs then assume we have a missing semicolon, which would give us: declaration-specifiers declarator decl-specs ^ ; <~~~~~~~~~ declaration ~~~~~~~~~~> Use c_parser_require to get an error with a fix-it hint. */ c_parser_require (parser, CPP_SEMICOLON, "expected %<;%>"); parser->error = false; } else { /* This can appear in many cases looking nothing like a function definition, so we don't give a more specific error suggesting there was one. */ c_parser_error (parser, "expected %<=%>, %<,%>, %<;%>, %<asm%> " "or %<__attribute__%>"); } if (nested) c_pop_function_context (); break; } if (DECL_DECLARED_INLINE_P (current_function_decl)) tv = TV_PARSE_INLINE; else tv = TV_PARSE_FUNC; auto_timevar at (g_timer, tv); /* Parse old-style parameter declarations. ??? Attributes are not allowed to start declaration specifiers here because of a syntax conflict between a function declaration with attribute suffix and a function definition with an attribute prefix on first old-style parameter declaration. Following the old parser, they are not accepted on subsequent old-style parameter declarations either. However, there is no ambiguity after the first declaration, nor indeed on the first as long as we don't allow postfix attributes after a declarator with a nonempty identifier list in a definition; and postfix attributes have never been accepted here in function definitions either. */ while (c_parser_next_token_is_not (parser, CPP_EOF) && c_parser_next_token_is_not (parser, CPP_OPEN_BRACE)) c_parser_declaration_or_fndef (parser, false, false, false, true, false, NULL, vNULL); store_parm_decls (); if (omp_declare_simd_clauses.exists ()) c_finish_omp_declare_simd (parser, current_function_decl, NULL_TREE, omp_declare_simd_clauses); if (oacc_routine_data) c_finish_oacc_routine (oacc_routine_data, current_function_decl, true); DECL_STRUCT_FUNCTION (current_function_decl)->function_start_locus = c_parser_peek_token (parser)->location; /* If the definition was marked with __GIMPLE then parse the function body as GIMPLE. */ if (specs->gimple_p) { cfun->pass_startwith = specs->gimple_or_rtl_pass; bool saved = in_late_binary_op; in_late_binary_op = true; c_parser_parse_gimple_body (parser); in_late_binary_op = saved; } /* Similarly, if it was marked with __RTL, use the RTL parser now, consuming the function body. */ else if (specs->rtl_p) { c_parser_parse_rtl_body (parser, specs->gimple_or_rtl_pass); /* Normally, store_parm_decls sets next_is_function_body, anticipating a function body. We need a push_scope/pop_scope pair to flush out this state, or subsequent function parsing will go wrong. */ push_scope (); pop_scope (); finish_function (); return; } else fnbody = c_parser_compound_statement (parser); tree fndecl = current_function_decl; if (nested) { tree decl = current_function_decl; /* Mark nested functions as needing static-chain initially. lower_nested_functions will recompute it but the DECL_STATIC_CHAIN flag is also used before that happens, by initializer_constant_valid_p. See gcc.dg/nested-fn-2.c. */ DECL_STATIC_CHAIN (decl) = 1; add_stmt (fnbody); finish_function (); c_pop_function_context (); add_stmt (build_stmt (DECL_SOURCE_LOCATION (decl), DECL_EXPR, decl)); } else { if (fnbody) add_stmt (fnbody); finish_function (); } /* Get rid of the empty stmt list for GIMPLE. */ if (specs->gimple_p) DECL_SAVED_TREE (fndecl) = NULL_TREE; break; } } /* Parse an asm-definition (asm() outside a function body). This is a GNU extension. asm-definition: simple-asm-expr ; */ static void c_parser_asm_definition (c_parser *parser) { tree asm_str = c_parser_simple_asm_expr (parser); if (asm_str) symtab->finalize_toplevel_asm (asm_str); c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } /* Parse a static assertion (C11 6.7.10). static_assert-declaration: static_assert-declaration-no-semi ; */ static void c_parser_static_assert_declaration (c_parser *parser) { c_parser_static_assert_declaration_no_semi (parser); if (parser->error || !c_parser_require (parser, CPP_SEMICOLON, "expected %<;%>")) c_parser_skip_to_end_of_block_or_statement (parser); } /* Parse a static assertion (C11 6.7.10), without the trailing semicolon. static_assert-declaration-no-semi: _Static_assert ( constant-expression , string-literal ) */ static void c_parser_static_assert_declaration_no_semi (c_parser *parser) { location_t assert_loc, value_loc; tree value; tree string; gcc_assert (c_parser_next_token_is_keyword (parser, RID_STATIC_ASSERT)); assert_loc = c_parser_peek_token (parser)->location; if (flag_isoc99) pedwarn_c99 (assert_loc, OPT_Wpedantic, "ISO C99 does not support %<_Static_assert%>"); else pedwarn_c99 (assert_loc, OPT_Wpedantic, "ISO C90 does not support %<_Static_assert%>"); c_parser_consume_token (parser); matching_parens parens; if (!parens.require_open (parser)) return; location_t value_tok_loc = c_parser_peek_token (parser)->location; value = c_parser_expr_no_commas (parser, NULL).value; value_loc = EXPR_LOC_OR_LOC (value, value_tok_loc); parser->lex_untranslated_string = true; if (!c_parser_require (parser, CPP_COMMA, "expected %<,%>")) { parser->lex_untranslated_string = false; return; } switch (c_parser_peek_token (parser)->type) { case CPP_STRING: case CPP_STRING16: case CPP_STRING32: case CPP_WSTRING: case CPP_UTF8STRING: string = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); parser->lex_untranslated_string = false; break; default: c_parser_error (parser, "expected string literal"); parser->lex_untranslated_string = false; return; } parens.require_close (parser); if (!INTEGRAL_TYPE_P (TREE_TYPE (value))) { error_at (value_loc, "expression in static assertion is not an integer"); return; } if (TREE_CODE (value) != INTEGER_CST) { value = c_fully_fold (value, false, NULL); /* Strip no-op conversions. */ STRIP_TYPE_NOPS (value); if (TREE_CODE (value) == INTEGER_CST) pedwarn (value_loc, OPT_Wpedantic, "expression in static assertion " "is not an integer constant expression"); } if (TREE_CODE (value) != INTEGER_CST) { error_at (value_loc, "expression in static assertion is not constant"); return; } constant_expression_warning (value); if (integer_zerop (value)) error_at (assert_loc, "static assertion failed: %E", string); } /* Parse some declaration specifiers (possibly none) (C90 6.5, C99 6.7, C11 6.7), adding them to SPECS (which may already include some). Storage class specifiers are accepted iff SCSPEC_OK; type specifiers are accepted iff TYPESPEC_OK; alignment specifiers are accepted iff ALIGNSPEC_OK; attributes are accepted at the start iff START_ATTR_OK; __auto_type is accepted iff AUTO_TYPE_OK. declaration-specifiers: storage-class-specifier declaration-specifiers[opt] type-specifier declaration-specifiers[opt] type-qualifier declaration-specifiers[opt] function-specifier declaration-specifiers[opt] alignment-specifier declaration-specifiers[opt] Function specifiers (inline) are from C99, and are currently handled as storage class specifiers, as is __thread. Alignment specifiers are from C11. C90 6.5.1, C99 6.7.1, C11 6.7.1: storage-class-specifier: typedef extern static auto register _Thread_local (_Thread_local is new in C11.) C99 6.7.4, C11 6.7.4: function-specifier: inline _Noreturn (_Noreturn is new in C11.) C90 6.5.2, C99 6.7.2, C11 6.7.2: type-specifier: void char short int long float double signed unsigned _Bool _Complex [_Imaginary removed in C99 TC2] struct-or-union-specifier enum-specifier typedef-name atomic-type-specifier (_Bool and _Complex are new in C99.) (atomic-type-specifier is new in C11.) C90 6.5.3, C99 6.7.3, C11 6.7.3: type-qualifier: const restrict volatile address-space-qualifier _Atomic (restrict is new in C99.) (_Atomic is new in C11.) GNU extensions: declaration-specifiers: attributes declaration-specifiers[opt] type-qualifier: address-space address-space: identifier recognized by the target storage-class-specifier: __thread type-specifier: typeof-specifier __auto_type __intN _Decimal32 _Decimal64 _Decimal128 _Fract _Accum _Sat (_Fract, _Accum, and _Sat are new from ISO/IEC DTR 18037: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1169.pdf) atomic-type-specifier _Atomic ( type-name ) Objective-C: type-specifier: class-name objc-protocol-refs[opt] typedef-name objc-protocol-refs objc-protocol-refs */ void c_parser_declspecs (c_parser *parser, struct c_declspecs *specs, bool scspec_ok, bool typespec_ok, bool start_attr_ok, bool alignspec_ok, bool auto_type_ok, enum c_lookahead_kind la) { bool attrs_ok = start_attr_ok; bool seen_type = specs->typespec_kind != ctsk_none; if (!typespec_ok) gcc_assert (la == cla_prefer_id); while (c_parser_next_token_is (parser, CPP_NAME) || c_parser_next_token_is (parser, CPP_KEYWORD) || (c_dialect_objc () && c_parser_next_token_is (parser, CPP_LESS))) { struct c_typespec t; tree attrs; tree align; location_t loc = c_parser_peek_token (parser)->location; /* If we cannot accept a type, exit if the next token must start one. Also, if we already have seen a tagged definition, a typename would be an error anyway and likely the user has simply forgotten a semicolon, so we exit. */ if ((!typespec_ok || specs->typespec_kind == ctsk_tagdef) && c_parser_next_tokens_start_typename (parser, la) && !c_parser_next_token_is_qualifier (parser) && !c_parser_next_token_is_keyword (parser, RID_ALIGNAS)) break; if (c_parser_next_token_is (parser, CPP_NAME)) { c_token *name_token = c_parser_peek_token (parser); tree value = name_token->value; c_id_kind kind = name_token->id_kind; if (kind == C_ID_ADDRSPACE) { addr_space_t as = name_token->keyword - RID_FIRST_ADDR_SPACE; declspecs_add_addrspace (name_token->location, specs, as); c_parser_consume_token (parser); attrs_ok = true; continue; } gcc_assert (!c_parser_next_token_is_qualifier (parser)); /* If we cannot accept a type, and the next token must start one, exit. Do the same if we already have seen a tagged definition, since it would be an error anyway and likely the user has simply forgotten a semicolon. */ if (seen_type || !c_parser_next_tokens_start_typename (parser, la)) break; /* Now at an unknown typename (C_ID_ID), a C_ID_TYPENAME or a C_ID_CLASSNAME. */ c_parser_consume_token (parser); seen_type = true; attrs_ok = true; if (kind == C_ID_ID) { error_at (loc, "unknown type name %qE", value); t.kind = ctsk_typedef; t.spec = error_mark_node; } else if (kind == C_ID_TYPENAME && (!c_dialect_objc () || c_parser_next_token_is_not (parser, CPP_LESS))) { t.kind = ctsk_typedef; /* For a typedef name, record the meaning, not the name. In case of 'foo foo, bar;'. */ t.spec = lookup_name (value); } else { tree proto = NULL_TREE; gcc_assert (c_dialect_objc ()); t.kind = ctsk_objc; if (c_parser_next_token_is (parser, CPP_LESS)) proto = c_parser_objc_protocol_refs (parser); t.spec = objc_get_protocol_qualified_type (value, proto); } t.expr = NULL_TREE; t.expr_const_operands = true; declspecs_add_type (name_token->location, specs, t); continue; } if (c_parser_next_token_is (parser, CPP_LESS)) { /* Make "<SomeProtocol>" equivalent to "id <SomeProtocol>" - nisse@lysator.liu.se. */ tree proto; gcc_assert (c_dialect_objc ()); if (!typespec_ok || seen_type) break; proto = c_parser_objc_protocol_refs (parser); t.kind = ctsk_objc; t.spec = objc_get_protocol_qualified_type (NULL_TREE, proto); t.expr = NULL_TREE; t.expr_const_operands = true; declspecs_add_type (loc, specs, t); continue; } gcc_assert (c_parser_next_token_is (parser, CPP_KEYWORD)); switch (c_parser_peek_token (parser)->keyword) { case RID_STATIC: case RID_EXTERN: case RID_REGISTER: case RID_TYPEDEF: case RID_INLINE: case RID_NORETURN: case RID_AUTO: case RID_THREAD: if (!scspec_ok) goto out; attrs_ok = true; /* TODO: Distinguish between function specifiers (inline, noreturn) and storage class specifiers, either here or in declspecs_add_scspec. */ declspecs_add_scspec (loc, specs, c_parser_peek_token (parser)->value); c_parser_consume_token (parser); break; case RID_AUTO_TYPE: if (!auto_type_ok) goto out; /* Fall through. */ case RID_UNSIGNED: case RID_LONG: case RID_SHORT: case RID_SIGNED: case RID_COMPLEX: case RID_INT: case RID_CHAR: case RID_FLOAT: case RID_DOUBLE: case RID_VOID: case RID_DFLOAT32: case RID_DFLOAT64: case RID_DFLOAT128: CASE_RID_FLOATN_NX: case RID_BOOL: case RID_FRACT: case RID_ACCUM: case RID_SAT: case RID_INT_N_0: case RID_INT_N_1: case RID_INT_N_2: case RID_INT_N_3: if (!typespec_ok) goto out; attrs_ok = true; seen_type = true; if (c_dialect_objc ()) parser->objc_need_raw_identifier = true; t.kind = ctsk_resword; t.spec = c_parser_peek_token (parser)->value; t.expr = NULL_TREE; t.expr_const_operands = true; declspecs_add_type (loc, specs, t); c_parser_consume_token (parser); break; case RID_ENUM: if (!typespec_ok) goto out; attrs_ok = true; seen_type = true; t = c_parser_enum_specifier (parser); invoke_plugin_callbacks (PLUGIN_FINISH_TYPE, t.spec); declspecs_add_type (loc, specs, t); break; case RID_STRUCT: case RID_UNION: if (!typespec_ok) goto out; attrs_ok = true; seen_type = true; t = c_parser_struct_or_union_specifier (parser); invoke_plugin_callbacks (PLUGIN_FINISH_TYPE, t.spec); declspecs_add_type (loc, specs, t); break; case RID_TYPEOF: /* ??? The old parser rejected typeof after other type specifiers, but is a syntax error the best way of handling this? */ if (!typespec_ok || seen_type) goto out; attrs_ok = true; seen_type = true; t = c_parser_typeof_specifier (parser); declspecs_add_type (loc, specs, t); break; case RID_ATOMIC: /* C parser handling of Objective-C constructs needs checking for correct lvalue-to-rvalue conversions, and the code in build_modify_expr handling various Objective-C cases, and that in build_unary_op handling Objective-C cases for increment / decrement, also needs updating; uses of TYPE_MAIN_VARIANT in objc_compare_types and objc_types_are_equivalent may also need updates. */ if (c_dialect_objc ()) sorry ("%<_Atomic%> in Objective-C"); if (flag_isoc99) pedwarn_c99 (loc, OPT_Wpedantic, "ISO C99 does not support the %<_Atomic%> qualifier"); else pedwarn_c99 (loc, OPT_Wpedantic, "ISO C90 does not support the %<_Atomic%> qualifier"); attrs_ok = true; tree value; value = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); if (typespec_ok && c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { /* _Atomic ( type-name ). */ seen_type = true; c_parser_consume_token (parser); struct c_type_name *type = c_parser_type_name (parser); t.kind = ctsk_typeof; t.spec = error_mark_node; t.expr = NULL_TREE; t.expr_const_operands = true; if (type != NULL) t.spec = groktypename (type, &t.expr, &t.expr_const_operands); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); if (t.spec != error_mark_node) { if (TREE_CODE (t.spec) == ARRAY_TYPE) error_at (loc, "%<_Atomic%>-qualified array type"); else if (TREE_CODE (t.spec) == FUNCTION_TYPE) error_at (loc, "%<_Atomic%>-qualified function type"); else if (TYPE_QUALS (t.spec) != TYPE_UNQUALIFIED) error_at (loc, "%<_Atomic%> applied to a qualified type"); else t.spec = c_build_qualified_type (t.spec, TYPE_QUAL_ATOMIC); } declspecs_add_type (loc, specs, t); } else declspecs_add_qual (loc, specs, value); break; case RID_CONST: case RID_VOLATILE: case RID_RESTRICT: attrs_ok = true; declspecs_add_qual (loc, specs, c_parser_peek_token (parser)->value); c_parser_consume_token (parser); break; case RID_ATTRIBUTE: if (!attrs_ok) goto out; attrs = c_parser_attributes (parser); declspecs_add_attrs (loc, specs, attrs); break; case RID_ALIGNAS: if (!alignspec_ok) goto out; align = c_parser_alignas_specifier (parser); declspecs_add_alignas (loc, specs, align); break; case RID_GIMPLE: if (! flag_gimple) error_at (loc, "%<__GIMPLE%> only valid with -fgimple"); c_parser_consume_token (parser); specs->gimple_p = true; specs->locations[cdw_gimple] = loc; specs->gimple_or_rtl_pass = c_parser_gimple_or_rtl_pass_list (parser); break; case RID_RTL: c_parser_consume_token (parser); specs->rtl_p = true; specs->locations[cdw_rtl] = loc; specs->gimple_or_rtl_pass = c_parser_gimple_or_rtl_pass_list (parser); break; default: goto out; } } out: ; } /* Parse an enum specifier (C90 6.5.2.2, C99 6.7.2.2, C11 6.7.2.2). enum-specifier: enum attributes[opt] identifier[opt] { enumerator-list } attributes[opt] enum attributes[opt] identifier[opt] { enumerator-list , } attributes[opt] enum attributes[opt] identifier The form with trailing comma is new in C99. The forms with attributes are GNU extensions. In GNU C, we accept any expression without commas in the syntax (assignment expressions, not just conditional expressions); assignment expressions will be diagnosed as non-constant. enumerator-list: enumerator enumerator-list , enumerator enumerator: enumeration-constant enumeration-constant = constant-expression GNU Extensions: enumerator: enumeration-constant attributes[opt] enumeration-constant attributes[opt] = constant-expression */ static struct c_typespec c_parser_enum_specifier (c_parser *parser) { struct c_typespec ret; tree attrs; tree ident = NULL_TREE; location_t enum_loc; location_t ident_loc = UNKNOWN_LOCATION; /* Quiet warning. */ gcc_assert (c_parser_next_token_is_keyword (parser, RID_ENUM)); c_parser_consume_token (parser); attrs = c_parser_attributes (parser); enum_loc = c_parser_peek_token (parser)->location; /* Set the location in case we create a decl now. */ c_parser_set_source_position_from_token (c_parser_peek_token (parser)); if (c_parser_next_token_is (parser, CPP_NAME)) { ident = c_parser_peek_token (parser)->value; ident_loc = c_parser_peek_token (parser)->location; enum_loc = ident_loc; c_parser_consume_token (parser); } if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) { /* Parse an enum definition. */ struct c_enum_contents the_enum; tree type; tree postfix_attrs; /* We chain the enumerators in reverse order, then put them in forward order at the end. */ tree values; timevar_push (TV_PARSE_ENUM); type = start_enum (enum_loc, &the_enum, ident); values = NULL_TREE; c_parser_consume_token (parser); while (true) { tree enum_id; tree enum_value; tree enum_decl; bool seen_comma; c_token *token; location_t comma_loc = UNKNOWN_LOCATION; /* Quiet warning. */ location_t decl_loc, value_loc; if (c_parser_next_token_is_not (parser, CPP_NAME)) { /* Give a nicer error for "enum {}". */ if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE) && !parser->error) { error_at (c_parser_peek_token (parser)->location, "empty enum is invalid"); parser->error = true; } else c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_CLOSE_BRACE, NULL); values = error_mark_node; break; } token = c_parser_peek_token (parser); enum_id = token->value; /* Set the location in case we create a decl now. */ c_parser_set_source_position_from_token (token); decl_loc = value_loc = token->location; c_parser_consume_token (parser); /* Parse any specified attributes. */ tree enum_attrs = c_parser_attributes (parser); if (c_parser_next_token_is (parser, CPP_EQ)) { c_parser_consume_token (parser); value_loc = c_parser_peek_token (parser)->location; enum_value = c_parser_expr_no_commas (parser, NULL).value; } else enum_value = NULL_TREE; enum_decl = build_enumerator (decl_loc, value_loc, &the_enum, enum_id, enum_value); if (enum_attrs) decl_attributes (&TREE_PURPOSE (enum_decl), enum_attrs, 0); TREE_CHAIN (enum_decl) = values; values = enum_decl; seen_comma = false; if (c_parser_next_token_is (parser, CPP_COMMA)) { comma_loc = c_parser_peek_token (parser)->location; seen_comma = true; c_parser_consume_token (parser); } if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { if (seen_comma) pedwarn_c90 (comma_loc, OPT_Wpedantic, "comma at end of enumerator list"); c_parser_consume_token (parser); break; } if (!seen_comma) { c_parser_error (parser, "expected %<,%> or %<}%>"); c_parser_skip_until_found (parser, CPP_CLOSE_BRACE, NULL); values = error_mark_node; break; } } postfix_attrs = c_parser_attributes (parser); ret.spec = finish_enum (type, nreverse (values), chainon (attrs, postfix_attrs)); ret.kind = ctsk_tagdef; ret.expr = NULL_TREE; ret.expr_const_operands = true; timevar_pop (TV_PARSE_ENUM); return ret; } else if (!ident) { c_parser_error (parser, "expected %<{%>"); ret.spec = error_mark_node; ret.kind = ctsk_tagref; ret.expr = NULL_TREE; ret.expr_const_operands = true; return ret; } ret = parser_xref_tag (ident_loc, ENUMERAL_TYPE, ident); /* In ISO C, enumerated types can be referred to only if already defined. */ if (pedantic && !COMPLETE_TYPE_P (ret.spec)) { gcc_assert (ident); pedwarn (enum_loc, OPT_Wpedantic, "ISO C forbids forward references to %<enum%> types"); } return ret; } /* Parse a struct or union specifier (C90 6.5.2.1, C99 6.7.2.1, C11 6.7.2.1). struct-or-union-specifier: struct-or-union attributes[opt] identifier[opt] { struct-contents } attributes[opt] struct-or-union attributes[opt] identifier struct-contents: struct-declaration-list struct-declaration-list: struct-declaration ; struct-declaration-list struct-declaration ; GNU extensions: struct-contents: empty struct-declaration struct-declaration-list struct-declaration struct-declaration-list: struct-declaration-list ; ; (Note that in the syntax here, unlike that in ISO C, the semicolons are included here rather than in struct-declaration, in order to describe the syntax with extra semicolons and missing semicolon at end.) Objective-C: struct-declaration-list: @defs ( class-name ) (Note this does not include a trailing semicolon, but can be followed by further declarations, and gets a pedwarn-if-pedantic when followed by a semicolon.) */ static struct c_typespec c_parser_struct_or_union_specifier (c_parser *parser) { struct c_typespec ret; tree attrs; tree ident = NULL_TREE; location_t struct_loc; location_t ident_loc = UNKNOWN_LOCATION; enum tree_code code; switch (c_parser_peek_token (parser)->keyword) { case RID_STRUCT: code = RECORD_TYPE; break; case RID_UNION: code = UNION_TYPE; break; default: gcc_unreachable (); } struct_loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); attrs = c_parser_attributes (parser); /* Set the location in case we create a decl now. */ c_parser_set_source_position_from_token (c_parser_peek_token (parser)); if (c_parser_next_token_is (parser, CPP_NAME)) { ident = c_parser_peek_token (parser)->value; ident_loc = c_parser_peek_token (parser)->location; struct_loc = ident_loc; c_parser_consume_token (parser); } if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) { /* Parse a struct or union definition. Start the scope of the tag before parsing components. */ struct c_struct_parse_info *struct_info; tree type = start_struct (struct_loc, code, ident, &struct_info); tree postfix_attrs; /* We chain the components in reverse order, then put them in forward order at the end. Each struct-declaration may declare multiple components (comma-separated), so we must use chainon to join them, although when parsing each struct-declaration we can use TREE_CHAIN directly. The theory behind all this is that there will be more semicolon separated fields than comma separated fields, and so we'll be minimizing the number of node traversals required by chainon. */ tree contents; timevar_push (TV_PARSE_STRUCT); contents = NULL_TREE; c_parser_consume_token (parser); /* Handle the Objective-C @defs construct, e.g. foo(sizeof(struct{ @defs(ClassName) }));. */ if (c_parser_next_token_is_keyword (parser, RID_AT_DEFS)) { tree name; gcc_assert (c_dialect_objc ()); c_parser_consume_token (parser); matching_parens parens; if (!parens.require_open (parser)) goto end_at_defs; if (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_token (parser)->id_kind == C_ID_CLASSNAME) { name = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); } else { c_parser_error (parser, "expected class name"); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); goto end_at_defs; } parens.skip_until_found_close (parser); contents = nreverse (objc_get_class_ivars (name)); } end_at_defs: /* Parse the struct-declarations and semicolons. Problems with semicolons are diagnosed here; empty structures are diagnosed elsewhere. */ while (true) { tree decls; /* Parse any stray semicolon. */ if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { location_t semicolon_loc = c_parser_peek_token (parser)->location; gcc_rich_location richloc (semicolon_loc); richloc.add_fixit_remove (); pedwarn (&richloc, OPT_Wpedantic, "extra semicolon in struct or union specified"); c_parser_consume_token (parser); continue; } /* Stop if at the end of the struct or union contents. */ if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { c_parser_consume_token (parser); break; } /* Accept #pragmas at struct scope. */ if (c_parser_next_token_is (parser, CPP_PRAGMA)) { c_parser_pragma (parser, pragma_struct, NULL); continue; } /* Parse some comma-separated declarations, but not the trailing semicolon if any. */ decls = c_parser_struct_declaration (parser); contents = chainon (decls, contents); /* If no semicolon follows, either we have a parse error or are at the end of the struct or union and should pedwarn. */ if (c_parser_next_token_is (parser, CPP_SEMICOLON)) c_parser_consume_token (parser); else { if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) pedwarn (c_parser_peek_token (parser)->location, 0, "no semicolon at end of struct or union"); else if (parser->error || !c_parser_next_token_starts_declspecs (parser)) { c_parser_error (parser, "expected %<;%>"); c_parser_skip_until_found (parser, CPP_CLOSE_BRACE, NULL); break; } /* If we come here, we have already emitted an error for an expected `;', identifier or `(', and we also recovered already. Go on with the next field. */ } } postfix_attrs = c_parser_attributes (parser); ret.spec = finish_struct (struct_loc, type, nreverse (contents), chainon (attrs, postfix_attrs), struct_info); ret.kind = ctsk_tagdef; ret.expr = NULL_TREE; ret.expr_const_operands = true; timevar_pop (TV_PARSE_STRUCT); return ret; } else if (!ident) { c_parser_error (parser, "expected %<{%>"); ret.spec = error_mark_node; ret.kind = ctsk_tagref; ret.expr = NULL_TREE; ret.expr_const_operands = true; return ret; } ret = parser_xref_tag (ident_loc, code, ident); return ret; } /* Parse a struct-declaration (C90 6.5.2.1, C99 6.7.2.1, C11 6.7.2.1), *without* the trailing semicolon. struct-declaration: specifier-qualifier-list struct-declarator-list static_assert-declaration-no-semi specifier-qualifier-list: type-specifier specifier-qualifier-list[opt] type-qualifier specifier-qualifier-list[opt] alignment-specifier specifier-qualifier-list[opt] attributes specifier-qualifier-list[opt] struct-declarator-list: struct-declarator struct-declarator-list , attributes[opt] struct-declarator struct-declarator: declarator attributes[opt] declarator[opt] : constant-expression attributes[opt] GNU extensions: struct-declaration: __extension__ struct-declaration specifier-qualifier-list Unlike the ISO C syntax, semicolons are handled elsewhere. The use of attributes where shown is a GNU extension. In GNU C, we accept any expression without commas in the syntax (assignment expressions, not just conditional expressions); assignment expressions will be diagnosed as non-constant. */ static tree c_parser_struct_declaration (c_parser *parser) { struct c_declspecs *specs; tree prefix_attrs; tree all_prefix_attrs; tree decls; location_t decl_loc; if (c_parser_next_token_is_keyword (parser, RID_EXTENSION)) { int ext; tree decl; ext = disable_extension_diagnostics (); c_parser_consume_token (parser); decl = c_parser_struct_declaration (parser); restore_extension_diagnostics (ext); return decl; } if (c_parser_next_token_is_keyword (parser, RID_STATIC_ASSERT)) { c_parser_static_assert_declaration_no_semi (parser); return NULL_TREE; } specs = build_null_declspecs (); decl_loc = c_parser_peek_token (parser)->location; /* Strictly by the standard, we shouldn't allow _Alignas here, but it appears to have been intended to allow it there, so we're keeping it as it is until WG14 reaches a conclusion of N1731. <http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1731.pdf> */ c_parser_declspecs (parser, specs, false, true, true, true, false, cla_nonabstract_decl); if (parser->error) return NULL_TREE; if (!specs->declspecs_seen_p) { c_parser_error (parser, "expected specifier-qualifier-list"); return NULL_TREE; } finish_declspecs (specs); if (c_parser_next_token_is (parser, CPP_SEMICOLON) || c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { tree ret; if (specs->typespec_kind == ctsk_none) { pedwarn (decl_loc, OPT_Wpedantic, "ISO C forbids member declarations with no members"); shadow_tag_warned (specs, pedantic); ret = NULL_TREE; } else { /* Support for unnamed structs or unions as members of structs or unions (which is [a] useful and [b] supports MS P-SDK). */ tree attrs = NULL; ret = grokfield (c_parser_peek_token (parser)->location, build_id_declarator (NULL_TREE), specs, NULL_TREE, &attrs); if (ret) decl_attributes (&ret, attrs, 0); } return ret; } /* Provide better error recovery. Note that a type name here is valid, and will be treated as a field name. */ if (specs->typespec_kind == ctsk_tagdef && TREE_CODE (specs->type) != ENUMERAL_TYPE && c_parser_next_token_starts_declspecs (parser) && !c_parser_next_token_is (parser, CPP_NAME)) { c_parser_error (parser, "expected %<;%>, identifier or %<(%>"); parser->error = false; return NULL_TREE; } pending_xref_error (); prefix_attrs = specs->attrs; all_prefix_attrs = prefix_attrs; specs->attrs = NULL_TREE; decls = NULL_TREE; while (true) { /* Declaring one or more declarators or un-named bit-fields. */ struct c_declarator *declarator; bool dummy = false; if (c_parser_next_token_is (parser, CPP_COLON)) declarator = build_id_declarator (NULL_TREE); else declarator = c_parser_declarator (parser, specs->typespec_kind != ctsk_none, C_DTR_NORMAL, &dummy); if (declarator == NULL) { c_parser_skip_to_end_of_block_or_statement (parser); break; } if (c_parser_next_token_is (parser, CPP_COLON) || c_parser_next_token_is (parser, CPP_COMMA) || c_parser_next_token_is (parser, CPP_SEMICOLON) || c_parser_next_token_is (parser, CPP_CLOSE_BRACE) || c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) { tree postfix_attrs = NULL_TREE; tree width = NULL_TREE; tree d; if (c_parser_next_token_is (parser, CPP_COLON)) { c_parser_consume_token (parser); width = c_parser_expr_no_commas (parser, NULL).value; } if (c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) postfix_attrs = c_parser_attributes (parser); d = grokfield (c_parser_peek_token (parser)->location, declarator, specs, width, &all_prefix_attrs); decl_attributes (&d, chainon (postfix_attrs, all_prefix_attrs), 0); DECL_CHAIN (d) = decls; decls = d; if (c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) all_prefix_attrs = chainon (c_parser_attributes (parser), prefix_attrs); else all_prefix_attrs = prefix_attrs; if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else if (c_parser_next_token_is (parser, CPP_SEMICOLON) || c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { /* Semicolon consumed in caller. */ break; } else { c_parser_error (parser, "expected %<,%>, %<;%> or %<}%>"); break; } } else { c_parser_error (parser, "expected %<:%>, %<,%>, %<;%>, %<}%> or " "%<__attribute__%>"); break; } } return decls; } /* Parse a typeof specifier (a GNU extension). typeof-specifier: typeof ( expression ) typeof ( type-name ) */ static struct c_typespec c_parser_typeof_specifier (c_parser *parser) { struct c_typespec ret; ret.kind = ctsk_typeof; ret.spec = error_mark_node; ret.expr = NULL_TREE; ret.expr_const_operands = true; gcc_assert (c_parser_next_token_is_keyword (parser, RID_TYPEOF)); c_parser_consume_token (parser); c_inhibit_evaluation_warnings++; in_typeof++; matching_parens parens; if (!parens.require_open (parser)) { c_inhibit_evaluation_warnings--; in_typeof--; return ret; } if (c_parser_next_tokens_start_typename (parser, cla_prefer_id)) { struct c_type_name *type = c_parser_type_name (parser); c_inhibit_evaluation_warnings--; in_typeof--; if (type != NULL) { ret.spec = groktypename (type, &ret.expr, &ret.expr_const_operands); pop_maybe_used (variably_modified_type_p (ret.spec, NULL_TREE)); } } else { bool was_vm; location_t here = c_parser_peek_token (parser)->location; struct c_expr expr = c_parser_expression (parser); c_inhibit_evaluation_warnings--; in_typeof--; if (TREE_CODE (expr.value) == COMPONENT_REF && DECL_C_BIT_FIELD (TREE_OPERAND (expr.value, 1))) error_at (here, "%<typeof%> applied to a bit-field"); mark_exp_read (expr.value); ret.spec = TREE_TYPE (expr.value); was_vm = variably_modified_type_p (ret.spec, NULL_TREE); /* This is returned with the type so that when the type is evaluated, this can be evaluated. */ if (was_vm) ret.expr = c_fully_fold (expr.value, false, &ret.expr_const_operands); pop_maybe_used (was_vm); /* For use in macros such as those in <stdatomic.h>, remove all qualifiers from atomic types. (const can be an issue for more macros using typeof than just the <stdatomic.h> ones.) */ if (ret.spec != error_mark_node && TYPE_ATOMIC (ret.spec)) ret.spec = c_build_qualified_type (ret.spec, TYPE_UNQUALIFIED); } parens.skip_until_found_close (parser); return ret; } /* Parse an alignment-specifier. C11 6.7.5: alignment-specifier: _Alignas ( type-name ) _Alignas ( constant-expression ) */ static tree c_parser_alignas_specifier (c_parser * parser) { tree ret = error_mark_node; location_t loc = c_parser_peek_token (parser)->location; gcc_assert (c_parser_next_token_is_keyword (parser, RID_ALIGNAS)); c_parser_consume_token (parser); if (flag_isoc99) pedwarn_c99 (loc, OPT_Wpedantic, "ISO C99 does not support %<_Alignas%>"); else pedwarn_c99 (loc, OPT_Wpedantic, "ISO C90 does not support %<_Alignas%>"); matching_parens parens; if (!parens.require_open (parser)) return ret; if (c_parser_next_tokens_start_typename (parser, cla_prefer_id)) { struct c_type_name *type = c_parser_type_name (parser); if (type != NULL) ret = c_sizeof_or_alignof_type (loc, groktypename (type, NULL, NULL), false, true, 1); } else ret = c_parser_expr_no_commas (parser, NULL).value; parens.skip_until_found_close (parser); return ret; } /* Parse a declarator, possibly an abstract declarator (C90 6.5.4, 6.5.5, C99 6.7.5, 6.7.6, C11 6.7.6, 6.7.7). If TYPE_SEEN_P then a typedef name may be redeclared; otherwise it may not. KIND indicates which kind of declarator is wanted. Returns a valid declarator except in the case of a syntax error in which case NULL is returned. *SEEN_ID is set to true if an identifier being declared is seen; this is used to diagnose bad forms of abstract array declarators and to determine whether an identifier list is syntactically permitted. declarator: pointer[opt] direct-declarator direct-declarator: identifier ( attributes[opt] declarator ) direct-declarator array-declarator direct-declarator ( parameter-type-list ) direct-declarator ( identifier-list[opt] ) pointer: * type-qualifier-list[opt] * type-qualifier-list[opt] pointer type-qualifier-list: type-qualifier attributes type-qualifier-list type-qualifier type-qualifier-list attributes array-declarator: [ type-qualifier-list[opt] assignment-expression[opt] ] [ static type-qualifier-list[opt] assignment-expression ] [ type-qualifier-list static assignment-expression ] [ type-qualifier-list[opt] * ] parameter-type-list: parameter-list parameter-list , ... parameter-list: parameter-declaration parameter-list , parameter-declaration parameter-declaration: declaration-specifiers declarator attributes[opt] declaration-specifiers abstract-declarator[opt] attributes[opt] identifier-list: identifier identifier-list , identifier abstract-declarator: pointer pointer[opt] direct-abstract-declarator direct-abstract-declarator: ( attributes[opt] abstract-declarator ) direct-abstract-declarator[opt] array-declarator direct-abstract-declarator[opt] ( parameter-type-list[opt] ) GNU extensions: direct-declarator: direct-declarator ( parameter-forward-declarations parameter-type-list[opt] ) direct-abstract-declarator: direct-abstract-declarator[opt] ( parameter-forward-declarations parameter-type-list[opt] ) parameter-forward-declarations: parameter-list ; parameter-forward-declarations parameter-list ; The uses of attributes shown above are GNU extensions. Some forms of array declarator are not included in C99 in the syntax for abstract declarators; these are disallowed elsewhere. This may be a defect (DR#289). This function also accepts an omitted abstract declarator as being an abstract declarator, although not part of the formal syntax. */ struct c_declarator * c_parser_declarator (c_parser *parser, bool type_seen_p, c_dtr_syn kind, bool *seen_id) { /* Parse any initial pointer part. */ if (c_parser_next_token_is (parser, CPP_MULT)) { struct c_declspecs *quals_attrs = build_null_declspecs (); struct c_declarator *inner; c_parser_consume_token (parser); c_parser_declspecs (parser, quals_attrs, false, false, true, false, false, cla_prefer_id); inner = c_parser_declarator (parser, type_seen_p, kind, seen_id); if (inner == NULL) return NULL; else return make_pointer_declarator (quals_attrs, inner); } /* Now we have a direct declarator, direct abstract declarator or nothing (which counts as a direct abstract declarator here). */ return c_parser_direct_declarator (parser, type_seen_p, kind, seen_id); } /* Parse a direct declarator or direct abstract declarator; arguments as c_parser_declarator. */ static struct c_declarator * c_parser_direct_declarator (c_parser *parser, bool type_seen_p, c_dtr_syn kind, bool *seen_id) { /* The direct declarator must start with an identifier (possibly omitted) or a parenthesized declarator (possibly abstract). In an ordinary declarator, initial parentheses must start a parenthesized declarator. In an abstract declarator or parameter declarator, they could start a parenthesized declarator or a parameter list. To tell which, the open parenthesis and any following attributes must be read. If a declaration specifier follows, then it is a parameter list; if the specifier is a typedef name, there might be an ambiguity about redeclaring it, which is resolved in the direction of treating it as a typedef name. If a close parenthesis follows, it is also an empty parameter list, as the syntax does not permit empty abstract declarators. Otherwise, it is a parenthesized declarator (in which case the analysis may be repeated inside it, recursively). ??? There is an ambiguity in a parameter declaration "int (__attribute__((foo)) x)", where x is not a typedef name: it could be an abstract declarator for a function, or declare x with parentheses. The proper resolution of this ambiguity needs documenting. At present we follow an accident of the old parser's implementation, whereby the first parameter must have some declaration specifiers other than just attributes. Thus as a parameter declaration it is treated as a parenthesized parameter named x, and as an abstract declarator it is rejected. ??? Also following the old parser, attributes inside an empty parameter list are ignored, making it a list not yielding a prototype, rather than giving an error or making it have one parameter with implicit type int. ??? Also following the old parser, typedef names may be redeclared in declarators, but not Objective-C class names. */ if (kind != C_DTR_ABSTRACT && c_parser_next_token_is (parser, CPP_NAME) && ((type_seen_p && (c_parser_peek_token (parser)->id_kind == C_ID_TYPENAME || c_parser_peek_token (parser)->id_kind == C_ID_CLASSNAME)) || c_parser_peek_token (parser)->id_kind == C_ID_ID)) { struct c_declarator *inner = build_id_declarator (c_parser_peek_token (parser)->value); *seen_id = true; inner->id_loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); return c_parser_direct_declarator_inner (parser, *seen_id, inner); } if (kind != C_DTR_NORMAL && c_parser_next_token_is (parser, CPP_OPEN_SQUARE)) { struct c_declarator *inner = build_id_declarator (NULL_TREE); inner->id_loc = c_parser_peek_token (parser)->location; return c_parser_direct_declarator_inner (parser, *seen_id, inner); } /* Either we are at the end of an abstract declarator, or we have parentheses. */ if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { tree attrs; struct c_declarator *inner; c_parser_consume_token (parser); attrs = c_parser_attributes (parser); if (kind != C_DTR_NORMAL && (c_parser_next_token_starts_declspecs (parser) || c_parser_next_token_is (parser, CPP_CLOSE_PAREN))) { struct c_arg_info *args = c_parser_parms_declarator (parser, kind == C_DTR_NORMAL, attrs); if (args == NULL) return NULL; else { inner = build_function_declarator (args, build_id_declarator (NULL_TREE)); return c_parser_direct_declarator_inner (parser, *seen_id, inner); } } /* A parenthesized declarator. */ inner = c_parser_declarator (parser, type_seen_p, kind, seen_id); if (inner != NULL && attrs != NULL) inner = build_attrs_declarator (attrs, inner); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { c_parser_consume_token (parser); if (inner == NULL) return NULL; else return c_parser_direct_declarator_inner (parser, *seen_id, inner); } else { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return NULL; } } else { if (kind == C_DTR_NORMAL) { c_parser_error (parser, "expected identifier or %<(%>"); return NULL; } else return build_id_declarator (NULL_TREE); } } /* Parse part of a direct declarator or direct abstract declarator, given that some (in INNER) has already been parsed; ID_PRESENT is true if an identifier is present, false for an abstract declarator. */ static struct c_declarator * c_parser_direct_declarator_inner (c_parser *parser, bool id_present, struct c_declarator *inner) { /* Parse a sequence of array declarators and parameter lists. */ if (c_parser_next_token_is (parser, CPP_OPEN_SQUARE)) { location_t brace_loc = c_parser_peek_token (parser)->location; struct c_declarator *declarator; struct c_declspecs *quals_attrs = build_null_declspecs (); bool static_seen; bool star_seen; struct c_expr dimen; dimen.value = NULL_TREE; dimen.original_code = ERROR_MARK; dimen.original_type = NULL_TREE; c_parser_consume_token (parser); c_parser_declspecs (parser, quals_attrs, false, false, true, false, false, cla_prefer_id); static_seen = c_parser_next_token_is_keyword (parser, RID_STATIC); if (static_seen) c_parser_consume_token (parser); if (static_seen && !quals_attrs->declspecs_seen_p) c_parser_declspecs (parser, quals_attrs, false, false, true, false, false, cla_prefer_id); if (!quals_attrs->declspecs_seen_p) quals_attrs = NULL; /* If "static" is present, there must be an array dimension. Otherwise, there may be a dimension, "*", or no dimension. */ if (static_seen) { star_seen = false; dimen = c_parser_expr_no_commas (parser, NULL); } else { if (c_parser_next_token_is (parser, CPP_CLOSE_SQUARE)) { dimen.value = NULL_TREE; star_seen = false; } else if (c_parser_next_token_is (parser, CPP_MULT)) { if (c_parser_peek_2nd_token (parser)->type == CPP_CLOSE_SQUARE) { dimen.value = NULL_TREE; star_seen = true; c_parser_consume_token (parser); } else { star_seen = false; dimen = c_parser_expr_no_commas (parser, NULL); } } else { star_seen = false; dimen = c_parser_expr_no_commas (parser, NULL); } } if (c_parser_next_token_is (parser, CPP_CLOSE_SQUARE)) c_parser_consume_token (parser); else { c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, "expected %<]%>"); return NULL; } if (dimen.value) dimen = convert_lvalue_to_rvalue (brace_loc, dimen, true, true); declarator = build_array_declarator (brace_loc, dimen.value, quals_attrs, static_seen, star_seen); if (declarator == NULL) return NULL; inner = set_array_declarator_inner (declarator, inner); return c_parser_direct_declarator_inner (parser, id_present, inner); } else if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { tree attrs; struct c_arg_info *args; c_parser_consume_token (parser); attrs = c_parser_attributes (parser); args = c_parser_parms_declarator (parser, id_present, attrs); if (args == NULL) return NULL; else { inner = build_function_declarator (args, inner); return c_parser_direct_declarator_inner (parser, id_present, inner); } } return inner; } /* Parse a parameter list or identifier list, including the closing parenthesis but not the opening one. ATTRS are the attributes at the start of the list. ID_LIST_OK is true if an identifier list is acceptable; such a list must not have attributes at the start. */ static struct c_arg_info * c_parser_parms_declarator (c_parser *parser, bool id_list_ok, tree attrs) { push_scope (); declare_parm_level (); /* If the list starts with an identifier, it is an identifier list. Otherwise, it is either a prototype list or an empty list. */ if (id_list_ok && !attrs && c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_token (parser)->id_kind == C_ID_ID /* Look ahead to detect typos in type names. */ && c_parser_peek_2nd_token (parser)->type != CPP_NAME && c_parser_peek_2nd_token (parser)->type != CPP_MULT && c_parser_peek_2nd_token (parser)->type != CPP_OPEN_PAREN && c_parser_peek_2nd_token (parser)->type != CPP_OPEN_SQUARE && c_parser_peek_2nd_token (parser)->type != CPP_KEYWORD) { tree list = NULL_TREE, *nextp = &list; while (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_token (parser)->id_kind == C_ID_ID) { *nextp = build_tree_list (NULL_TREE, c_parser_peek_token (parser)->value); nextp = & TREE_CHAIN (*nextp); c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_COMMA)) break; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { c_parser_error (parser, "expected identifier"); break; } } if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { struct c_arg_info *ret = build_arg_info (); ret->types = list; c_parser_consume_token (parser); pop_scope (); return ret; } else { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); pop_scope (); return NULL; } } else { struct c_arg_info *ret = c_parser_parms_list_declarator (parser, attrs, NULL); pop_scope (); return ret; } } /* Parse a parameter list (possibly empty), including the closing parenthesis but not the opening one. ATTRS are the attributes at the start of the list. EXPR is NULL or an expression that needs to be evaluated for the side effects of array size expressions in the parameters. */ static struct c_arg_info * c_parser_parms_list_declarator (c_parser *parser, tree attrs, tree expr) { bool bad_parm = false; /* ??? Following the old parser, forward parameter declarations may use abstract declarators, and if no real parameter declarations follow the forward declarations then this is not diagnosed. Also note as above that attributes are ignored as the only contents of the parentheses, or as the only contents after forward declarations. */ if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { struct c_arg_info *ret = build_arg_info (); c_parser_consume_token (parser); return ret; } if (c_parser_next_token_is (parser, CPP_ELLIPSIS)) { struct c_arg_info *ret = build_arg_info (); if (flag_allow_parameterless_variadic_functions) { /* F (...) is allowed. */ ret->types = NULL_TREE; } else { /* Suppress -Wold-style-definition for this case. */ ret->types = error_mark_node; error_at (c_parser_peek_token (parser)->location, "ISO C requires a named argument before %<...%>"); } c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { c_parser_consume_token (parser); return ret; } else { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return NULL; } } /* Nonempty list of parameters, either terminated with semicolon (forward declarations; recurse) or with close parenthesis (normal function) or with ", ... )" (variadic function). */ while (true) { /* Parse a parameter. */ struct c_parm *parm = c_parser_parameter_declaration (parser, attrs); attrs = NULL_TREE; if (parm == NULL) bad_parm = true; else push_parm_decl (parm, &expr); if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { tree new_attrs; c_parser_consume_token (parser); mark_forward_parm_decls (); new_attrs = c_parser_attributes (parser); return c_parser_parms_list_declarator (parser, new_attrs, expr); } if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { c_parser_consume_token (parser); if (bad_parm) return NULL; else return get_parm_info (false, expr); } if (!c_parser_require (parser, CPP_COMMA, "expected %<;%>, %<,%> or %<)%>", UNKNOWN_LOCATION, false)) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return NULL; } if (c_parser_next_token_is (parser, CPP_ELLIPSIS)) { c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { c_parser_consume_token (parser); if (bad_parm) return NULL; else return get_parm_info (true, expr); } else { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return NULL; } } } } /* Parse a parameter declaration. ATTRS are the attributes at the start of the declaration if it is the first parameter. */ static struct c_parm * c_parser_parameter_declaration (c_parser *parser, tree attrs) { struct c_declspecs *specs; struct c_declarator *declarator; tree prefix_attrs; tree postfix_attrs = NULL_TREE; bool dummy = false; /* Accept #pragmas between parameter declarations. */ while (c_parser_next_token_is (parser, CPP_PRAGMA)) c_parser_pragma (parser, pragma_param, NULL); if (!c_parser_next_token_starts_declspecs (parser)) { c_token *token = c_parser_peek_token (parser); if (parser->error) return NULL; c_parser_set_source_position_from_token (token); if (c_parser_next_tokens_start_typename (parser, cla_prefer_type)) { name_hint hint = lookup_name_fuzzy (token->value, FUZZY_LOOKUP_TYPENAME, token->location); if (hint) { gcc_rich_location richloc (token->location); richloc.add_fixit_replace (hint.suggestion ()); error_at (&richloc, "unknown type name %qE; did you mean %qs?", token->value, hint.suggestion ()); } else error_at (token->location, "unknown type name %qE", token->value); parser->error = true; } /* ??? In some Objective-C cases '...' isn't applicable so there should be a different message. */ else c_parser_error (parser, "expected declaration specifiers or %<...%>"); c_parser_skip_to_end_of_parameter (parser); return NULL; } location_t start_loc = c_parser_peek_token (parser)->location; specs = build_null_declspecs (); if (attrs) { declspecs_add_attrs (input_location, specs, attrs); attrs = NULL_TREE; } c_parser_declspecs (parser, specs, true, true, true, true, false, cla_nonabstract_decl); finish_declspecs (specs); pending_xref_error (); prefix_attrs = specs->attrs; specs->attrs = NULL_TREE; declarator = c_parser_declarator (parser, specs->typespec_kind != ctsk_none, C_DTR_PARM, &dummy); if (declarator == NULL) { c_parser_skip_until_found (parser, CPP_COMMA, NULL); return NULL; } if (c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) postfix_attrs = c_parser_attributes (parser); /* Generate a location for the parameter, ranging from the start of the initial token to the end of the final token. If we have a identifier, then use it for the caret location, e.g. extern int callee (int one, int (*two)(int, int), float three); ~~~~~~^~~~~~~~~~~~~~ otherwise, reuse the start location for the caret location e.g.: extern int callee (int one, int (*)(int, int), float three); ^~~~~~~~~~~~~~~~~ */ location_t end_loc = parser->last_token_location; /* Find any cdk_id declarator; determine if we have an identifier. */ c_declarator *id_declarator = declarator; while (id_declarator && id_declarator->kind != cdk_id) id_declarator = id_declarator->declarator; location_t caret_loc = (id_declarator->u.id ? id_declarator->id_loc : start_loc); location_t param_loc = make_location (caret_loc, start_loc, end_loc); return build_c_parm (specs, chainon (postfix_attrs, prefix_attrs), declarator, param_loc); } /* Parse a string literal in an asm expression. It should not be translated, and wide string literals are an error although permitted by the syntax. This is a GNU extension. asm-string-literal: string-literal ??? At present, following the old parser, the caller needs to have set lex_untranslated_string to 1. It would be better to follow the C++ parser rather than using this kludge. */ static tree c_parser_asm_string_literal (c_parser *parser) { tree str; int save_flag = warn_overlength_strings; warn_overlength_strings = 0; if (c_parser_next_token_is (parser, CPP_STRING)) { str = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); } else if (c_parser_next_token_is (parser, CPP_WSTRING)) { error_at (c_parser_peek_token (parser)->location, "wide string literal in %<asm%>"); str = build_string (1, ""); c_parser_consume_token (parser); } else { c_parser_error (parser, "expected string literal"); str = NULL_TREE; } warn_overlength_strings = save_flag; return str; } /* Parse a simple asm expression. This is used in restricted contexts, where a full expression with inputs and outputs does not make sense. This is a GNU extension. simple-asm-expr: asm ( asm-string-literal ) */ static tree c_parser_simple_asm_expr (c_parser *parser) { tree str; gcc_assert (c_parser_next_token_is_keyword (parser, RID_ASM)); /* ??? Follow the C++ parser rather than using the lex_untranslated_string kludge. */ parser->lex_untranslated_string = true; c_parser_consume_token (parser); matching_parens parens; if (!parens.require_open (parser)) { parser->lex_untranslated_string = false; return NULL_TREE; } str = c_parser_asm_string_literal (parser); parser->lex_untranslated_string = false; if (!parens.require_close (parser)) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return NULL_TREE; } return str; } static tree c_parser_attribute_any_word (c_parser *parser) { tree attr_name = NULL_TREE; if (c_parser_next_token_is (parser, CPP_KEYWORD)) { /* ??? See comment above about what keywords are accepted here. */ bool ok; switch (c_parser_peek_token (parser)->keyword) { case RID_STATIC: case RID_UNSIGNED: case RID_LONG: case RID_CONST: case RID_EXTERN: case RID_REGISTER: case RID_TYPEDEF: case RID_SHORT: case RID_INLINE: case RID_NORETURN: case RID_VOLATILE: case RID_SIGNED: case RID_AUTO: case RID_RESTRICT: case RID_COMPLEX: case RID_THREAD: case RID_INT: case RID_CHAR: case RID_FLOAT: case RID_DOUBLE: case RID_VOID: case RID_DFLOAT32: case RID_DFLOAT64: case RID_DFLOAT128: CASE_RID_FLOATN_NX: case RID_BOOL: case RID_FRACT: case RID_ACCUM: case RID_SAT: case RID_TRANSACTION_ATOMIC: case RID_TRANSACTION_CANCEL: case RID_ATOMIC: case RID_AUTO_TYPE: case RID_INT_N_0: case RID_INT_N_1: case RID_INT_N_2: case RID_INT_N_3: ok = true; break; default: ok = false; break; } if (!ok) return NULL_TREE; /* Accept __attribute__((__const)) as __attribute__((const)) etc. */ attr_name = ridpointers[(int) c_parser_peek_token (parser)->keyword]; } else if (c_parser_next_token_is (parser, CPP_NAME)) attr_name = c_parser_peek_token (parser)->value; return attr_name; } /* Parse (possibly empty) attributes. This is a GNU extension. attributes: empty attributes attribute attribute: __attribute__ ( ( attribute-list ) ) attribute-list: attrib attribute_list , attrib attrib: empty any-word any-word ( identifier ) any-word ( identifier , nonempty-expr-list ) any-word ( expr-list ) where the "identifier" must not be declared as a type, and "any-word" may be any identifier (including one declared as a type), a reserved word storage class specifier, type specifier or type qualifier. ??? This still leaves out most reserved keywords (following the old parser), shouldn't we include them, and why not allow identifiers declared as types to start the arguments? */ static tree c_parser_attributes (c_parser *parser) { tree attrs = NULL_TREE; while (c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) { /* ??? Follow the C++ parser rather than using the lex_untranslated_string kludge. */ parser->lex_untranslated_string = true; /* Consume the `__attribute__' keyword. */ c_parser_consume_token (parser); /* Look for the two `(' tokens. */ if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { parser->lex_untranslated_string = false; return attrs; } if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { parser->lex_untranslated_string = false; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return attrs; } /* Parse the attribute list. */ while (c_parser_next_token_is (parser, CPP_COMMA) || c_parser_next_token_is (parser, CPP_NAME) || c_parser_next_token_is (parser, CPP_KEYWORD)) { tree attr, attr_name, attr_args; vec<tree, va_gc> *expr_list; if (c_parser_next_token_is (parser, CPP_COMMA)) { c_parser_consume_token (parser); continue; } attr_name = c_parser_attribute_any_word (parser); if (attr_name == NULL) break; attr_name = canonicalize_attr_name (attr_name); c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_OPEN_PAREN)) { attr = build_tree_list (attr_name, NULL_TREE); /* Add this attribute to the list. */ attrs = chainon (attrs, attr); /* If the next token isn't a comma, we're done. */ if (!c_parser_next_token_is (parser, CPP_COMMA)) break; continue; } c_parser_consume_token (parser); /* Parse the attribute contents. If they start with an identifier which is followed by a comma or close parenthesis, then the arguments start with that identifier; otherwise they are an expression list. In objective-c the identifier may be a classname. */ if (c_parser_next_token_is (parser, CPP_NAME) && (c_parser_peek_token (parser)->id_kind == C_ID_ID || (c_dialect_objc () && c_parser_peek_token (parser)->id_kind == C_ID_CLASSNAME)) && ((c_parser_peek_2nd_token (parser)->type == CPP_COMMA) || (c_parser_peek_2nd_token (parser)->type == CPP_CLOSE_PAREN)) && (attribute_takes_identifier_p (attr_name) || (c_dialect_objc () && c_parser_peek_token (parser)->id_kind == C_ID_CLASSNAME))) { tree arg1 = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) attr_args = build_tree_list (NULL_TREE, arg1); else { tree tree_list; c_parser_consume_token (parser); expr_list = c_parser_expr_list (parser, false, true, NULL, NULL, NULL, NULL); tree_list = build_tree_list_vec (expr_list); attr_args = tree_cons (NULL_TREE, arg1, tree_list); release_tree_vector (expr_list); } } else { if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) attr_args = NULL_TREE; else { expr_list = c_parser_expr_list (parser, false, true, NULL, NULL, NULL, NULL); attr_args = build_tree_list_vec (expr_list); release_tree_vector (expr_list); } } attr = build_tree_list (attr_name, attr_args); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) c_parser_consume_token (parser); else { parser->lex_untranslated_string = false; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return attrs; } /* Add this attribute to the list. */ attrs = chainon (attrs, attr); /* If the next token isn't a comma, we're done. */ if (!c_parser_next_token_is (parser, CPP_COMMA)) break; } /* Look for the two `)' tokens. */ if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) c_parser_consume_token (parser); else { parser->lex_untranslated_string = false; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return attrs; } if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) c_parser_consume_token (parser); else { parser->lex_untranslated_string = false; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return attrs; } parser->lex_untranslated_string = false; } return attrs; } /* Parse a type name (C90 6.5.5, C99 6.7.6, C11 6.7.7). ALIGNAS_OK says whether alignment specifiers are OK (only in cases that might be the type name of a compound literal). type-name: specifier-qualifier-list abstract-declarator[opt] */ struct c_type_name * c_parser_type_name (c_parser *parser, bool alignas_ok) { struct c_declspecs *specs = build_null_declspecs (); struct c_declarator *declarator; struct c_type_name *ret; bool dummy = false; c_parser_declspecs (parser, specs, false, true, true, alignas_ok, false, cla_prefer_type); if (!specs->declspecs_seen_p) { c_parser_error (parser, "expected specifier-qualifier-list"); return NULL; } if (specs->type != error_mark_node) { pending_xref_error (); finish_declspecs (specs); } declarator = c_parser_declarator (parser, specs->typespec_kind != ctsk_none, C_DTR_ABSTRACT, &dummy); if (declarator == NULL) return NULL; ret = XOBNEW (&parser_obstack, struct c_type_name); ret->specs = specs; ret->declarator = declarator; return ret; } /* Parse an initializer (C90 6.5.7, C99 6.7.8, C11 6.7.9). initializer: assignment-expression { initializer-list } { initializer-list , } initializer-list: designation[opt] initializer initializer-list , designation[opt] initializer designation: designator-list = designator-list: designator designator-list designator designator: array-designator . identifier array-designator: [ constant-expression ] GNU extensions: initializer: { } designation: array-designator identifier : array-designator: [ constant-expression ... constant-expression ] Any expression without commas is accepted in the syntax for the constant-expressions, with non-constant expressions rejected later. This function is only used for top-level initializers; for nested ones, see c_parser_initval. */ static struct c_expr c_parser_initializer (c_parser *parser) { if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) return c_parser_braced_init (parser, NULL_TREE, false, NULL); else { struct c_expr ret; location_t loc = c_parser_peek_token (parser)->location; ret = c_parser_expr_no_commas (parser, NULL); if (TREE_CODE (ret.value) != STRING_CST && TREE_CODE (ret.value) != COMPOUND_LITERAL_EXPR) ret = convert_lvalue_to_rvalue (loc, ret, true, true); return ret; } } /* The location of the last comma within the current initializer list, or UNKNOWN_LOCATION if not within one. */ location_t last_init_list_comma; /* Parse a braced initializer list. TYPE is the type specified for a compound literal, and NULL_TREE for other initializers and for nested braced lists. NESTED_P is true for nested braced lists, false for the list of a compound literal or the list that is the top-level initializer in a declaration. */ static struct c_expr c_parser_braced_init (c_parser *parser, tree type, bool nested_p, struct obstack *outer_obstack) { struct c_expr ret; struct obstack braced_init_obstack; location_t brace_loc = c_parser_peek_token (parser)->location; gcc_obstack_init (&braced_init_obstack); gcc_assert (c_parser_next_token_is (parser, CPP_OPEN_BRACE)); matching_braces braces; braces.consume_open (parser); if (nested_p) { finish_implicit_inits (brace_loc, outer_obstack); push_init_level (brace_loc, 0, &braced_init_obstack); } else really_start_incremental_init (type); if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { pedwarn (brace_loc, OPT_Wpedantic, "ISO C forbids empty initializer braces"); } else { /* Parse a non-empty initializer list, possibly with a trailing comma. */ while (true) { c_parser_initelt (parser, &braced_init_obstack); if (parser->error) break; if (c_parser_next_token_is (parser, CPP_COMMA)) { last_init_list_comma = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); } else break; if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) break; } } c_token *next_tok = c_parser_peek_token (parser); if (next_tok->type != CPP_CLOSE_BRACE) { ret.set_error (); ret.original_code = ERROR_MARK; ret.original_type = NULL; braces.skip_until_found_close (parser); pop_init_level (brace_loc, 0, &braced_init_obstack, last_init_list_comma); obstack_free (&braced_init_obstack, NULL); return ret; } location_t close_loc = next_tok->location; c_parser_consume_token (parser); ret = pop_init_level (brace_loc, 0, &braced_init_obstack, close_loc); obstack_free (&braced_init_obstack, NULL); set_c_expr_source_range (&ret, brace_loc, close_loc); return ret; } /* Parse a nested initializer, including designators. */ static void c_parser_initelt (c_parser *parser, struct obstack * braced_init_obstack) { /* Parse any designator or designator list. A single array designator may have the subsequent "=" omitted in GNU C, but a longer list or a structure member designator may not. */ if (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_2nd_token (parser)->type == CPP_COLON) { /* Old-style structure member designator. */ set_init_label (c_parser_peek_token (parser)->location, c_parser_peek_token (parser)->value, c_parser_peek_token (parser)->location, braced_init_obstack); /* Use the colon as the error location. */ pedwarn (c_parser_peek_2nd_token (parser)->location, OPT_Wpedantic, "obsolete use of designated initializer with %<:%>"); c_parser_consume_token (parser); c_parser_consume_token (parser); } else { /* des_seen is 0 if there have been no designators, 1 if there has been a single array designator and 2 otherwise. */ int des_seen = 0; /* Location of a designator. */ location_t des_loc = UNKNOWN_LOCATION; /* Quiet warning. */ while (c_parser_next_token_is (parser, CPP_OPEN_SQUARE) || c_parser_next_token_is (parser, CPP_DOT)) { int des_prev = des_seen; if (!des_seen) des_loc = c_parser_peek_token (parser)->location; if (des_seen < 2) des_seen++; if (c_parser_next_token_is (parser, CPP_DOT)) { des_seen = 2; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_NAME)) { set_init_label (des_loc, c_parser_peek_token (parser)->value, c_parser_peek_token (parser)->location, braced_init_obstack); c_parser_consume_token (parser); } else { struct c_expr init; init.set_error (); init.original_code = ERROR_MARK; init.original_type = NULL; c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_COMMA, NULL); process_init_element (input_location, init, false, braced_init_obstack); return; } } else { tree first, second; location_t ellipsis_loc = UNKNOWN_LOCATION; /* Quiet warning. */ location_t array_index_loc = UNKNOWN_LOCATION; /* ??? Following the old parser, [ objc-receiver objc-message-args ] is accepted as an initializer, being distinguished from a designator by what follows the first assignment expression inside the square brackets, but after a first array designator a subsequent square bracket is for Objective-C taken to start an expression, using the obsolete form of designated initializer without '=', rather than possibly being a second level of designation: in LALR terms, the '[' is shifted rather than reducing designator to designator-list. */ if (des_prev == 1 && c_dialect_objc ()) { des_seen = des_prev; break; } if (des_prev == 0 && c_dialect_objc ()) { /* This might be an array designator or an Objective-C message expression. If the former, continue parsing here; if the latter, parse the remainder of the initializer given the starting primary-expression. ??? It might make sense to distinguish when des_prev == 1 as well; see previous comment. */ tree rec, args; struct c_expr mexpr; c_parser_consume_token (parser); if (c_parser_peek_token (parser)->type == CPP_NAME && ((c_parser_peek_token (parser)->id_kind == C_ID_TYPENAME) || (c_parser_peek_token (parser)->id_kind == C_ID_CLASSNAME))) { /* Type name receiver. */ tree id = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); rec = objc_get_class_reference (id); goto parse_message_args; } first = c_parser_expr_no_commas (parser, NULL).value; mark_exp_read (first); if (c_parser_next_token_is (parser, CPP_ELLIPSIS) || c_parser_next_token_is (parser, CPP_CLOSE_SQUARE)) goto array_desig_after_first; /* Expression receiver. So far only one part without commas has been parsed; there might be more of the expression. */ rec = first; while (c_parser_next_token_is (parser, CPP_COMMA)) { struct c_expr next; location_t comma_loc, exp_loc; comma_loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); exp_loc = c_parser_peek_token (parser)->location; next = c_parser_expr_no_commas (parser, NULL); next = convert_lvalue_to_rvalue (exp_loc, next, true, true); rec = build_compound_expr (comma_loc, rec, next.value); } parse_message_args: /* Now parse the objc-message-args. */ args = c_parser_objc_message_args (parser); c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, "expected %<]%>"); mexpr.value = objc_build_message_expr (rec, args); mexpr.original_code = ERROR_MARK; mexpr.original_type = NULL; /* Now parse and process the remainder of the initializer, starting with this message expression as a primary-expression. */ c_parser_initval (parser, &mexpr, braced_init_obstack); return; } c_parser_consume_token (parser); array_index_loc = c_parser_peek_token (parser)->location; first = c_parser_expr_no_commas (parser, NULL).value; mark_exp_read (first); array_desig_after_first: if (c_parser_next_token_is (parser, CPP_ELLIPSIS)) { ellipsis_loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); second = c_parser_expr_no_commas (parser, NULL).value; mark_exp_read (second); } else second = NULL_TREE; if (c_parser_next_token_is (parser, CPP_CLOSE_SQUARE)) { c_parser_consume_token (parser); set_init_index (array_index_loc, first, second, braced_init_obstack); if (second) pedwarn (ellipsis_loc, OPT_Wpedantic, "ISO C forbids specifying range of elements to initialize"); } else c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, "expected %<]%>"); } } if (des_seen >= 1) { if (c_parser_next_token_is (parser, CPP_EQ)) { pedwarn_c90 (des_loc, OPT_Wpedantic, "ISO C90 forbids specifying subobject " "to initialize"); c_parser_consume_token (parser); } else { if (des_seen == 1) pedwarn (c_parser_peek_token (parser)->location, OPT_Wpedantic, "obsolete use of designated initializer without %<=%>"); else { struct c_expr init; init.set_error (); init.original_code = ERROR_MARK; init.original_type = NULL; c_parser_error (parser, "expected %<=%>"); c_parser_skip_until_found (parser, CPP_COMMA, NULL); process_init_element (input_location, init, false, braced_init_obstack); return; } } } } c_parser_initval (parser, NULL, braced_init_obstack); } /* Parse a nested initializer; as c_parser_initializer but parses initializers within braced lists, after any designators have been applied. If AFTER is not NULL then it is an Objective-C message expression which is the primary-expression starting the initializer. */ static void c_parser_initval (c_parser *parser, struct c_expr *after, struct obstack * braced_init_obstack) { struct c_expr init; gcc_assert (!after || c_dialect_objc ()); location_t loc = c_parser_peek_token (parser)->location; if (c_parser_next_token_is (parser, CPP_OPEN_BRACE) && !after) init = c_parser_braced_init (parser, NULL_TREE, true, braced_init_obstack); else { init = c_parser_expr_no_commas (parser, after); if (init.value != NULL_TREE && TREE_CODE (init.value) != STRING_CST && TREE_CODE (init.value) != COMPOUND_LITERAL_EXPR) init = convert_lvalue_to_rvalue (loc, init, true, true); } process_init_element (loc, init, false, braced_init_obstack); } /* Parse a compound statement (possibly a function body) (C90 6.6.2, C99 6.8.2, C11 6.8.2). compound-statement: { block-item-list[opt] } { label-declarations block-item-list } block-item-list: block-item block-item-list block-item block-item: nested-declaration statement nested-declaration: declaration GNU extensions: compound-statement: { label-declarations block-item-list } nested-declaration: __extension__ nested-declaration nested-function-definition label-declarations: label-declaration label-declarations label-declaration label-declaration: __label__ identifier-list ; Allowing the mixing of declarations and code is new in C99. The GNU syntax also permits (not shown above) labels at the end of compound statements, which yield an error. We don't allow labels on declarations; this might seem like a natural extension, but there would be a conflict between attributes on the label and prefix attributes on the declaration. ??? The syntax follows the old parser in requiring something after label declarations. Although they are erroneous if the labels declared aren't defined, is it useful for the syntax to be this way? OpenACC: block-item: openacc-directive openacc-directive: update-directive OpenMP: block-item: openmp-directive openmp-directive: barrier-directive flush-directive taskwait-directive taskyield-directive cancel-directive cancellation-point-directive */ static tree c_parser_compound_statement (c_parser *parser) { tree stmt; location_t brace_loc; brace_loc = c_parser_peek_token (parser)->location; if (!c_parser_require (parser, CPP_OPEN_BRACE, "expected %<{%>")) { /* Ensure a scope is entered and left anyway to avoid confusion if we have just prepared to enter a function body. */ stmt = c_begin_compound_stmt (true); c_end_compound_stmt (brace_loc, stmt, true); return error_mark_node; } stmt = c_begin_compound_stmt (true); c_parser_compound_statement_nostart (parser); return c_end_compound_stmt (brace_loc, stmt, true); } /* Parse a compound statement except for the opening brace. This is used for parsing both compound statements and statement expressions (which follow different paths to handling the opening). */ static void c_parser_compound_statement_nostart (c_parser *parser) { bool last_stmt = false; bool last_label = false; bool save_valid_for_pragma = valid_location_for_stdc_pragma_p (); location_t label_loc = UNKNOWN_LOCATION; /* Quiet warning. */ if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { add_debug_begin_stmt (c_parser_peek_token (parser)->location); c_parser_consume_token (parser); return; } mark_valid_location_for_stdc_pragma (true); if (c_parser_next_token_is_keyword (parser, RID_LABEL)) { /* Read zero or more forward-declarations for labels that nested functions can jump to. */ mark_valid_location_for_stdc_pragma (false); while (c_parser_next_token_is_keyword (parser, RID_LABEL)) { label_loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); /* Any identifiers, including those declared as type names, are OK here. */ while (true) { tree label; if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); break; } label = declare_label (c_parser_peek_token (parser)->value); C_DECLARED_LABEL_FLAG (label) = 1; add_stmt (build_stmt (label_loc, DECL_EXPR, label)); c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; } c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } pedwarn (label_loc, OPT_Wpedantic, "ISO C forbids label declarations"); } /* We must now have at least one statement, label or declaration. */ if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { mark_valid_location_for_stdc_pragma (save_valid_for_pragma); c_parser_error (parser, "expected declaration or statement"); c_parser_consume_token (parser); return; } while (c_parser_next_token_is_not (parser, CPP_CLOSE_BRACE)) { location_t loc = c_parser_peek_token (parser)->location; loc = expansion_point_location_if_in_system_header (loc); if (c_parser_next_token_is_keyword (parser, RID_CASE) || c_parser_next_token_is_keyword (parser, RID_DEFAULT) || (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_2nd_token (parser)->type == CPP_COLON)) { if (c_parser_next_token_is_keyword (parser, RID_CASE)) label_loc = c_parser_peek_2nd_token (parser)->location; else label_loc = c_parser_peek_token (parser)->location; last_label = true; last_stmt = false; mark_valid_location_for_stdc_pragma (false); c_parser_label (parser); } else if (!last_label && c_parser_next_tokens_start_declaration (parser)) { last_label = false; mark_valid_location_for_stdc_pragma (false); bool fallthru_attr_p = false; c_parser_declaration_or_fndef (parser, true, true, true, true, true, NULL, vNULL, NULL, &fallthru_attr_p); if (last_stmt && !fallthru_attr_p) pedwarn_c90 (loc, OPT_Wdeclaration_after_statement, "ISO C90 forbids mixed declarations and code"); last_stmt = fallthru_attr_p; } else if (!last_label && c_parser_next_token_is_keyword (parser, RID_EXTENSION)) { /* __extension__ can start a declaration, but is also an unary operator that can start an expression. Consume all but the last of a possible series of __extension__ to determine which. */ while (c_parser_peek_2nd_token (parser)->type == CPP_KEYWORD && (c_parser_peek_2nd_token (parser)->keyword == RID_EXTENSION)) c_parser_consume_token (parser); if (c_token_starts_declaration (c_parser_peek_2nd_token (parser))) { int ext; ext = disable_extension_diagnostics (); c_parser_consume_token (parser); last_label = false; mark_valid_location_for_stdc_pragma (false); c_parser_declaration_or_fndef (parser, true, true, true, true, true, NULL, vNULL); /* Following the old parser, __extension__ does not disable this diagnostic. */ restore_extension_diagnostics (ext); if (last_stmt) pedwarn_c90 (loc, OPT_Wdeclaration_after_statement, "ISO C90 forbids mixed declarations and code"); last_stmt = false; } else goto statement; } else if (c_parser_next_token_is (parser, CPP_PRAGMA)) { /* External pragmas, and some omp pragmas, are not associated with regular c code, and so are not to be considered statements syntactically. This ensures that the user doesn't put them places that would turn into syntax errors if the directive were ignored. */ if (c_parser_pragma (parser, last_label ? pragma_stmt : pragma_compound, NULL)) last_label = false, last_stmt = true; } else if (c_parser_next_token_is (parser, CPP_EOF)) { mark_valid_location_for_stdc_pragma (save_valid_for_pragma); c_parser_error (parser, "expected declaration or statement"); return; } else if (c_parser_next_token_is_keyword (parser, RID_ELSE)) { if (parser->in_if_block) { mark_valid_location_for_stdc_pragma (save_valid_for_pragma); error_at (loc, "expected %<}%> before %<else%>"); return; } else { error_at (loc, "%<else%> without a previous %<if%>"); c_parser_consume_token (parser); continue; } } else { statement: last_label = false; last_stmt = true; mark_valid_location_for_stdc_pragma (false); c_parser_statement_after_labels (parser, NULL); } parser->error = false; } if (last_label) error_at (label_loc, "label at end of compound statement"); c_parser_consume_token (parser); /* Restore the value we started with. */ mark_valid_location_for_stdc_pragma (save_valid_for_pragma); } /* Parse all consecutive labels. */ static void c_parser_all_labels (c_parser *parser) { while (c_parser_next_token_is_keyword (parser, RID_CASE) || c_parser_next_token_is_keyword (parser, RID_DEFAULT) || (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_2nd_token (parser)->type == CPP_COLON)) c_parser_label (parser); } /* Parse a label (C90 6.6.1, C99 6.8.1, C11 6.8.1). label: identifier : attributes[opt] case constant-expression : default : GNU extensions: label: case constant-expression ... constant-expression : The use of attributes on labels is a GNU extension. The syntax in GNU C accepts any expressions without commas, non-constant expressions being rejected later. */ static void c_parser_label (c_parser *parser) { location_t loc1 = c_parser_peek_token (parser)->location; tree label = NULL_TREE; /* Remember whether this case or a user-defined label is allowed to fall through to. */ bool fallthrough_p = c_parser_peek_token (parser)->flags & PREV_FALLTHROUGH; if (c_parser_next_token_is_keyword (parser, RID_CASE)) { tree exp1, exp2; c_parser_consume_token (parser); exp1 = c_parser_expr_no_commas (parser, NULL).value; if (c_parser_next_token_is (parser, CPP_COLON)) { c_parser_consume_token (parser); label = do_case (loc1, exp1, NULL_TREE); } else if (c_parser_next_token_is (parser, CPP_ELLIPSIS)) { c_parser_consume_token (parser); exp2 = c_parser_expr_no_commas (parser, NULL).value; if (c_parser_require (parser, CPP_COLON, "expected %<:%>")) label = do_case (loc1, exp1, exp2); } else c_parser_error (parser, "expected %<:%> or %<...%>"); } else if (c_parser_next_token_is_keyword (parser, RID_DEFAULT)) { c_parser_consume_token (parser); if (c_parser_require (parser, CPP_COLON, "expected %<:%>")) label = do_case (loc1, NULL_TREE, NULL_TREE); } else { tree name = c_parser_peek_token (parser)->value; tree tlab; tree attrs; location_t loc2 = c_parser_peek_token (parser)->location; gcc_assert (c_parser_next_token_is (parser, CPP_NAME)); c_parser_consume_token (parser); gcc_assert (c_parser_next_token_is (parser, CPP_COLON)); c_parser_consume_token (parser); attrs = c_parser_attributes (parser); tlab = define_label (loc2, name); if (tlab) { decl_attributes (&tlab, attrs, 0); label = add_stmt (build_stmt (loc1, LABEL_EXPR, tlab)); } } if (label) { if (TREE_CODE (label) == LABEL_EXPR) FALLTHROUGH_LABEL_P (LABEL_EXPR_LABEL (label)) = fallthrough_p; else FALLTHROUGH_LABEL_P (CASE_LABEL (label)) = fallthrough_p; /* Allow '__attribute__((fallthrough));'. */ if (c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) { location_t loc = c_parser_peek_token (parser)->location; tree attrs = c_parser_attributes (parser); if (attribute_fallthrough_p (attrs)) { if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { tree fn = build_call_expr_internal_loc (loc, IFN_FALLTHROUGH, void_type_node, 0); add_stmt (fn); } else warning_at (loc, OPT_Wattributes, "%<fallthrough%> attribute " "not followed by %<;%>"); } else if (attrs != NULL_TREE) warning_at (loc, OPT_Wattributes, "only attribute %<fallthrough%>" " can be applied to a null statement"); } if (c_parser_next_tokens_start_declaration (parser)) { error_at (c_parser_peek_token (parser)->location, "a label can only be part of a statement and " "a declaration is not a statement"); c_parser_declaration_or_fndef (parser, /*fndef_ok*/ false, /*static_assert_ok*/ true, /*empty_ok*/ true, /*nested*/ true, /*start_attr_ok*/ true, NULL, vNULL); } } } /* Parse a statement (C90 6.6, C99 6.8, C11 6.8). statement: labeled-statement compound-statement expression-statement selection-statement iteration-statement jump-statement labeled-statement: label statement expression-statement: expression[opt] ; selection-statement: if-statement switch-statement iteration-statement: while-statement do-statement for-statement jump-statement: goto identifier ; continue ; break ; return expression[opt] ; GNU extensions: statement: asm-statement jump-statement: goto * expression ; expression-statement: attributes ; Objective-C: statement: objc-throw-statement objc-try-catch-statement objc-synchronized-statement objc-throw-statement: @throw expression ; @throw ; OpenACC: statement: openacc-construct openacc-construct: parallel-construct kernels-construct data-construct loop-construct parallel-construct: parallel-directive structured-block kernels-construct: kernels-directive structured-block data-construct: data-directive structured-block loop-construct: loop-directive structured-block OpenMP: statement: openmp-construct openmp-construct: parallel-construct for-construct simd-construct for-simd-construct sections-construct single-construct parallel-for-construct parallel-for-simd-construct parallel-sections-construct master-construct critical-construct atomic-construct ordered-construct parallel-construct: parallel-directive structured-block for-construct: for-directive iteration-statement simd-construct: simd-directive iteration-statements for-simd-construct: for-simd-directive iteration-statements sections-construct: sections-directive section-scope single-construct: single-directive structured-block parallel-for-construct: parallel-for-directive iteration-statement parallel-for-simd-construct: parallel-for-simd-directive iteration-statement parallel-sections-construct: parallel-sections-directive section-scope master-construct: master-directive structured-block critical-construct: critical-directive structured-block atomic-construct: atomic-directive expression-statement ordered-construct: ordered-directive structured-block Transactional Memory: statement: transaction-statement transaction-cancel-statement IF_P is used to track whether there's a (possibly labeled) if statement which is not enclosed in braces and has an else clause. This is used to implement -Wparentheses. */ static void c_parser_statement (c_parser *parser, bool *if_p, location_t *loc_after_labels) { c_parser_all_labels (parser); if (loc_after_labels) *loc_after_labels = c_parser_peek_token (parser)->location; c_parser_statement_after_labels (parser, if_p, NULL); } /* Parse a statement, other than a labeled statement. CHAIN is a vector of if-else-if conditions. IF_P is used to track whether there's a (possibly labeled) if statement which is not enclosed in braces and has an else clause. This is used to implement -Wparentheses. */ static void c_parser_statement_after_labels (c_parser *parser, bool *if_p, vec<tree> *chain) { location_t loc = c_parser_peek_token (parser)->location; tree stmt = NULL_TREE; bool in_if_block = parser->in_if_block; parser->in_if_block = false; if (if_p != NULL) *if_p = false; if (c_parser_peek_token (parser)->type != CPP_OPEN_BRACE) add_debug_begin_stmt (loc); switch (c_parser_peek_token (parser)->type) { case CPP_OPEN_BRACE: add_stmt (c_parser_compound_statement (parser)); break; case CPP_KEYWORD: switch (c_parser_peek_token (parser)->keyword) { case RID_IF: c_parser_if_statement (parser, if_p, chain); break; case RID_SWITCH: c_parser_switch_statement (parser, if_p); break; case RID_WHILE: c_parser_while_statement (parser, false, 0, if_p); break; case RID_DO: c_parser_do_statement (parser, 0, false); break; case RID_FOR: c_parser_for_statement (parser, false, 0, if_p); break; case RID_GOTO: c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_NAME)) { stmt = c_finish_goto_label (loc, c_parser_peek_token (parser)->value); c_parser_consume_token (parser); } else if (c_parser_next_token_is (parser, CPP_MULT)) { struct c_expr val; c_parser_consume_token (parser); val = c_parser_expression (parser); val = convert_lvalue_to_rvalue (loc, val, false, true); stmt = c_finish_goto_ptr (loc, val.value); } else c_parser_error (parser, "expected identifier or %<*%>"); goto expect_semicolon; case RID_CONTINUE: c_parser_consume_token (parser); stmt = c_finish_bc_stmt (loc, &c_cont_label, false); goto expect_semicolon; case RID_BREAK: c_parser_consume_token (parser); stmt = c_finish_bc_stmt (loc, &c_break_label, true); goto expect_semicolon; case RID_RETURN: c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { stmt = c_finish_return (loc, NULL_TREE, NULL_TREE); c_parser_consume_token (parser); } else { location_t xloc = c_parser_peek_token (parser)->location; struct c_expr expr = c_parser_expression_conv (parser); mark_exp_read (expr.value); stmt = c_finish_return (EXPR_LOC_OR_LOC (expr.value, xloc), expr.value, expr.original_type); goto expect_semicolon; } break; case RID_ASM: stmt = c_parser_asm_statement (parser); break; case RID_TRANSACTION_ATOMIC: case RID_TRANSACTION_RELAXED: stmt = c_parser_transaction (parser, c_parser_peek_token (parser)->keyword); break; case RID_TRANSACTION_CANCEL: stmt = c_parser_transaction_cancel (parser); goto expect_semicolon; case RID_AT_THROW: gcc_assert (c_dialect_objc ()); c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { stmt = objc_build_throw_stmt (loc, NULL_TREE); c_parser_consume_token (parser); } else { struct c_expr expr = c_parser_expression (parser); expr = convert_lvalue_to_rvalue (loc, expr, false, false); expr.value = c_fully_fold (expr.value, false, NULL); stmt = objc_build_throw_stmt (loc, expr.value); goto expect_semicolon; } break; case RID_AT_TRY: gcc_assert (c_dialect_objc ()); c_parser_objc_try_catch_finally_statement (parser); break; case RID_AT_SYNCHRONIZED: gcc_assert (c_dialect_objc ()); c_parser_objc_synchronized_statement (parser); break; case RID_ATTRIBUTE: { /* Allow '__attribute__((fallthrough));'. */ tree attrs = c_parser_attributes (parser); if (attribute_fallthrough_p (attrs)) { if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { tree fn = build_call_expr_internal_loc (loc, IFN_FALLTHROUGH, void_type_node, 0); add_stmt (fn); /* Eat the ';'. */ c_parser_consume_token (parser); } else warning_at (loc, OPT_Wattributes, "%<fallthrough%> attribute not followed " "by %<;%>"); } else if (attrs != NULL_TREE) warning_at (loc, OPT_Wattributes, "only attribute %<fallthrough%>" " can be applied to a null statement"); break; } default: goto expr_stmt; } break; case CPP_SEMICOLON: c_parser_consume_token (parser); break; case CPP_CLOSE_PAREN: case CPP_CLOSE_SQUARE: /* Avoid infinite loop in error recovery: c_parser_skip_until_found stops at a closing nesting delimiter without consuming it, but here we need to consume it to proceed further. */ c_parser_error (parser, "expected statement"); c_parser_consume_token (parser); break; case CPP_PRAGMA: c_parser_pragma (parser, pragma_stmt, if_p); break; default: expr_stmt: stmt = c_finish_expr_stmt (loc, c_parser_expression_conv (parser).value); expect_semicolon: c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); break; } /* Two cases cannot and do not have line numbers associated: If stmt is degenerate, such as "2;", then stmt is an INTEGER_CST, which cannot hold line numbers. But that's OK because the statement will either be changed to a MODIFY_EXPR during gimplification of the statement expr, or discarded. If stmt was compound, but without new variables, we will have skipped the creation of a BIND and will have a bare STATEMENT_LIST. But that's OK because (recursively) all of the component statements should already have line numbers assigned. ??? Can we discard no-op statements earlier? */ if (EXPR_LOCATION (stmt) == UNKNOWN_LOCATION) protected_set_expr_location (stmt, loc); parser->in_if_block = in_if_block; } /* Parse the condition from an if, do, while or for statements. */ static tree c_parser_condition (c_parser *parser) { location_t loc = c_parser_peek_token (parser)->location; tree cond; cond = c_parser_expression_conv (parser).value; cond = c_objc_common_truthvalue_conversion (loc, cond); cond = c_fully_fold (cond, false, NULL); if (warn_sequence_point) verify_sequence_points (cond); return cond; } /* Parse a parenthesized condition from an if, do or while statement. condition: ( expression ) */ static tree c_parser_paren_condition (c_parser *parser) { tree cond; matching_parens parens; if (!parens.require_open (parser)) return error_mark_node; cond = c_parser_condition (parser); parens.skip_until_found_close (parser); return cond; } /* Parse a statement which is a block in C99. IF_P is used to track whether there's a (possibly labeled) if statement which is not enclosed in braces and has an else clause. This is used to implement -Wparentheses. */ static tree c_parser_c99_block_statement (c_parser *parser, bool *if_p, location_t *loc_after_labels) { tree block = c_begin_compound_stmt (flag_isoc99); location_t loc = c_parser_peek_token (parser)->location; c_parser_statement (parser, if_p, loc_after_labels); return c_end_compound_stmt (loc, block, flag_isoc99); } /* Parse the body of an if statement. This is just parsing a statement but (a) it is a block in C99, (b) we track whether the body is an if statement for the sake of -Wparentheses warnings, (c) we handle an empty body specially for the sake of -Wempty-body warnings, and (d) we call parser_compound_statement directly because c_parser_statement_after_labels resets parser->in_if_block. IF_P is used to track whether there's a (possibly labeled) if statement which is not enclosed in braces and has an else clause. This is used to implement -Wparentheses. */ static tree c_parser_if_body (c_parser *parser, bool *if_p, const token_indent_info &if_tinfo) { tree block = c_begin_compound_stmt (flag_isoc99); location_t body_loc = c_parser_peek_token (parser)->location; location_t body_loc_after_labels = UNKNOWN_LOCATION; token_indent_info body_tinfo = get_token_indent_info (c_parser_peek_token (parser)); c_parser_all_labels (parser); if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { location_t loc = c_parser_peek_token (parser)->location; add_stmt (build_empty_stmt (loc)); c_parser_consume_token (parser); if (!c_parser_next_token_is_keyword (parser, RID_ELSE)) warning_at (loc, OPT_Wempty_body, "suggest braces around empty body in an %<if%> statement"); } else if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) add_stmt (c_parser_compound_statement (parser)); else { body_loc_after_labels = c_parser_peek_token (parser)->location; c_parser_statement_after_labels (parser, if_p); } token_indent_info next_tinfo = get_token_indent_info (c_parser_peek_token (parser)); warn_for_misleading_indentation (if_tinfo, body_tinfo, next_tinfo); if (body_loc_after_labels != UNKNOWN_LOCATION && next_tinfo.type != CPP_SEMICOLON) warn_for_multistatement_macros (body_loc_after_labels, next_tinfo.location, if_tinfo.location, RID_IF); return c_end_compound_stmt (body_loc, block, flag_isoc99); } /* Parse the else body of an if statement. This is just parsing a statement but (a) it is a block in C99, (b) we handle an empty body specially for the sake of -Wempty-body warnings. CHAIN is a vector of if-else-if conditions. */ static tree c_parser_else_body (c_parser *parser, const token_indent_info &else_tinfo, vec<tree> *chain) { location_t body_loc = c_parser_peek_token (parser)->location; tree block = c_begin_compound_stmt (flag_isoc99); token_indent_info body_tinfo = get_token_indent_info (c_parser_peek_token (parser)); location_t body_loc_after_labels = UNKNOWN_LOCATION; c_parser_all_labels (parser); if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { location_t loc = c_parser_peek_token (parser)->location; warning_at (loc, OPT_Wempty_body, "suggest braces around empty body in an %<else%> statement"); add_stmt (build_empty_stmt (loc)); c_parser_consume_token (parser); } else { if (!c_parser_next_token_is (parser, CPP_OPEN_BRACE)) body_loc_after_labels = c_parser_peek_token (parser)->location; c_parser_statement_after_labels (parser, NULL, chain); } token_indent_info next_tinfo = get_token_indent_info (c_parser_peek_token (parser)); warn_for_misleading_indentation (else_tinfo, body_tinfo, next_tinfo); if (body_loc_after_labels != UNKNOWN_LOCATION && next_tinfo.type != CPP_SEMICOLON) warn_for_multistatement_macros (body_loc_after_labels, next_tinfo.location, else_tinfo.location, RID_ELSE); return c_end_compound_stmt (body_loc, block, flag_isoc99); } /* We might need to reclassify any previously-lexed identifier, e.g. when we've left a for loop with an if-statement without else in the body - we might have used a wrong scope for the token. See PR67784. */ static void c_parser_maybe_reclassify_token (c_parser *parser) { if (c_parser_next_token_is (parser, CPP_NAME)) { c_token *token = c_parser_peek_token (parser); if (token->id_kind != C_ID_CLASSNAME) { tree decl = lookup_name (token->value); token->id_kind = C_ID_ID; if (decl) { if (TREE_CODE (decl) == TYPE_DECL) token->id_kind = C_ID_TYPENAME; } else if (c_dialect_objc ()) { tree objc_interface_decl = objc_is_class_name (token->value); /* Objective-C class names are in the same namespace as variables and typedefs, and hence are shadowed by local declarations. */ if (objc_interface_decl) { token->value = objc_interface_decl; token->id_kind = C_ID_CLASSNAME; } } } } } /* Parse an if statement (C90 6.6.4, C99 6.8.4, C11 6.8.4). if-statement: if ( expression ) statement if ( expression ) statement else statement CHAIN is a vector of if-else-if conditions. IF_P is used to track whether there's a (possibly labeled) if statement which is not enclosed in braces and has an else clause. This is used to implement -Wparentheses. */ static void c_parser_if_statement (c_parser *parser, bool *if_p, vec<tree> *chain) { tree block; location_t loc; tree cond; bool nested_if = false; tree first_body, second_body; bool in_if_block; gcc_assert (c_parser_next_token_is_keyword (parser, RID_IF)); token_indent_info if_tinfo = get_token_indent_info (c_parser_peek_token (parser)); c_parser_consume_token (parser); block = c_begin_compound_stmt (flag_isoc99); loc = c_parser_peek_token (parser)->location; cond = c_parser_paren_condition (parser); in_if_block = parser->in_if_block; parser->in_if_block = true; first_body = c_parser_if_body (parser, &nested_if, if_tinfo); parser->in_if_block = in_if_block; if (warn_duplicated_cond) warn_duplicated_cond_add_or_warn (EXPR_LOCATION (cond), cond, &chain); if (c_parser_next_token_is_keyword (parser, RID_ELSE)) { token_indent_info else_tinfo = get_token_indent_info (c_parser_peek_token (parser)); c_parser_consume_token (parser); if (warn_duplicated_cond) { if (c_parser_next_token_is_keyword (parser, RID_IF) && chain == NULL) { /* We've got "if (COND) else if (COND2)". Start the condition chain and add COND as the first element. */ chain = new vec<tree> (); if (!CONSTANT_CLASS_P (cond) && !TREE_SIDE_EFFECTS (cond)) chain->safe_push (cond); } else if (!c_parser_next_token_is_keyword (parser, RID_IF)) { /* This is if-else without subsequent if. Zap the condition chain; we would have already warned at this point. */ delete chain; chain = NULL; } } second_body = c_parser_else_body (parser, else_tinfo, chain); /* Set IF_P to true to indicate that this if statement has an else clause. This may trigger the Wparentheses warning below when we get back up to the parent if statement. */ if (if_p != NULL) *if_p = true; } else { second_body = NULL_TREE; /* Diagnose an ambiguous else if if-then-else is nested inside if-then. */ if (nested_if) warning_at (loc, OPT_Wdangling_else, "suggest explicit braces to avoid ambiguous %<else%>"); if (warn_duplicated_cond) { /* This if statement does not have an else clause. We don't need the condition chain anymore. */ delete chain; chain = NULL; } } c_finish_if_stmt (loc, cond, first_body, second_body); add_stmt (c_end_compound_stmt (loc, block, flag_isoc99)); c_parser_maybe_reclassify_token (parser); } /* Parse a switch statement (C90 6.6.4, C99 6.8.4, C11 6.8.4). switch-statement: switch (expression) statement */ static void c_parser_switch_statement (c_parser *parser, bool *if_p) { struct c_expr ce; tree block, expr, body, save_break; location_t switch_loc = c_parser_peek_token (parser)->location; location_t switch_cond_loc; gcc_assert (c_parser_next_token_is_keyword (parser, RID_SWITCH)); c_parser_consume_token (parser); block = c_begin_compound_stmt (flag_isoc99); bool explicit_cast_p = false; matching_parens parens; if (parens.require_open (parser)) { switch_cond_loc = c_parser_peek_token (parser)->location; if (c_parser_next_token_is (parser, CPP_OPEN_PAREN) && c_token_starts_typename (c_parser_peek_2nd_token (parser))) explicit_cast_p = true; ce = c_parser_expression (parser); ce = convert_lvalue_to_rvalue (switch_cond_loc, ce, true, false); expr = ce.value; /* ??? expr has no valid location? */ parens.skip_until_found_close (parser); } else { switch_cond_loc = UNKNOWN_LOCATION; expr = error_mark_node; ce.original_type = error_mark_node; } c_start_case (switch_loc, switch_cond_loc, expr, explicit_cast_p); save_break = c_break_label; c_break_label = NULL_TREE; location_t loc_after_labels; bool open_brace_p = c_parser_peek_token (parser)->type == CPP_OPEN_BRACE; body = c_parser_c99_block_statement (parser, if_p, &loc_after_labels); location_t next_loc = c_parser_peek_token (parser)->location; if (!open_brace_p && c_parser_peek_token (parser)->type != CPP_SEMICOLON) warn_for_multistatement_macros (loc_after_labels, next_loc, switch_loc, RID_SWITCH); if (c_break_label) { location_t here = c_parser_peek_token (parser)->location; tree t = build1 (LABEL_EXPR, void_type_node, c_break_label); SET_EXPR_LOCATION (t, here); SWITCH_BREAK_LABEL_P (c_break_label) = 1; append_to_statement_list_force (t, &body); } c_finish_case (body, ce.original_type); c_break_label = save_break; add_stmt (c_end_compound_stmt (switch_loc, block, flag_isoc99)); c_parser_maybe_reclassify_token (parser); } /* Parse a while statement (C90 6.6.5, C99 6.8.5, C11 6.8.5). while-statement: while (expression) statement IF_P is used to track whether there's a (possibly labeled) if statement which is not enclosed in braces and has an else clause. This is used to implement -Wparentheses. */ static void c_parser_while_statement (c_parser *parser, bool ivdep, unsigned short unroll, bool *if_p) { tree block, cond, body, save_break, save_cont; location_t loc; gcc_assert (c_parser_next_token_is_keyword (parser, RID_WHILE)); token_indent_info while_tinfo = get_token_indent_info (c_parser_peek_token (parser)); c_parser_consume_token (parser); block = c_begin_compound_stmt (flag_isoc99); loc = c_parser_peek_token (parser)->location; cond = c_parser_paren_condition (parser); if (ivdep && cond != error_mark_node) cond = build3 (ANNOTATE_EXPR, TREE_TYPE (cond), cond, build_int_cst (integer_type_node, annot_expr_ivdep_kind), integer_zero_node); if (unroll && cond != error_mark_node) cond = build3 (ANNOTATE_EXPR, TREE_TYPE (cond), cond, build_int_cst (integer_type_node, annot_expr_unroll_kind), build_int_cst (integer_type_node, unroll)); save_break = c_break_label; c_break_label = NULL_TREE; save_cont = c_cont_label; c_cont_label = NULL_TREE; token_indent_info body_tinfo = get_token_indent_info (c_parser_peek_token (parser)); location_t loc_after_labels; bool open_brace = c_parser_next_token_is (parser, CPP_OPEN_BRACE); body = c_parser_c99_block_statement (parser, if_p, &loc_after_labels); c_finish_loop (loc, cond, NULL, body, c_break_label, c_cont_label, true); add_stmt (c_end_compound_stmt (loc, block, flag_isoc99)); c_parser_maybe_reclassify_token (parser); token_indent_info next_tinfo = get_token_indent_info (c_parser_peek_token (parser)); warn_for_misleading_indentation (while_tinfo, body_tinfo, next_tinfo); if (next_tinfo.type != CPP_SEMICOLON && !open_brace) warn_for_multistatement_macros (loc_after_labels, next_tinfo.location, while_tinfo.location, RID_WHILE); c_break_label = save_break; c_cont_label = save_cont; } /* Parse a do statement (C90 6.6.5, C99 6.8.5, C11 6.8.5). do-statement: do statement while ( expression ) ; */ static void c_parser_do_statement (c_parser *parser, bool ivdep, unsigned short unroll) { tree block, cond, body, save_break, save_cont, new_break, new_cont; location_t loc; gcc_assert (c_parser_next_token_is_keyword (parser, RID_DO)); c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_SEMICOLON)) warning_at (c_parser_peek_token (parser)->location, OPT_Wempty_body, "suggest braces around empty body in %<do%> statement"); block = c_begin_compound_stmt (flag_isoc99); loc = c_parser_peek_token (parser)->location; save_break = c_break_label; c_break_label = NULL_TREE; save_cont = c_cont_label; c_cont_label = NULL_TREE; body = c_parser_c99_block_statement (parser, NULL); c_parser_require_keyword (parser, RID_WHILE, "expected %<while%>"); new_break = c_break_label; c_break_label = save_break; new_cont = c_cont_label; c_cont_label = save_cont; cond = c_parser_paren_condition (parser); if (ivdep && cond != error_mark_node) cond = build3 (ANNOTATE_EXPR, TREE_TYPE (cond), cond, build_int_cst (integer_type_node, annot_expr_ivdep_kind), integer_zero_node); if (unroll && cond != error_mark_node) cond = build3 (ANNOTATE_EXPR, TREE_TYPE (cond), cond, build_int_cst (integer_type_node, annot_expr_unroll_kind), build_int_cst (integer_type_node, unroll)); if (!c_parser_require (parser, CPP_SEMICOLON, "expected %<;%>")) c_parser_skip_to_end_of_block_or_statement (parser); c_finish_loop (loc, cond, NULL, body, new_break, new_cont, false); add_stmt (c_end_compound_stmt (loc, block, flag_isoc99)); } /* Parse a for statement (C90 6.6.5, C99 6.8.5, C11 6.8.5). for-statement: for ( expression[opt] ; expression[opt] ; expression[opt] ) statement for ( nested-declaration expression[opt] ; expression[opt] ) statement The form with a declaration is new in C99. ??? In accordance with the old parser, the declaration may be a nested function, which is then rejected in check_for_loop_decls, but does it make any sense for this to be included in the grammar? Note in particular that the nested function does not include a trailing ';', whereas the "declaration" production includes one. Also, can we reject bad declarations earlier and cheaper than check_for_loop_decls? In Objective-C, there are two additional variants: foreach-statement: for ( expression in expresssion ) statement for ( declaration in expression ) statement This is inconsistent with C, because the second variant is allowed even if c99 is not enabled. The rest of the comment documents these Objective-C foreach-statement. Here is the canonical example of the first variant: for (object in array) { do something with object } we call the first expression ("object") the "object_expression" and the second expression ("array") the "collection_expression". object_expression must be an lvalue of type "id" (a generic Objective-C object) because the loop works by assigning to object_expression the various objects from the collection_expression. collection_expression must evaluate to something of type "id" which responds to the method countByEnumeratingWithState:objects:count:. The canonical example of the second variant is: for (id object in array) { do something with object } which is completely equivalent to { id object; for (object in array) { do something with object } } Note that initizializing 'object' in some way (eg, "for ((object = xxx) in array) { do something with object }") is possibly technically valid, but completely pointless as 'object' will be assigned to something else as soon as the loop starts. We should most likely reject it (TODO). The beginning of the Objective-C foreach-statement looks exactly like the beginning of the for-statement, and we can tell it is a foreach-statement only because the initial declaration or expression is terminated by 'in' instead of ';'. IF_P is used to track whether there's a (possibly labeled) if statement which is not enclosed in braces and has an else clause. This is used to implement -Wparentheses. */ static void c_parser_for_statement (c_parser *parser, bool ivdep, unsigned short unroll, bool *if_p) { tree block, cond, incr, save_break, save_cont, body; /* The following are only used when parsing an ObjC foreach statement. */ tree object_expression; /* Silence the bogus uninitialized warning. */ tree collection_expression = NULL; location_t loc = c_parser_peek_token (parser)->location; location_t for_loc = c_parser_peek_token (parser)->location; bool is_foreach_statement = false; gcc_assert (c_parser_next_token_is_keyword (parser, RID_FOR)); token_indent_info for_tinfo = get_token_indent_info (c_parser_peek_token (parser)); c_parser_consume_token (parser); /* Open a compound statement in Objective-C as well, just in case this is as foreach expression. */ block = c_begin_compound_stmt (flag_isoc99 || c_dialect_objc ()); cond = error_mark_node; incr = error_mark_node; matching_parens parens; if (parens.require_open (parser)) { /* Parse the initialization declaration or expression. */ object_expression = error_mark_node; parser->objc_could_be_foreach_context = c_dialect_objc (); if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { parser->objc_could_be_foreach_context = false; c_parser_consume_token (parser); c_finish_expr_stmt (loc, NULL_TREE); } else if (c_parser_next_tokens_start_declaration (parser)) { c_parser_declaration_or_fndef (parser, true, true, true, true, true, &object_expression, vNULL); parser->objc_could_be_foreach_context = false; if (c_parser_next_token_is_keyword (parser, RID_IN)) { c_parser_consume_token (parser); is_foreach_statement = true; if (check_for_loop_decls (for_loc, true) == NULL_TREE) c_parser_error (parser, "multiple iterating variables in fast enumeration"); } else check_for_loop_decls (for_loc, flag_isoc99); } else if (c_parser_next_token_is_keyword (parser, RID_EXTENSION)) { /* __extension__ can start a declaration, but is also an unary operator that can start an expression. Consume all but the last of a possible series of __extension__ to determine which. */ while (c_parser_peek_2nd_token (parser)->type == CPP_KEYWORD && (c_parser_peek_2nd_token (parser)->keyword == RID_EXTENSION)) c_parser_consume_token (parser); if (c_token_starts_declaration (c_parser_peek_2nd_token (parser))) { int ext; ext = disable_extension_diagnostics (); c_parser_consume_token (parser); c_parser_declaration_or_fndef (parser, true, true, true, true, true, &object_expression, vNULL); parser->objc_could_be_foreach_context = false; restore_extension_diagnostics (ext); if (c_parser_next_token_is_keyword (parser, RID_IN)) { c_parser_consume_token (parser); is_foreach_statement = true; if (check_for_loop_decls (for_loc, true) == NULL_TREE) c_parser_error (parser, "multiple iterating variables in fast enumeration"); } else check_for_loop_decls (for_loc, flag_isoc99); } else goto init_expr; } else { init_expr: { struct c_expr ce; tree init_expression; ce = c_parser_expression (parser); init_expression = ce.value; parser->objc_could_be_foreach_context = false; if (c_parser_next_token_is_keyword (parser, RID_IN)) { c_parser_consume_token (parser); is_foreach_statement = true; if (! lvalue_p (init_expression)) c_parser_error (parser, "invalid iterating variable in fast enumeration"); object_expression = c_fully_fold (init_expression, false, NULL); } else { ce = convert_lvalue_to_rvalue (loc, ce, true, false); init_expression = ce.value; c_finish_expr_stmt (loc, init_expression); c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } } } /* Parse the loop condition. In the case of a foreach statement, there is no loop condition. */ gcc_assert (!parser->objc_could_be_foreach_context); if (!is_foreach_statement) { if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { if (ivdep) { c_parser_error (parser, "missing loop condition in loop with " "%<GCC ivdep%> pragma"); cond = error_mark_node; } else if (unroll) { c_parser_error (parser, "missing loop condition in loop with " "%<GCC unroll%> pragma"); cond = error_mark_node; } else { c_parser_consume_token (parser); cond = NULL_TREE; } } else { cond = c_parser_condition (parser); c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } if (ivdep && cond != error_mark_node) cond = build3 (ANNOTATE_EXPR, TREE_TYPE (cond), cond, build_int_cst (integer_type_node, annot_expr_ivdep_kind), integer_zero_node); if (unroll && cond != error_mark_node) cond = build3 (ANNOTATE_EXPR, TREE_TYPE (cond), cond, build_int_cst (integer_type_node, annot_expr_unroll_kind), build_int_cst (integer_type_node, unroll)); } /* Parse the increment expression (the third expression in a for-statement). In the case of a foreach-statement, this is the expression that follows the 'in'. */ if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { if (is_foreach_statement) { c_parser_error (parser, "missing collection in fast enumeration"); collection_expression = error_mark_node; } else incr = c_process_expr_stmt (loc, NULL_TREE); } else { if (is_foreach_statement) collection_expression = c_fully_fold (c_parser_expression (parser).value, false, NULL); else { struct c_expr ce = c_parser_expression (parser); ce = convert_lvalue_to_rvalue (loc, ce, true, false); incr = c_process_expr_stmt (loc, ce.value); } } parens.skip_until_found_close (parser); } save_break = c_break_label; c_break_label = NULL_TREE; save_cont = c_cont_label; c_cont_label = NULL_TREE; token_indent_info body_tinfo = get_token_indent_info (c_parser_peek_token (parser)); location_t loc_after_labels; bool open_brace = c_parser_next_token_is (parser, CPP_OPEN_BRACE); body = c_parser_c99_block_statement (parser, if_p, &loc_after_labels); if (is_foreach_statement) objc_finish_foreach_loop (loc, object_expression, collection_expression, body, c_break_label, c_cont_label); else c_finish_loop (loc, cond, incr, body, c_break_label, c_cont_label, true); add_stmt (c_end_compound_stmt (loc, block, flag_isoc99 || c_dialect_objc ())); c_parser_maybe_reclassify_token (parser); token_indent_info next_tinfo = get_token_indent_info (c_parser_peek_token (parser)); warn_for_misleading_indentation (for_tinfo, body_tinfo, next_tinfo); if (next_tinfo.type != CPP_SEMICOLON && !open_brace) warn_for_multistatement_macros (loc_after_labels, next_tinfo.location, for_tinfo.location, RID_FOR); c_break_label = save_break; c_cont_label = save_cont; } /* Parse an asm statement, a GNU extension. This is a full-blown asm statement with inputs, outputs, clobbers, and volatile, inline, and goto tags allowed. asm-qualifier: volatile inline goto asm-qualifier-list: asm-qualifier-list asm-qualifier asm-qualifier asm-statement: asm asm-qualifier-list[opt] ( asm-argument ) ; asm-argument: asm-string-literal asm-string-literal : asm-operands[opt] asm-string-literal : asm-operands[opt] : asm-operands[opt] asm-string-literal : asm-operands[opt] : asm-operands[opt] \ : asm-clobbers[opt] asm-string-literal : : asm-operands[opt] : asm-clobbers[opt] \ : asm-goto-operands The form with asm-goto-operands is valid if and only if the asm-qualifier-list contains goto, and is the only allowed form in that case. Duplicate asm-qualifiers are not allowed. */ static tree c_parser_asm_statement (c_parser *parser) { tree str, outputs, inputs, clobbers, labels, ret; bool simple; location_t asm_loc = c_parser_peek_token (parser)->location; int section, nsections; gcc_assert (c_parser_next_token_is_keyword (parser, RID_ASM)); c_parser_consume_token (parser); /* Handle the asm-qualifier-list. */ location_t volatile_loc = UNKNOWN_LOCATION; location_t inline_loc = UNKNOWN_LOCATION; location_t goto_loc = UNKNOWN_LOCATION; for (;;) { c_token *token = c_parser_peek_token (parser); location_t loc = token->location; switch (token->keyword) { case RID_VOLATILE: if (volatile_loc) { error_at (loc, "duplicate asm qualifier %qE", token->value); inform (volatile_loc, "first seen here"); } else volatile_loc = loc; c_parser_consume_token (parser); continue; case RID_INLINE: if (inline_loc) { error_at (loc, "duplicate asm qualifier %qE", token->value); inform (inline_loc, "first seen here"); } else inline_loc = loc; c_parser_consume_token (parser); continue; case RID_GOTO: if (goto_loc) { error_at (loc, "duplicate asm qualifier %qE", token->value); inform (goto_loc, "first seen here"); } else goto_loc = loc; c_parser_consume_token (parser); continue; case RID_CONST: case RID_RESTRICT: warning_at (loc, 0, "%qE is not an asm qualifier", token->value); c_parser_consume_token (parser); continue; default: break; } break; } bool is_volatile = (volatile_loc != UNKNOWN_LOCATION); bool is_inline = (inline_loc != UNKNOWN_LOCATION); bool is_goto = (goto_loc != UNKNOWN_LOCATION); /* ??? Follow the C++ parser rather than using the lex_untranslated_string kludge. */ parser->lex_untranslated_string = true; ret = NULL; matching_parens parens; if (!parens.require_open (parser)) goto error; str = c_parser_asm_string_literal (parser); if (str == NULL_TREE) goto error_close_paren; simple = true; outputs = NULL_TREE; inputs = NULL_TREE; clobbers = NULL_TREE; labels = NULL_TREE; if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN) && !is_goto) goto done_asm; /* Parse each colon-delimited section of operands. */ nsections = 3 + is_goto; for (section = 0; section < nsections; ++section) { if (!c_parser_require (parser, CPP_COLON, is_goto ? G_("expected %<:%>") : G_("expected %<:%> or %<)%>"), UNKNOWN_LOCATION, is_goto)) goto error_close_paren; /* Once past any colon, we're no longer a simple asm. */ simple = false; if ((!c_parser_next_token_is (parser, CPP_COLON) && !c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) || section == 3) switch (section) { case 0: /* For asm goto, we don't allow output operands, but reserve the slot for a future extension that does allow them. */ if (!is_goto) outputs = c_parser_asm_operands (parser); break; case 1: inputs = c_parser_asm_operands (parser); break; case 2: clobbers = c_parser_asm_clobbers (parser); break; case 3: labels = c_parser_asm_goto_operands (parser); break; default: gcc_unreachable (); } if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN) && !is_goto) goto done_asm; } done_asm: if (!parens.require_close (parser)) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); goto error; } if (!c_parser_require (parser, CPP_SEMICOLON, "expected %<;%>")) c_parser_skip_to_end_of_block_or_statement (parser); ret = build_asm_stmt (is_volatile, build_asm_expr (asm_loc, str, outputs, inputs, clobbers, labels, simple, is_inline)); error: parser->lex_untranslated_string = false; return ret; error_close_paren: c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); goto error; } /* Parse asm operands, a GNU extension. asm-operands: asm-operand asm-operands , asm-operand asm-operand: asm-string-literal ( expression ) [ identifier ] asm-string-literal ( expression ) */ static tree c_parser_asm_operands (c_parser *parser) { tree list = NULL_TREE; while (true) { tree name, str; struct c_expr expr; if (c_parser_next_token_is (parser, CPP_OPEN_SQUARE)) { c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_NAME)) { tree id = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); name = build_string (IDENTIFIER_LENGTH (id), IDENTIFIER_POINTER (id)); } else { c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, NULL); return NULL_TREE; } c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, "expected %<]%>"); } else name = NULL_TREE; str = c_parser_asm_string_literal (parser); if (str == NULL_TREE) return NULL_TREE; parser->lex_untranslated_string = false; matching_parens parens; if (!parens.require_open (parser)) { parser->lex_untranslated_string = true; return NULL_TREE; } expr = c_parser_expression (parser); mark_exp_read (expr.value); parser->lex_untranslated_string = true; if (!parens.require_close (parser)) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return NULL_TREE; } list = chainon (list, build_tree_list (build_tree_list (name, str), expr.value)); if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; } return list; } /* Parse asm clobbers, a GNU extension. asm-clobbers: asm-string-literal asm-clobbers , asm-string-literal */ static tree c_parser_asm_clobbers (c_parser *parser) { tree list = NULL_TREE; while (true) { tree str = c_parser_asm_string_literal (parser); if (str) list = tree_cons (NULL_TREE, str, list); else return NULL_TREE; if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; } return list; } /* Parse asm goto labels, a GNU extension. asm-goto-operands: identifier asm-goto-operands , identifier */ static tree c_parser_asm_goto_operands (c_parser *parser) { tree list = NULL_TREE; while (true) { tree name, label; if (c_parser_next_token_is (parser, CPP_NAME)) { c_token *tok = c_parser_peek_token (parser); name = tok->value; label = lookup_label_for_goto (tok->location, name); c_parser_consume_token (parser); TREE_USED (label) = 1; } else { c_parser_error (parser, "expected identifier"); return NULL_TREE; } name = build_string (IDENTIFIER_LENGTH (name), IDENTIFIER_POINTER (name)); list = tree_cons (name, label, list); if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else return nreverse (list); } } /* Parse an expression other than a compound expression; that is, an assignment expression (C90 6.3.16, C99 6.5.16, C11 6.5.16). If AFTER is not NULL then it is an Objective-C message expression which is the primary-expression starting the expression as an initializer. assignment-expression: conditional-expression unary-expression assignment-operator assignment-expression assignment-operator: one of = *= /= %= += -= <<= >>= &= ^= |= In GNU C we accept any conditional expression on the LHS and diagnose the invalid lvalue rather than producing a syntax error. */ static struct c_expr c_parser_expr_no_commas (c_parser *parser, struct c_expr *after, tree omp_atomic_lhs) { struct c_expr lhs, rhs, ret; enum tree_code code; location_t op_location, exp_location; gcc_assert (!after || c_dialect_objc ()); lhs = c_parser_conditional_expression (parser, after, omp_atomic_lhs); op_location = c_parser_peek_token (parser)->location; switch (c_parser_peek_token (parser)->type) { case CPP_EQ: code = NOP_EXPR; break; case CPP_MULT_EQ: code = MULT_EXPR; break; case CPP_DIV_EQ: code = TRUNC_DIV_EXPR; break; case CPP_MOD_EQ: code = TRUNC_MOD_EXPR; break; case CPP_PLUS_EQ: code = PLUS_EXPR; break; case CPP_MINUS_EQ: code = MINUS_EXPR; break; case CPP_LSHIFT_EQ: code = LSHIFT_EXPR; break; case CPP_RSHIFT_EQ: code = RSHIFT_EXPR; break; case CPP_AND_EQ: code = BIT_AND_EXPR; break; case CPP_XOR_EQ: code = BIT_XOR_EXPR; break; case CPP_OR_EQ: code = BIT_IOR_EXPR; break; default: return lhs; } c_parser_consume_token (parser); exp_location = c_parser_peek_token (parser)->location; rhs = c_parser_expr_no_commas (parser, NULL); rhs = convert_lvalue_to_rvalue (exp_location, rhs, true, true); ret.value = build_modify_expr (op_location, lhs.value, lhs.original_type, code, exp_location, rhs.value, rhs.original_type); set_c_expr_source_range (&ret, lhs.get_start (), rhs.get_finish ()); if (code == NOP_EXPR) ret.original_code = MODIFY_EXPR; else { TREE_NO_WARNING (ret.value) = 1; ret.original_code = ERROR_MARK; } ret.original_type = NULL; return ret; } /* Parse a conditional expression (C90 6.3.15, C99 6.5.15, C11 6.5.15). If AFTER is not NULL then it is an Objective-C message expression which is the primary-expression starting the expression as an initializer. conditional-expression: logical-OR-expression logical-OR-expression ? expression : conditional-expression GNU extensions: conditional-expression: logical-OR-expression ? : conditional-expression */ static struct c_expr c_parser_conditional_expression (c_parser *parser, struct c_expr *after, tree omp_atomic_lhs) { struct c_expr cond, exp1, exp2, ret; location_t start, cond_loc, colon_loc; gcc_assert (!after || c_dialect_objc ()); cond = c_parser_binary_expression (parser, after, omp_atomic_lhs); if (c_parser_next_token_is_not (parser, CPP_QUERY)) return cond; if (cond.value != error_mark_node) start = cond.get_start (); else start = UNKNOWN_LOCATION; cond_loc = c_parser_peek_token (parser)->location; cond = convert_lvalue_to_rvalue (cond_loc, cond, true, true); c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_COLON)) { tree eptype = NULL_TREE; location_t middle_loc = c_parser_peek_token (parser)->location; pedwarn (middle_loc, OPT_Wpedantic, "ISO C forbids omitting the middle term of a ?: expression"); if (TREE_CODE (cond.value) == EXCESS_PRECISION_EXPR) { eptype = TREE_TYPE (cond.value); cond.value = TREE_OPERAND (cond.value, 0); } tree e = cond.value; while (TREE_CODE (e) == COMPOUND_EXPR) e = TREE_OPERAND (e, 1); warn_for_omitted_condop (middle_loc, e); /* Make sure first operand is calculated only once. */ exp1.value = save_expr (default_conversion (cond.value)); if (eptype) exp1.value = build1 (EXCESS_PRECISION_EXPR, eptype, exp1.value); exp1.original_type = NULL; exp1.src_range = cond.src_range; cond.value = c_objc_common_truthvalue_conversion (cond_loc, exp1.value); c_inhibit_evaluation_warnings += cond.value == truthvalue_true_node; } else { cond.value = c_objc_common_truthvalue_conversion (cond_loc, default_conversion (cond.value)); c_inhibit_evaluation_warnings += cond.value == truthvalue_false_node; exp1 = c_parser_expression_conv (parser); mark_exp_read (exp1.value); c_inhibit_evaluation_warnings += ((cond.value == truthvalue_true_node) - (cond.value == truthvalue_false_node)); } colon_loc = c_parser_peek_token (parser)->location; if (!c_parser_require (parser, CPP_COLON, "expected %<:%>")) { c_inhibit_evaluation_warnings -= cond.value == truthvalue_true_node; ret.set_error (); ret.original_code = ERROR_MARK; ret.original_type = NULL; return ret; } { location_t exp2_loc = c_parser_peek_token (parser)->location; exp2 = c_parser_conditional_expression (parser, NULL, NULL_TREE); exp2 = convert_lvalue_to_rvalue (exp2_loc, exp2, true, true); } c_inhibit_evaluation_warnings -= cond.value == truthvalue_true_node; location_t loc1 = make_location (exp1.get_start (), exp1.src_range); location_t loc2 = make_location (exp2.get_start (), exp2.src_range); ret.value = build_conditional_expr (colon_loc, cond.value, cond.original_code == C_MAYBE_CONST_EXPR, exp1.value, exp1.original_type, loc1, exp2.value, exp2.original_type, loc2); ret.original_code = ERROR_MARK; if (exp1.value == error_mark_node || exp2.value == error_mark_node) ret.original_type = NULL; else { tree t1, t2; /* If both sides are enum type, the default conversion will have made the type of the result be an integer type. We want to remember the enum types we started with. */ t1 = exp1.original_type ? exp1.original_type : TREE_TYPE (exp1.value); t2 = exp2.original_type ? exp2.original_type : TREE_TYPE (exp2.value); ret.original_type = ((t1 != error_mark_node && t2 != error_mark_node && (TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))) ? t1 : NULL); } set_c_expr_source_range (&ret, start, exp2.get_finish ()); return ret; } /* Parse a binary expression; that is, a logical-OR-expression (C90 6.3.5-6.3.14, C99 6.5.5-6.5.14, C11 6.5.5-6.5.14). If AFTER is not NULL then it is an Objective-C message expression which is the primary-expression starting the expression as an initializer. OMP_ATOMIC_LHS is NULL, unless parsing OpenMP #pragma omp atomic, when it should be the unfolded lhs. In a valid OpenMP source, one of the operands of the toplevel binary expression must be equal to it. In that case, just return a build2 created binary operation rather than result of parser_build_binary_op. multiplicative-expression: cast-expression multiplicative-expression * cast-expression multiplicative-expression / cast-expression multiplicative-expression % cast-expression additive-expression: multiplicative-expression additive-expression + multiplicative-expression additive-expression - multiplicative-expression shift-expression: additive-expression shift-expression << additive-expression shift-expression >> additive-expression relational-expression: shift-expression relational-expression < shift-expression relational-expression > shift-expression relational-expression <= shift-expression relational-expression >= shift-expression equality-expression: relational-expression equality-expression == relational-expression equality-expression != relational-expression AND-expression: equality-expression AND-expression & equality-expression exclusive-OR-expression: AND-expression exclusive-OR-expression ^ AND-expression inclusive-OR-expression: exclusive-OR-expression inclusive-OR-expression | exclusive-OR-expression logical-AND-expression: inclusive-OR-expression logical-AND-expression && inclusive-OR-expression logical-OR-expression: logical-AND-expression logical-OR-expression || logical-AND-expression */ static struct c_expr c_parser_binary_expression (c_parser *parser, struct c_expr *after, tree omp_atomic_lhs) { /* A binary expression is parsed using operator-precedence parsing, with the operands being cast expressions. All the binary operators are left-associative. Thus a binary expression is of form: E0 op1 E1 op2 E2 ... which we represent on a stack. On the stack, the precedence levels are strictly increasing. When a new operator is encountered of higher precedence than that at the top of the stack, it is pushed; its LHS is the top expression, and its RHS is everything parsed until it is popped. When a new operator is encountered with precedence less than or equal to that at the top of the stack, triples E[i-1] op[i] E[i] are popped and replaced by the result of the operation until the operator at the top of the stack has lower precedence than the new operator or there is only one element on the stack; then the top expression is the LHS of the new operator. In the case of logical AND and OR expressions, we also need to adjust c_inhibit_evaluation_warnings as appropriate when the operators are pushed and popped. */ struct { /* The expression at this stack level. */ struct c_expr expr; /* The precedence of the operator on its left, PREC_NONE at the bottom of the stack. */ enum c_parser_prec prec; /* The operation on its left. */ enum tree_code op; /* The source location of this operation. */ location_t loc; /* The sizeof argument if expr.original_code == SIZEOF_EXPR. */ tree sizeof_arg; } stack[NUM_PRECS]; int sp; /* Location of the binary operator. */ location_t binary_loc = UNKNOWN_LOCATION; /* Quiet warning. */ #define POP \ do { \ switch (stack[sp].op) \ { \ case TRUTH_ANDIF_EXPR: \ c_inhibit_evaluation_warnings -= (stack[sp - 1].expr.value \ == truthvalue_false_node); \ break; \ case TRUTH_ORIF_EXPR: \ c_inhibit_evaluation_warnings -= (stack[sp - 1].expr.value \ == truthvalue_true_node); \ break; \ case TRUNC_DIV_EXPR: \ if (stack[sp - 1].expr.original_code == SIZEOF_EXPR \ && stack[sp].expr.original_code == SIZEOF_EXPR) \ { \ tree type0 = stack[sp - 1].sizeof_arg; \ tree type1 = stack[sp].sizeof_arg; \ tree first_arg = type0; \ if (!TYPE_P (type0)) \ type0 = TREE_TYPE (type0); \ if (!TYPE_P (type1)) \ type1 = TREE_TYPE (type1); \ if (POINTER_TYPE_P (type0) \ && comptypes (TREE_TYPE (type0), type1) \ && !(TREE_CODE (first_arg) == PARM_DECL \ && C_ARRAY_PARAMETER (first_arg) \ && warn_sizeof_array_argument)) \ if (warning_at (stack[sp].loc, OPT_Wsizeof_pointer_div, \ "division %<sizeof (%T) / sizeof (%T)%> does " \ "not compute the number of array elements", \ type0, type1)) \ if (DECL_P (first_arg)) \ inform (DECL_SOURCE_LOCATION (first_arg), \ "first %<sizeof%> operand was declared here"); \ } \ break; \ default: \ break; \ } \ stack[sp - 1].expr \ = convert_lvalue_to_rvalue (stack[sp - 1].loc, \ stack[sp - 1].expr, true, true); \ stack[sp].expr \ = convert_lvalue_to_rvalue (stack[sp].loc, \ stack[sp].expr, true, true); \ if (__builtin_expect (omp_atomic_lhs != NULL_TREE, 0) && sp == 1 \ && c_parser_peek_token (parser)->type == CPP_SEMICOLON \ && ((1 << stack[sp].prec) \ & ((1 << PREC_BITOR) | (1 << PREC_BITXOR) | (1 << PREC_BITAND) \ | (1 << PREC_SHIFT) | (1 << PREC_ADD) | (1 << PREC_MULT))) \ && stack[sp].op != TRUNC_MOD_EXPR \ && stack[0].expr.value != error_mark_node \ && stack[1].expr.value != error_mark_node \ && (c_tree_equal (stack[0].expr.value, omp_atomic_lhs) \ || c_tree_equal (stack[1].expr.value, omp_atomic_lhs))) \ stack[0].expr.value \ = build2 (stack[1].op, TREE_TYPE (stack[0].expr.value), \ stack[0].expr.value, stack[1].expr.value); \ else \ stack[sp - 1].expr = parser_build_binary_op (stack[sp].loc, \ stack[sp].op, \ stack[sp - 1].expr, \ stack[sp].expr); \ sp--; \ } while (0) gcc_assert (!after || c_dialect_objc ()); stack[0].loc = c_parser_peek_token (parser)->location; stack[0].expr = c_parser_cast_expression (parser, after); stack[0].prec = PREC_NONE; stack[0].sizeof_arg = c_last_sizeof_arg; sp = 0; while (true) { enum c_parser_prec oprec; enum tree_code ocode; source_range src_range; if (parser->error) goto out; switch (c_parser_peek_token (parser)->type) { case CPP_MULT: oprec = PREC_MULT; ocode = MULT_EXPR; break; case CPP_DIV: oprec = PREC_MULT; ocode = TRUNC_DIV_EXPR; break; case CPP_MOD: oprec = PREC_MULT; ocode = TRUNC_MOD_EXPR; break; case CPP_PLUS: oprec = PREC_ADD; ocode = PLUS_EXPR; break; case CPP_MINUS: oprec = PREC_ADD; ocode = MINUS_EXPR; break; case CPP_LSHIFT: oprec = PREC_SHIFT; ocode = LSHIFT_EXPR; break; case CPP_RSHIFT: oprec = PREC_SHIFT; ocode = RSHIFT_EXPR; break; case CPP_LESS: oprec = PREC_REL; ocode = LT_EXPR; break; case CPP_GREATER: oprec = PREC_REL; ocode = GT_EXPR; break; case CPP_LESS_EQ: oprec = PREC_REL; ocode = LE_EXPR; break; case CPP_GREATER_EQ: oprec = PREC_REL; ocode = GE_EXPR; break; case CPP_EQ_EQ: oprec = PREC_EQ; ocode = EQ_EXPR; break; case CPP_NOT_EQ: oprec = PREC_EQ; ocode = NE_EXPR; break; case CPP_AND: oprec = PREC_BITAND; ocode = BIT_AND_EXPR; break; case CPP_XOR: oprec = PREC_BITXOR; ocode = BIT_XOR_EXPR; break; case CPP_OR: oprec = PREC_BITOR; ocode = BIT_IOR_EXPR; break; case CPP_AND_AND: oprec = PREC_LOGAND; ocode = TRUTH_ANDIF_EXPR; break; case CPP_OR_OR: oprec = PREC_LOGOR; ocode = TRUTH_ORIF_EXPR; break; default: /* Not a binary operator, so end of the binary expression. */ goto out; } binary_loc = c_parser_peek_token (parser)->location; while (oprec <= stack[sp].prec) POP; c_parser_consume_token (parser); switch (ocode) { case TRUTH_ANDIF_EXPR: src_range = stack[sp].expr.src_range; stack[sp].expr = convert_lvalue_to_rvalue (stack[sp].loc, stack[sp].expr, true, true); stack[sp].expr.value = c_objc_common_truthvalue_conversion (stack[sp].loc, default_conversion (stack[sp].expr.value)); c_inhibit_evaluation_warnings += (stack[sp].expr.value == truthvalue_false_node); set_c_expr_source_range (&stack[sp].expr, src_range); break; case TRUTH_ORIF_EXPR: src_range = stack[sp].expr.src_range; stack[sp].expr = convert_lvalue_to_rvalue (stack[sp].loc, stack[sp].expr, true, true); stack[sp].expr.value = c_objc_common_truthvalue_conversion (stack[sp].loc, default_conversion (stack[sp].expr.value)); c_inhibit_evaluation_warnings += (stack[sp].expr.value == truthvalue_true_node); set_c_expr_source_range (&stack[sp].expr, src_range); break; default: break; } sp++; stack[sp].loc = binary_loc; stack[sp].expr = c_parser_cast_expression (parser, NULL); stack[sp].prec = oprec; stack[sp].op = ocode; stack[sp].sizeof_arg = c_last_sizeof_arg; } out: while (sp > 0) POP; return stack[0].expr; #undef POP } /* Parse a cast expression (C90 6.3.4, C99 6.5.4, C11 6.5.4). If AFTER is not NULL then it is an Objective-C message expression which is the primary-expression starting the expression as an initializer. cast-expression: unary-expression ( type-name ) unary-expression */ static struct c_expr c_parser_cast_expression (c_parser *parser, struct c_expr *after) { location_t cast_loc = c_parser_peek_token (parser)->location; gcc_assert (!after || c_dialect_objc ()); if (after) return c_parser_postfix_expression_after_primary (parser, cast_loc, *after); /* If the expression begins with a parenthesized type name, it may be either a cast or a compound literal; we need to see whether the next character is '{' to tell the difference. If not, it is an unary expression. Full detection of unknown typenames here would require a 3-token lookahead. */ if (c_parser_next_token_is (parser, CPP_OPEN_PAREN) && c_token_starts_typename (c_parser_peek_2nd_token (parser))) { struct c_type_name *type_name; struct c_expr ret; struct c_expr expr; matching_parens parens; parens.consume_open (parser); type_name = c_parser_type_name (parser, true); parens.skip_until_found_close (parser); if (type_name == NULL) { ret.set_error (); ret.original_code = ERROR_MARK; ret.original_type = NULL; return ret; } /* Save casted types in the function's used types hash table. */ used_types_insert (type_name->specs->type); if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) return c_parser_postfix_expression_after_paren_type (parser, type_name, cast_loc); if (type_name->specs->alignas_p) error_at (type_name->specs->locations[cdw_alignas], "alignment specified for type name in cast"); { location_t expr_loc = c_parser_peek_token (parser)->location; expr = c_parser_cast_expression (parser, NULL); expr = convert_lvalue_to_rvalue (expr_loc, expr, true, true); } ret.value = c_cast_expr (cast_loc, type_name, expr.value); if (ret.value && expr.value) set_c_expr_source_range (&ret, cast_loc, expr.get_finish ()); ret.original_code = ERROR_MARK; ret.original_type = NULL; return ret; } else return c_parser_unary_expression (parser); } /* Parse an unary expression (C90 6.3.3, C99 6.5.3, C11 6.5.3). unary-expression: postfix-expression ++ unary-expression -- unary-expression unary-operator cast-expression sizeof unary-expression sizeof ( type-name ) unary-operator: one of & * + - ~ ! GNU extensions: unary-expression: __alignof__ unary-expression __alignof__ ( type-name ) && identifier (C11 permits _Alignof with type names only.) unary-operator: one of __extension__ __real__ __imag__ Transactional Memory: unary-expression: transaction-expression In addition, the GNU syntax treats ++ and -- as unary operators, so they may be applied to cast expressions with errors for non-lvalues given later. */ static struct c_expr c_parser_unary_expression (c_parser *parser) { int ext; struct c_expr ret, op; location_t op_loc = c_parser_peek_token (parser)->location; location_t exp_loc; location_t finish; ret.original_code = ERROR_MARK; ret.original_type = NULL; switch (c_parser_peek_token (parser)->type) { case CPP_PLUS_PLUS: c_parser_consume_token (parser); exp_loc = c_parser_peek_token (parser)->location; op = c_parser_cast_expression (parser, NULL); op = default_function_array_read_conversion (exp_loc, op); return parser_build_unary_op (op_loc, PREINCREMENT_EXPR, op); case CPP_MINUS_MINUS: c_parser_consume_token (parser); exp_loc = c_parser_peek_token (parser)->location; op = c_parser_cast_expression (parser, NULL); op = default_function_array_read_conversion (exp_loc, op); return parser_build_unary_op (op_loc, PREDECREMENT_EXPR, op); case CPP_AND: c_parser_consume_token (parser); op = c_parser_cast_expression (parser, NULL); mark_exp_read (op.value); return parser_build_unary_op (op_loc, ADDR_EXPR, op); case CPP_MULT: { c_parser_consume_token (parser); exp_loc = c_parser_peek_token (parser)->location; op = c_parser_cast_expression (parser, NULL); finish = op.get_finish (); op = convert_lvalue_to_rvalue (exp_loc, op, true, true); location_t combined_loc = make_location (op_loc, op_loc, finish); ret.value = build_indirect_ref (combined_loc, op.value, RO_UNARY_STAR); ret.src_range.m_start = op_loc; ret.src_range.m_finish = finish; return ret; } case CPP_PLUS: if (!c_dialect_objc () && !in_system_header_at (input_location)) warning_at (op_loc, OPT_Wtraditional, "traditional C rejects the unary plus operator"); c_parser_consume_token (parser); exp_loc = c_parser_peek_token (parser)->location; op = c_parser_cast_expression (parser, NULL); op = convert_lvalue_to_rvalue (exp_loc, op, true, true); return parser_build_unary_op (op_loc, CONVERT_EXPR, op); case CPP_MINUS: c_parser_consume_token (parser); exp_loc = c_parser_peek_token (parser)->location; op = c_parser_cast_expression (parser, NULL); op = convert_lvalue_to_rvalue (exp_loc, op, true, true); return parser_build_unary_op (op_loc, NEGATE_EXPR, op); case CPP_COMPL: c_parser_consume_token (parser); exp_loc = c_parser_peek_token (parser)->location; op = c_parser_cast_expression (parser, NULL); op = convert_lvalue_to_rvalue (exp_loc, op, true, true); return parser_build_unary_op (op_loc, BIT_NOT_EXPR, op); case CPP_NOT: c_parser_consume_token (parser); exp_loc = c_parser_peek_token (parser)->location; op = c_parser_cast_expression (parser, NULL); op = convert_lvalue_to_rvalue (exp_loc, op, true, true); return parser_build_unary_op (op_loc, TRUTH_NOT_EXPR, op); case CPP_AND_AND: /* Refer to the address of a label as a pointer. */ c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_NAME)) { ret.value = finish_label_address_expr (c_parser_peek_token (parser)->value, op_loc); set_c_expr_source_range (&ret, op_loc, c_parser_peek_token (parser)->get_finish ()); c_parser_consume_token (parser); } else { c_parser_error (parser, "expected identifier"); ret.set_error (); } return ret; case CPP_KEYWORD: switch (c_parser_peek_token (parser)->keyword) { case RID_SIZEOF: return c_parser_sizeof_expression (parser); case RID_ALIGNOF: return c_parser_alignof_expression (parser); case RID_EXTENSION: c_parser_consume_token (parser); ext = disable_extension_diagnostics (); ret = c_parser_cast_expression (parser, NULL); restore_extension_diagnostics (ext); return ret; case RID_REALPART: c_parser_consume_token (parser); exp_loc = c_parser_peek_token (parser)->location; op = c_parser_cast_expression (parser, NULL); op = default_function_array_conversion (exp_loc, op); return parser_build_unary_op (op_loc, REALPART_EXPR, op); case RID_IMAGPART: c_parser_consume_token (parser); exp_loc = c_parser_peek_token (parser)->location; op = c_parser_cast_expression (parser, NULL); op = default_function_array_conversion (exp_loc, op); return parser_build_unary_op (op_loc, IMAGPART_EXPR, op); case RID_TRANSACTION_ATOMIC: case RID_TRANSACTION_RELAXED: return c_parser_transaction_expression (parser, c_parser_peek_token (parser)->keyword); default: return c_parser_postfix_expression (parser); } default: return c_parser_postfix_expression (parser); } } /* Parse a sizeof expression. */ static struct c_expr c_parser_sizeof_expression (c_parser *parser) { struct c_expr expr; struct c_expr result; location_t expr_loc; gcc_assert (c_parser_next_token_is_keyword (parser, RID_SIZEOF)); location_t start; location_t finish = UNKNOWN_LOCATION; start = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); c_inhibit_evaluation_warnings++; in_sizeof++; if (c_parser_next_token_is (parser, CPP_OPEN_PAREN) && c_token_starts_typename (c_parser_peek_2nd_token (parser))) { /* Either sizeof ( type-name ) or sizeof unary-expression starting with a compound literal. */ struct c_type_name *type_name; matching_parens parens; parens.consume_open (parser); expr_loc = c_parser_peek_token (parser)->location; type_name = c_parser_type_name (parser, true); parens.skip_until_found_close (parser); finish = parser->tokens_buf[0].location; if (type_name == NULL) { struct c_expr ret; c_inhibit_evaluation_warnings--; in_sizeof--; ret.set_error (); ret.original_code = ERROR_MARK; ret.original_type = NULL; return ret; } if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) { expr = c_parser_postfix_expression_after_paren_type (parser, type_name, expr_loc); finish = expr.get_finish (); goto sizeof_expr; } /* sizeof ( type-name ). */ if (type_name->specs->alignas_p) error_at (type_name->specs->locations[cdw_alignas], "alignment specified for type name in %<sizeof%>"); c_inhibit_evaluation_warnings--; in_sizeof--; result = c_expr_sizeof_type (expr_loc, type_name); } else { expr_loc = c_parser_peek_token (parser)->location; expr = c_parser_unary_expression (parser); finish = expr.get_finish (); sizeof_expr: c_inhibit_evaluation_warnings--; in_sizeof--; mark_exp_read (expr.value); if (TREE_CODE (expr.value) == COMPONENT_REF && DECL_C_BIT_FIELD (TREE_OPERAND (expr.value, 1))) error_at (expr_loc, "%<sizeof%> applied to a bit-field"); result = c_expr_sizeof_expr (expr_loc, expr); } if (finish != UNKNOWN_LOCATION) set_c_expr_source_range (&result, start, finish); return result; } /* Parse an alignof expression. */ static struct c_expr c_parser_alignof_expression (c_parser *parser) { struct c_expr expr; location_t start_loc = c_parser_peek_token (parser)->location; location_t end_loc; tree alignof_spelling = c_parser_peek_token (parser)->value; gcc_assert (c_parser_next_token_is_keyword (parser, RID_ALIGNOF)); bool is_c11_alignof = strcmp (IDENTIFIER_POINTER (alignof_spelling), "_Alignof") == 0; /* A diagnostic is not required for the use of this identifier in the implementation namespace; only diagnose it for the C11 spelling because of existing code using the other spellings. */ if (is_c11_alignof) { if (flag_isoc99) pedwarn_c99 (start_loc, OPT_Wpedantic, "ISO C99 does not support %qE", alignof_spelling); else pedwarn_c99 (start_loc, OPT_Wpedantic, "ISO C90 does not support %qE", alignof_spelling); } c_parser_consume_token (parser); c_inhibit_evaluation_warnings++; in_alignof++; if (c_parser_next_token_is (parser, CPP_OPEN_PAREN) && c_token_starts_typename (c_parser_peek_2nd_token (parser))) { /* Either __alignof__ ( type-name ) or __alignof__ unary-expression starting with a compound literal. */ location_t loc; struct c_type_name *type_name; struct c_expr ret; matching_parens parens; parens.consume_open (parser); loc = c_parser_peek_token (parser)->location; type_name = c_parser_type_name (parser, true); end_loc = c_parser_peek_token (parser)->location; parens.skip_until_found_close (parser); if (type_name == NULL) { struct c_expr ret; c_inhibit_evaluation_warnings--; in_alignof--; ret.set_error (); ret.original_code = ERROR_MARK; ret.original_type = NULL; return ret; } if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) { expr = c_parser_postfix_expression_after_paren_type (parser, type_name, loc); goto alignof_expr; } /* alignof ( type-name ). */ if (type_name->specs->alignas_p) error_at (type_name->specs->locations[cdw_alignas], "alignment specified for type name in %qE", alignof_spelling); c_inhibit_evaluation_warnings--; in_alignof--; ret.value = c_sizeof_or_alignof_type (loc, groktypename (type_name, NULL, NULL), false, is_c11_alignof, 1); ret.original_code = ERROR_MARK; ret.original_type = NULL; set_c_expr_source_range (&ret, start_loc, end_loc); return ret; } else { struct c_expr ret; expr = c_parser_unary_expression (parser); end_loc = expr.src_range.m_finish; alignof_expr: mark_exp_read (expr.value); c_inhibit_evaluation_warnings--; in_alignof--; if (is_c11_alignof) pedwarn (start_loc, OPT_Wpedantic, "ISO C does not allow %<%E (expression)%>", alignof_spelling); ret.value = c_alignof_expr (start_loc, expr.value); ret.original_code = ERROR_MARK; ret.original_type = NULL; set_c_expr_source_range (&ret, start_loc, end_loc); return ret; } } /* Helper function to read arguments of builtins which are interfaces for the middle-end nodes like COMPLEX_EXPR, VEC_PERM_EXPR and others. The name of the builtin is passed using BNAME parameter. Function returns true if there were no errors while parsing and stores the arguments in CEXPR_LIST. If it returns true, *OUT_CLOSE_PAREN_LOC is written to with the location of the closing parenthesis. */ static bool c_parser_get_builtin_args (c_parser *parser, const char *bname, vec<c_expr_t, va_gc> **ret_cexpr_list, bool choose_expr_p, location_t *out_close_paren_loc) { location_t loc = c_parser_peek_token (parser)->location; vec<c_expr_t, va_gc> *cexpr_list; c_expr_t expr; bool saved_force_folding_builtin_constant_p; *ret_cexpr_list = NULL; if (c_parser_next_token_is_not (parser, CPP_OPEN_PAREN)) { error_at (loc, "cannot take address of %qs", bname); return false; } c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { *out_close_paren_loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); return true; } saved_force_folding_builtin_constant_p = force_folding_builtin_constant_p; force_folding_builtin_constant_p |= choose_expr_p; expr = c_parser_expr_no_commas (parser, NULL); force_folding_builtin_constant_p = saved_force_folding_builtin_constant_p; vec_alloc (cexpr_list, 1); vec_safe_push (cexpr_list, expr); while (c_parser_next_token_is (parser, CPP_COMMA)) { c_parser_consume_token (parser); expr = c_parser_expr_no_commas (parser, NULL); vec_safe_push (cexpr_list, expr); } *out_close_paren_loc = c_parser_peek_token (parser)->location; if (!c_parser_require (parser, CPP_CLOSE_PAREN, "expected %<)%>")) return false; *ret_cexpr_list = cexpr_list; return true; } /* This represents a single generic-association. */ struct c_generic_association { /* The location of the starting token of the type. */ location_t type_location; /* The association's type, or NULL_TREE for 'default'. */ tree type; /* The association's expression. */ struct c_expr expression; }; /* Parse a generic-selection. (C11 6.5.1.1). generic-selection: _Generic ( assignment-expression , generic-assoc-list ) generic-assoc-list: generic-association generic-assoc-list , generic-association generic-association: type-name : assignment-expression default : assignment-expression */ static struct c_expr c_parser_generic_selection (c_parser *parser) { struct c_expr selector, error_expr; tree selector_type; struct c_generic_association matched_assoc; bool match_found = false; location_t generic_loc, selector_loc; error_expr.original_code = ERROR_MARK; error_expr.original_type = NULL; error_expr.set_error (); matched_assoc.type_location = UNKNOWN_LOCATION; matched_assoc.type = NULL_TREE; matched_assoc.expression = error_expr; gcc_assert (c_parser_next_token_is_keyword (parser, RID_GENERIC)); generic_loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); if (flag_isoc99) pedwarn_c99 (generic_loc, OPT_Wpedantic, "ISO C99 does not support %<_Generic%>"); else pedwarn_c99 (generic_loc, OPT_Wpedantic, "ISO C90 does not support %<_Generic%>"); matching_parens parens; if (!parens.require_open (parser)) return error_expr; c_inhibit_evaluation_warnings++; selector_loc = c_parser_peek_token (parser)->location; selector = c_parser_expr_no_commas (parser, NULL); selector = default_function_array_conversion (selector_loc, selector); c_inhibit_evaluation_warnings--; if (selector.value == error_mark_node) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return selector; } selector_type = TREE_TYPE (selector.value); /* In ISO C terms, rvalues (including the controlling expression of _Generic) do not have qualified types. */ if (TREE_CODE (selector_type) != ARRAY_TYPE) selector_type = TYPE_MAIN_VARIANT (selector_type); /* In ISO C terms, _Noreturn is not part of the type of expressions such as &abort, but in GCC it is represented internally as a type qualifier. */ if (FUNCTION_POINTER_TYPE_P (selector_type) && TYPE_QUALS (TREE_TYPE (selector_type)) != TYPE_UNQUALIFIED) selector_type = build_pointer_type (TYPE_MAIN_VARIANT (TREE_TYPE (selector_type))); if (!c_parser_require (parser, CPP_COMMA, "expected %<,%>")) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return error_expr; } auto_vec<c_generic_association> associations; while (1) { struct c_generic_association assoc, *iter; unsigned int ix; c_token *token = c_parser_peek_token (parser); assoc.type_location = token->location; if (token->type == CPP_KEYWORD && token->keyword == RID_DEFAULT) { c_parser_consume_token (parser); assoc.type = NULL_TREE; } else { struct c_type_name *type_name; type_name = c_parser_type_name (parser); if (type_name == NULL) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return error_expr; } assoc.type = groktypename (type_name, NULL, NULL); if (assoc.type == error_mark_node) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return error_expr; } if (TREE_CODE (assoc.type) == FUNCTION_TYPE) error_at (assoc.type_location, "%<_Generic%> association has function type"); else if (!COMPLETE_TYPE_P (assoc.type)) error_at (assoc.type_location, "%<_Generic%> association has incomplete type"); if (variably_modified_type_p (assoc.type, NULL_TREE)) error_at (assoc.type_location, "%<_Generic%> association has " "variable length type"); } if (!c_parser_require (parser, CPP_COLON, "expected %<:%>")) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return error_expr; } assoc.expression = c_parser_expr_no_commas (parser, NULL); if (assoc.expression.value == error_mark_node) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return error_expr; } for (ix = 0; associations.iterate (ix, &iter); ++ix) { if (assoc.type == NULL_TREE) { if (iter->type == NULL_TREE) { error_at (assoc.type_location, "duplicate %<default%> case in %<_Generic%>"); inform (iter->type_location, "original %<default%> is here"); } } else if (iter->type != NULL_TREE) { if (comptypes (assoc.type, iter->type)) { error_at (assoc.type_location, "%<_Generic%> specifies two compatible types"); inform (iter->type_location, "compatible type is here"); } } } if (assoc.type == NULL_TREE) { if (!match_found) { matched_assoc = assoc; match_found = true; } } else if (comptypes (assoc.type, selector_type)) { if (!match_found || matched_assoc.type == NULL_TREE) { matched_assoc = assoc; match_found = true; } else { error_at (assoc.type_location, "%<_Generic%> selector matches multiple associations"); inform (matched_assoc.type_location, "other match is here"); } } associations.safe_push (assoc); if (c_parser_peek_token (parser)->type != CPP_COMMA) break; c_parser_consume_token (parser); } if (!parens.require_close (parser)) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return error_expr; } if (!match_found) { error_at (selector_loc, "%<_Generic%> selector of type %qT is not " "compatible with any association", selector_type); return error_expr; } return matched_assoc.expression; } /* Check the validity of a function pointer argument *EXPR (argument position POS) to __builtin_tgmath. Return the number of function arguments if possibly valid; return 0 having reported an error if not valid. */ static unsigned int check_tgmath_function (c_expr *expr, unsigned int pos) { tree type = TREE_TYPE (expr->value); if (!FUNCTION_POINTER_TYPE_P (type)) { error_at (expr->get_location (), "argument %u of %<__builtin_tgmath%> is not a function pointer", pos); return 0; } type = TREE_TYPE (type); if (!prototype_p (type)) { error_at (expr->get_location (), "argument %u of %<__builtin_tgmath%> is unprototyped", pos); return 0; } if (stdarg_p (type)) { error_at (expr->get_location (), "argument %u of %<__builtin_tgmath%> has variable arguments", pos); return 0; } unsigned int nargs = 0; function_args_iterator iter; tree t; FOREACH_FUNCTION_ARGS (type, t, iter) { if (t == void_type_node) break; nargs++; } if (nargs == 0) { error_at (expr->get_location (), "argument %u of %<__builtin_tgmath%> has no arguments", pos); return 0; } return nargs; } /* Ways in which a parameter or return value of a type-generic macro may vary between the different functions the macro may call. */ enum tgmath_parm_kind { tgmath_fixed, tgmath_real, tgmath_complex }; /* Parse a postfix expression (C90 6.3.1-6.3.2, C99 6.5.1-6.5.2, C11 6.5.1-6.5.2). Compound literals aren't handled here; callers have to call c_parser_postfix_expression_after_paren_type on encountering them. postfix-expression: primary-expression postfix-expression [ expression ] postfix-expression ( argument-expression-list[opt] ) postfix-expression . identifier postfix-expression -> identifier postfix-expression ++ postfix-expression -- ( type-name ) { initializer-list } ( type-name ) { initializer-list , } argument-expression-list: argument-expression argument-expression-list , argument-expression primary-expression: identifier constant string-literal ( expression ) generic-selection GNU extensions: primary-expression: __func__ (treated as a keyword in GNU C) __FUNCTION__ __PRETTY_FUNCTION__ ( compound-statement ) __builtin_va_arg ( assignment-expression , type-name ) __builtin_offsetof ( type-name , offsetof-member-designator ) __builtin_choose_expr ( assignment-expression , assignment-expression , assignment-expression ) __builtin_types_compatible_p ( type-name , type-name ) __builtin_tgmath ( expr-list ) __builtin_complex ( assignment-expression , assignment-expression ) __builtin_shuffle ( assignment-expression , assignment-expression ) __builtin_shuffle ( assignment-expression , assignment-expression , assignment-expression, ) offsetof-member-designator: identifier offsetof-member-designator . identifier offsetof-member-designator [ expression ] Objective-C: primary-expression: [ objc-receiver objc-message-args ] @selector ( objc-selector-arg ) @protocol ( identifier ) @encode ( type-name ) objc-string-literal Classname . identifier */ static struct c_expr c_parser_postfix_expression (c_parser *parser) { struct c_expr expr, e1; struct c_type_name *t1, *t2; location_t loc = c_parser_peek_token (parser)->location; source_range tok_range = c_parser_peek_token (parser)->get_range (); expr.original_code = ERROR_MARK; expr.original_type = NULL; switch (c_parser_peek_token (parser)->type) { case CPP_NUMBER: expr.value = c_parser_peek_token (parser)->value; set_c_expr_source_range (&expr, tok_range); loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); if (TREE_CODE (expr.value) == FIXED_CST && !targetm.fixed_point_supported_p ()) { error_at (loc, "fixed-point types not supported for this target"); expr.set_error (); } break; case CPP_CHAR: case CPP_CHAR16: case CPP_CHAR32: case CPP_WCHAR: expr.value = c_parser_peek_token (parser)->value; /* For the purpose of warning when a pointer is compared with a zero character constant. */ expr.original_type = char_type_node; set_c_expr_source_range (&expr, tok_range); c_parser_consume_token (parser); break; case CPP_STRING: case CPP_STRING16: case CPP_STRING32: case CPP_WSTRING: case CPP_UTF8STRING: expr.value = c_parser_peek_token (parser)->value; set_c_expr_source_range (&expr, tok_range); expr.original_code = STRING_CST; c_parser_consume_token (parser); break; case CPP_OBJC_STRING: gcc_assert (c_dialect_objc ()); expr.value = objc_build_string_object (c_parser_peek_token (parser)->value); set_c_expr_source_range (&expr, tok_range); c_parser_consume_token (parser); break; case CPP_NAME: switch (c_parser_peek_token (parser)->id_kind) { case C_ID_ID: { tree id = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); expr.value = build_external_ref (loc, id, (c_parser_peek_token (parser)->type == CPP_OPEN_PAREN), &expr.original_type); set_c_expr_source_range (&expr, tok_range); break; } case C_ID_CLASSNAME: { /* Here we parse the Objective-C 2.0 Class.name dot syntax. */ tree class_name = c_parser_peek_token (parser)->value; tree component; c_parser_consume_token (parser); gcc_assert (c_dialect_objc ()); if (!c_parser_require (parser, CPP_DOT, "expected %<.%>")) { expr.set_error (); break; } if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); expr.set_error (); break; } c_token *component_tok = c_parser_peek_token (parser); component = component_tok->value; location_t end_loc = component_tok->get_finish (); c_parser_consume_token (parser); expr.value = objc_build_class_component_ref (class_name, component); set_c_expr_source_range (&expr, loc, end_loc); break; } default: c_parser_error (parser, "expected expression"); expr.set_error (); break; } break; case CPP_OPEN_PAREN: /* A parenthesized expression, statement expression or compound literal. */ if (c_parser_peek_2nd_token (parser)->type == CPP_OPEN_BRACE) { /* A statement expression. */ tree stmt; location_t brace_loc; c_parser_consume_token (parser); brace_loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); if (!building_stmt_list_p ()) { error_at (loc, "braced-group within expression allowed " "only inside a function"); parser->error = true; c_parser_skip_until_found (parser, CPP_CLOSE_BRACE, NULL); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); expr.set_error (); break; } stmt = c_begin_stmt_expr (); c_parser_compound_statement_nostart (parser); location_t close_loc = c_parser_peek_token (parser)->location; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); pedwarn (loc, OPT_Wpedantic, "ISO C forbids braced-groups within expressions"); expr.value = c_finish_stmt_expr (brace_loc, stmt); set_c_expr_source_range (&expr, loc, close_loc); mark_exp_read (expr.value); } else { /* A parenthesized expression. */ location_t loc_open_paren = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); expr = c_parser_expression (parser); if (TREE_CODE (expr.value) == MODIFY_EXPR) TREE_NO_WARNING (expr.value) = 1; if (expr.original_code != C_MAYBE_CONST_EXPR && expr.original_code != SIZEOF_EXPR) expr.original_code = ERROR_MARK; /* Don't change EXPR.ORIGINAL_TYPE. */ location_t loc_close_paren = c_parser_peek_token (parser)->location; set_c_expr_source_range (&expr, loc_open_paren, loc_close_paren); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>", loc_open_paren); } break; case CPP_KEYWORD: switch (c_parser_peek_token (parser)->keyword) { case RID_FUNCTION_NAME: pedwarn (loc, OPT_Wpedantic, "ISO C does not support " "%<__FUNCTION__%> predefined identifier"); expr.value = fname_decl (loc, c_parser_peek_token (parser)->keyword, c_parser_peek_token (parser)->value); set_c_expr_source_range (&expr, loc, loc); c_parser_consume_token (parser); break; case RID_PRETTY_FUNCTION_NAME: pedwarn (loc, OPT_Wpedantic, "ISO C does not support " "%<__PRETTY_FUNCTION__%> predefined identifier"); expr.value = fname_decl (loc, c_parser_peek_token (parser)->keyword, c_parser_peek_token (parser)->value); set_c_expr_source_range (&expr, loc, loc); c_parser_consume_token (parser); break; case RID_C99_FUNCTION_NAME: pedwarn_c90 (loc, OPT_Wpedantic, "ISO C90 does not support " "%<__func__%> predefined identifier"); expr.value = fname_decl (loc, c_parser_peek_token (parser)->keyword, c_parser_peek_token (parser)->value); set_c_expr_source_range (&expr, loc, loc); c_parser_consume_token (parser); break; case RID_VA_ARG: { location_t start_loc = loc; c_parser_consume_token (parser); matching_parens parens; if (!parens.require_open (parser)) { expr.set_error (); break; } e1 = c_parser_expr_no_commas (parser, NULL); mark_exp_read (e1.value); e1.value = c_fully_fold (e1.value, false, NULL); if (!c_parser_require (parser, CPP_COMMA, "expected %<,%>")) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); expr.set_error (); break; } loc = c_parser_peek_token (parser)->location; t1 = c_parser_type_name (parser); location_t end_loc = c_parser_peek_token (parser)->get_finish (); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); if (t1 == NULL) { expr.set_error (); } else { tree type_expr = NULL_TREE; expr.value = c_build_va_arg (start_loc, e1.value, loc, groktypename (t1, &type_expr, NULL)); if (type_expr) { expr.value = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (expr.value), type_expr, expr.value); C_MAYBE_CONST_EXPR_NON_CONST (expr.value) = true; } set_c_expr_source_range (&expr, start_loc, end_loc); } } break; case RID_OFFSETOF: { c_parser_consume_token (parser); matching_parens parens; if (!parens.require_open (parser)) { expr.set_error (); break; } t1 = c_parser_type_name (parser); if (t1 == NULL) parser->error = true; if (!c_parser_require (parser, CPP_COMMA, "expected %<,%>")) gcc_assert (parser->error); if (parser->error) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); expr.set_error (); break; } tree type = groktypename (t1, NULL, NULL); tree offsetof_ref; if (type == error_mark_node) offsetof_ref = error_mark_node; else { offsetof_ref = build1 (INDIRECT_REF, type, null_pointer_node); SET_EXPR_LOCATION (offsetof_ref, loc); } /* Parse the second argument to __builtin_offsetof. We must have one identifier, and beyond that we want to accept sub structure and sub array references. */ if (c_parser_next_token_is (parser, CPP_NAME)) { c_token *comp_tok = c_parser_peek_token (parser); offsetof_ref = build_component_ref (loc, offsetof_ref, comp_tok->value, comp_tok->location); c_parser_consume_token (parser); while (c_parser_next_token_is (parser, CPP_DOT) || c_parser_next_token_is (parser, CPP_OPEN_SQUARE) || c_parser_next_token_is (parser, CPP_DEREF)) { if (c_parser_next_token_is (parser, CPP_DEREF)) { loc = c_parser_peek_token (parser)->location; offsetof_ref = build_array_ref (loc, offsetof_ref, integer_zero_node); goto do_dot; } else if (c_parser_next_token_is (parser, CPP_DOT)) { do_dot: c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); break; } c_token *comp_tok = c_parser_peek_token (parser); offsetof_ref = build_component_ref (loc, offsetof_ref, comp_tok->value, comp_tok->location); c_parser_consume_token (parser); } else { struct c_expr ce; tree idx; loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); ce = c_parser_expression (parser); ce = convert_lvalue_to_rvalue (loc, ce, false, false); idx = ce.value; idx = c_fully_fold (idx, false, NULL); c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, "expected %<]%>"); offsetof_ref = build_array_ref (loc, offsetof_ref, idx); } } } else c_parser_error (parser, "expected identifier"); location_t end_loc = c_parser_peek_token (parser)->get_finish (); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); expr.value = fold_offsetof (offsetof_ref); set_c_expr_source_range (&expr, loc, end_loc); } break; case RID_CHOOSE_EXPR: { vec<c_expr_t, va_gc> *cexpr_list; c_expr_t *e1_p, *e2_p, *e3_p; tree c; location_t close_paren_loc; c_parser_consume_token (parser); if (!c_parser_get_builtin_args (parser, "__builtin_choose_expr", &cexpr_list, true, &close_paren_loc)) { expr.set_error (); break; } if (vec_safe_length (cexpr_list) != 3) { error_at (loc, "wrong number of arguments to " "%<__builtin_choose_expr%>"); expr.set_error (); break; } e1_p = &(*cexpr_list)[0]; e2_p = &(*cexpr_list)[1]; e3_p = &(*cexpr_list)[2]; c = e1_p->value; mark_exp_read (e2_p->value); mark_exp_read (e3_p->value); if (TREE_CODE (c) != INTEGER_CST || !INTEGRAL_TYPE_P (TREE_TYPE (c))) error_at (loc, "first argument to %<__builtin_choose_expr%> not" " a constant"); constant_expression_warning (c); expr = integer_zerop (c) ? *e3_p : *e2_p; set_c_expr_source_range (&expr, loc, close_paren_loc); break; } case RID_TYPES_COMPATIBLE_P: { c_parser_consume_token (parser); matching_parens parens; if (!parens.require_open (parser)) { expr.set_error (); break; } t1 = c_parser_type_name (parser); if (t1 == NULL) { expr.set_error (); break; } if (!c_parser_require (parser, CPP_COMMA, "expected %<,%>")) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); expr.set_error (); break; } t2 = c_parser_type_name (parser); if (t2 == NULL) { expr.set_error (); break; } location_t close_paren_loc = c_parser_peek_token (parser)->location; parens.skip_until_found_close (parser); tree e1, e2; e1 = groktypename (t1, NULL, NULL); e2 = groktypename (t2, NULL, NULL); if (e1 == error_mark_node || e2 == error_mark_node) { expr.set_error (); break; } e1 = TYPE_MAIN_VARIANT (e1); e2 = TYPE_MAIN_VARIANT (e2); expr.value = comptypes (e1, e2) ? integer_one_node : integer_zero_node; set_c_expr_source_range (&expr, loc, close_paren_loc); } break; case RID_BUILTIN_TGMATH: { vec<c_expr_t, va_gc> *cexpr_list; location_t close_paren_loc; c_parser_consume_token (parser); if (!c_parser_get_builtin_args (parser, "__builtin_tgmath", &cexpr_list, false, &close_paren_loc)) { expr.set_error (); break; } if (vec_safe_length (cexpr_list) < 3) { error_at (loc, "too few arguments to %<__builtin_tgmath%>"); expr.set_error (); break; } unsigned int i; c_expr_t *p; FOR_EACH_VEC_ELT (*cexpr_list, i, p) *p = convert_lvalue_to_rvalue (loc, *p, true, true); unsigned int nargs = check_tgmath_function (&(*cexpr_list)[0], 1); if (nargs == 0) { expr.set_error (); break; } if (vec_safe_length (cexpr_list) < nargs) { error_at (loc, "too few arguments to %<__builtin_tgmath%>"); expr.set_error (); break; } unsigned int num_functions = vec_safe_length (cexpr_list) - nargs; if (num_functions < 2) { error_at (loc, "too few arguments to %<__builtin_tgmath%>"); expr.set_error (); break; } /* The first NUM_FUNCTIONS expressions are the function pointers. The remaining NARGS expressions are the arguments that are to be passed to one of those functions, chosen following <tgmath.h> rules. */ for (unsigned int j = 1; j < num_functions; j++) { unsigned int this_nargs = check_tgmath_function (&(*cexpr_list)[j], j + 1); if (this_nargs == 0) { expr.set_error (); goto out; } if (this_nargs != nargs) { error_at ((*cexpr_list)[j].get_location (), "argument %u of %<__builtin_tgmath%> has " "wrong number of arguments", j + 1); expr.set_error (); goto out; } } /* The functions all have the same number of arguments. Determine whether arguments and return types vary in ways permitted for <tgmath.h> functions. */ /* The first entry in each of these vectors is for the return type, subsequent entries for parameter types. */ auto_vec<enum tgmath_parm_kind> parm_kind (nargs + 1); auto_vec<tree> parm_first (nargs + 1); auto_vec<bool> parm_complex (nargs + 1); auto_vec<bool> parm_varies (nargs + 1); tree first_type = TREE_TYPE (TREE_TYPE ((*cexpr_list)[0].value)); tree first_ret = TYPE_MAIN_VARIANT (TREE_TYPE (first_type)); parm_first.quick_push (first_ret); parm_complex.quick_push (TREE_CODE (first_ret) == COMPLEX_TYPE); parm_varies.quick_push (false); function_args_iterator iter; tree t; unsigned int argpos; FOREACH_FUNCTION_ARGS (first_type, t, iter) { if (t == void_type_node) break; parm_first.quick_push (TYPE_MAIN_VARIANT (t)); parm_complex.quick_push (TREE_CODE (t) == COMPLEX_TYPE); parm_varies.quick_push (false); } for (unsigned int j = 1; j < num_functions; j++) { tree type = TREE_TYPE (TREE_TYPE ((*cexpr_list)[j].value)); tree ret = TYPE_MAIN_VARIANT (TREE_TYPE (type)); if (ret != parm_first[0]) { parm_varies[0] = true; if (!SCALAR_FLOAT_TYPE_P (parm_first[0]) && !COMPLEX_FLOAT_TYPE_P (parm_first[0])) { error_at ((*cexpr_list)[0].get_location (), "invalid type-generic return type for " "argument %u of %<__builtin_tgmath%>", 1); expr.set_error (); goto out; } if (!SCALAR_FLOAT_TYPE_P (ret) && !COMPLEX_FLOAT_TYPE_P (ret)) { error_at ((*cexpr_list)[j].get_location (), "invalid type-generic return type for " "argument %u of %<__builtin_tgmath%>", j + 1); expr.set_error (); goto out; } } if (TREE_CODE (ret) == COMPLEX_TYPE) parm_complex[0] = true; argpos = 1; FOREACH_FUNCTION_ARGS (type, t, iter) { if (t == void_type_node) break; t = TYPE_MAIN_VARIANT (t); if (t != parm_first[argpos]) { parm_varies[argpos] = true; if (!SCALAR_FLOAT_TYPE_P (parm_first[argpos]) && !COMPLEX_FLOAT_TYPE_P (parm_first[argpos])) { error_at ((*cexpr_list)[0].get_location (), "invalid type-generic type for " "argument %u of argument %u of " "%<__builtin_tgmath%>", argpos, 1); expr.set_error (); goto out; } if (!SCALAR_FLOAT_TYPE_P (t) && !COMPLEX_FLOAT_TYPE_P (t)) { error_at ((*cexpr_list)[j].get_location (), "invalid type-generic type for " "argument %u of argument %u of " "%<__builtin_tgmath%>", argpos, j + 1); expr.set_error (); goto out; } } if (TREE_CODE (t) == COMPLEX_TYPE) parm_complex[argpos] = true; argpos++; } } enum tgmath_parm_kind max_variation = tgmath_fixed; for (unsigned int j = 0; j <= nargs; j++) { enum tgmath_parm_kind this_kind; if (parm_varies[j]) { if (parm_complex[j]) max_variation = this_kind = tgmath_complex; else { this_kind = tgmath_real; if (max_variation != tgmath_complex) max_variation = tgmath_real; } } else this_kind = tgmath_fixed; parm_kind.quick_push (this_kind); } if (max_variation == tgmath_fixed) { error_at (loc, "function arguments of %<__builtin_tgmath%> " "all have the same type"); expr.set_error (); break; } /* Identify a parameter (not the return type) that varies, including with complex types if any variation includes complex types; there must be at least one such parameter. */ unsigned int tgarg = 0; for (unsigned int j = 1; j <= nargs; j++) if (parm_kind[j] == max_variation) { tgarg = j; break; } if (tgarg == 0) { error_at (loc, "function arguments of %<__builtin_tgmath%> " "lack type-generic parameter"); expr.set_error (); break; } /* Determine the type of the relevant parameter for each function. */ auto_vec<tree> tg_type (num_functions); for (unsigned int j = 0; j < num_functions; j++) { tree type = TREE_TYPE (TREE_TYPE ((*cexpr_list)[j].value)); argpos = 1; FOREACH_FUNCTION_ARGS (type, t, iter) { if (argpos == tgarg) { tg_type.quick_push (TYPE_MAIN_VARIANT (t)); break; } argpos++; } } /* Verify that the corresponding types are different for all the listed functions. Also determine whether all the types are complex, whether all the types are standard or binary, and whether all the types are decimal. */ bool all_complex = true; bool all_binary = true; bool all_decimal = true; hash_set<tree> tg_types; FOR_EACH_VEC_ELT (tg_type, i, t) { if (TREE_CODE (t) == COMPLEX_TYPE) all_decimal = false; else { all_complex = false; if (DECIMAL_FLOAT_TYPE_P (t)) all_binary = false; else all_decimal = false; } if (tg_types.add (t)) { error_at ((*cexpr_list)[i].get_location (), "duplicate type-generic parameter type for " "function argument %u of %<__builtin_tgmath%>", i + 1); expr.set_error (); goto out; } } /* Verify that other parameters and the return type whose types vary have their types varying in the correct way. */ for (unsigned int j = 0; j < num_functions; j++) { tree exp_type = tg_type[j]; tree exp_real_type = exp_type; if (TREE_CODE (exp_type) == COMPLEX_TYPE) exp_real_type = TREE_TYPE (exp_type); tree type = TREE_TYPE (TREE_TYPE ((*cexpr_list)[j].value)); tree ret = TYPE_MAIN_VARIANT (TREE_TYPE (type)); if ((parm_kind[0] == tgmath_complex && ret != exp_type) || (parm_kind[0] == tgmath_real && ret != exp_real_type)) { error_at ((*cexpr_list)[j].get_location (), "bad return type for function argument %u " "of %<__builtin_tgmath%>", j + 1); expr.set_error (); goto out; } argpos = 1; FOREACH_FUNCTION_ARGS (type, t, iter) { if (t == void_type_node) break; t = TYPE_MAIN_VARIANT (t); if ((parm_kind[argpos] == tgmath_complex && t != exp_type) || (parm_kind[argpos] == tgmath_real && t != exp_real_type)) { error_at ((*cexpr_list)[j].get_location (), "bad type for argument %u of " "function argument %u of " "%<__builtin_tgmath%>", argpos, j + 1); expr.set_error (); goto out; } argpos++; } } /* The functions listed are a valid set of functions for a <tgmath.h> macro to select between. Identify the matching function, if any. First, the argument types must be combined following <tgmath.h> rules. Integer types are treated as _Decimal64 if any type-generic argument is decimal, or if the only alternatives for type-generic arguments are of decimal types, and are otherwise treated as double (or _Complex double for complex integer types, or _Float64 or _Complex _Float64 if all the return types are the same _FloatN or _FloatNx type). After that adjustment, types are combined following the usual arithmetic conversions. If the function only accepts complex arguments, a complex type is produced. */ bool arg_complex = all_complex; bool arg_binary = all_binary; bool arg_int_decimal = all_decimal; for (unsigned int j = 1; j <= nargs; j++) { if (parm_kind[j] == tgmath_fixed) continue; c_expr_t *ce = &(*cexpr_list)[num_functions + j - 1]; tree type = TREE_TYPE (ce->value); if (!INTEGRAL_TYPE_P (type) && !SCALAR_FLOAT_TYPE_P (type) && TREE_CODE (type) != COMPLEX_TYPE) { error_at (ce->get_location (), "invalid type of argument %u of type-generic " "function", j); expr.set_error (); goto out; } if (DECIMAL_FLOAT_TYPE_P (type)) { arg_int_decimal = true; if (all_complex) { error_at (ce->get_location (), "decimal floating-point argument %u to " "complex-only type-generic function", j); expr.set_error (); goto out; } else if (all_binary) { error_at (ce->get_location (), "decimal floating-point argument %u to " "binary-only type-generic function", j); expr.set_error (); goto out; } else if (arg_complex) { error_at (ce->get_location (), "both complex and decimal floating-point " "arguments to type-generic function"); expr.set_error (); goto out; } else if (arg_binary) { error_at (ce->get_location (), "both binary and decimal floating-point " "arguments to type-generic function"); expr.set_error (); goto out; } } else if (TREE_CODE (type) == COMPLEX_TYPE) { arg_complex = true; if (COMPLEX_FLOAT_TYPE_P (type)) arg_binary = true; if (all_decimal) { error_at (ce->get_location (), "complex argument %u to " "decimal-only type-generic function", j); expr.set_error (); goto out; } else if (arg_int_decimal) { error_at (ce->get_location (), "both complex and decimal floating-point " "arguments to type-generic function"); expr.set_error (); goto out; } } else if (SCALAR_FLOAT_TYPE_P (type)) { arg_binary = true; if (all_decimal) { error_at (ce->get_location (), "binary argument %u to " "decimal-only type-generic function", j); expr.set_error (); goto out; } else if (arg_int_decimal) { error_at (ce->get_location (), "both binary and decimal floating-point " "arguments to type-generic function"); expr.set_error (); goto out; } } } /* For a macro rounding its result to a narrower type, map integer types to _Float64 not double if the return type is a _FloatN or _FloatNx type. */ bool arg_int_float64 = false; if (parm_kind[0] == tgmath_fixed && SCALAR_FLOAT_TYPE_P (parm_first[0]) && float64_type_node != NULL_TREE) for (unsigned int j = 0; j < NUM_FLOATN_NX_TYPES; j++) if (parm_first[0] == FLOATN_TYPE_NODE (j)) { arg_int_float64 = true; break; } tree arg_real = NULL_TREE; for (unsigned int j = 1; j <= nargs; j++) { if (parm_kind[j] == tgmath_fixed) continue; c_expr_t *ce = &(*cexpr_list)[num_functions + j - 1]; tree type = TYPE_MAIN_VARIANT (TREE_TYPE (ce->value)); if (TREE_CODE (type) == COMPLEX_TYPE) type = TREE_TYPE (type); if (INTEGRAL_TYPE_P (type)) type = (arg_int_decimal ? dfloat64_type_node : arg_int_float64 ? float64_type_node : double_type_node); if (arg_real == NULL_TREE) arg_real = type; else arg_real = common_type (arg_real, type); if (arg_real == error_mark_node) { expr.set_error (); goto out; } } tree arg_type = (arg_complex ? build_complex_type (arg_real) : arg_real); /* Look for a function to call with type-generic parameter type ARG_TYPE. */ c_expr_t *fn = NULL; for (unsigned int j = 0; j < num_functions; j++) { if (tg_type[j] == arg_type) { fn = &(*cexpr_list)[j]; break; } } if (fn == NULL && parm_kind[0] == tgmath_fixed && SCALAR_FLOAT_TYPE_P (parm_first[0])) { /* Presume this is a macro that rounds its result to a narrower type, and look for the first function with at least the range and precision of the argument type. */ for (unsigned int j = 0; j < num_functions; j++) { if (arg_complex != (TREE_CODE (tg_type[j]) == COMPLEX_TYPE)) continue; tree real_tg_type = (arg_complex ? TREE_TYPE (tg_type[j]) : tg_type[j]); if (DECIMAL_FLOAT_TYPE_P (arg_real) != DECIMAL_FLOAT_TYPE_P (real_tg_type)) continue; scalar_float_mode arg_mode = SCALAR_FLOAT_TYPE_MODE (arg_real); scalar_float_mode tg_mode = SCALAR_FLOAT_TYPE_MODE (real_tg_type); const real_format *arg_fmt = REAL_MODE_FORMAT (arg_mode); const real_format *tg_fmt = REAL_MODE_FORMAT (tg_mode); if (arg_fmt->b == tg_fmt->b && arg_fmt->p <= tg_fmt->p && arg_fmt->emax <= tg_fmt->emax && (arg_fmt->emin - arg_fmt->p >= tg_fmt->emin - tg_fmt->p)) { fn = &(*cexpr_list)[j]; break; } } } if (fn == NULL) { error_at (loc, "no matching function for type-generic call"); expr.set_error (); break; } /* Construct a call to FN. */ vec<tree, va_gc> *args; vec_alloc (args, nargs); vec<tree, va_gc> *origtypes; vec_alloc (origtypes, nargs); auto_vec<location_t> arg_loc (nargs); for (unsigned int j = 0; j < nargs; j++) { c_expr_t *ce = &(*cexpr_list)[num_functions + j]; args->quick_push (ce->value); arg_loc.quick_push (ce->get_location ()); origtypes->quick_push (ce->original_type); } expr.value = c_build_function_call_vec (loc, arg_loc, fn->value, args, origtypes); set_c_expr_source_range (&expr, loc, close_paren_loc); break; } case RID_BUILTIN_CALL_WITH_STATIC_CHAIN: { vec<c_expr_t, va_gc> *cexpr_list; c_expr_t *e2_p; tree chain_value; location_t close_paren_loc; c_parser_consume_token (parser); if (!c_parser_get_builtin_args (parser, "__builtin_call_with_static_chain", &cexpr_list, false, &close_paren_loc)) { expr.set_error (); break; } if (vec_safe_length (cexpr_list) != 2) { error_at (loc, "wrong number of arguments to " "%<__builtin_call_with_static_chain%>"); expr.set_error (); break; } expr = (*cexpr_list)[0]; e2_p = &(*cexpr_list)[1]; *e2_p = convert_lvalue_to_rvalue (loc, *e2_p, true, true); chain_value = e2_p->value; mark_exp_read (chain_value); if (TREE_CODE (expr.value) != CALL_EXPR) error_at (loc, "first argument to " "%<__builtin_call_with_static_chain%> " "must be a call expression"); else if (TREE_CODE (TREE_TYPE (chain_value)) != POINTER_TYPE) error_at (loc, "second argument to " "%<__builtin_call_with_static_chain%> " "must be a pointer type"); else CALL_EXPR_STATIC_CHAIN (expr.value) = chain_value; set_c_expr_source_range (&expr, loc, close_paren_loc); break; } case RID_BUILTIN_COMPLEX: { vec<c_expr_t, va_gc> *cexpr_list; c_expr_t *e1_p, *e2_p; location_t close_paren_loc; c_parser_consume_token (parser); if (!c_parser_get_builtin_args (parser, "__builtin_complex", &cexpr_list, false, &close_paren_loc)) { expr.set_error (); break; } if (vec_safe_length (cexpr_list) != 2) { error_at (loc, "wrong number of arguments to " "%<__builtin_complex%>"); expr.set_error (); break; } e1_p = &(*cexpr_list)[0]; e2_p = &(*cexpr_list)[1]; *e1_p = convert_lvalue_to_rvalue (loc, *e1_p, true, true); if (TREE_CODE (e1_p->value) == EXCESS_PRECISION_EXPR) e1_p->value = convert (TREE_TYPE (e1_p->value), TREE_OPERAND (e1_p->value, 0)); *e2_p = convert_lvalue_to_rvalue (loc, *e2_p, true, true); if (TREE_CODE (e2_p->value) == EXCESS_PRECISION_EXPR) e2_p->value = convert (TREE_TYPE (e2_p->value), TREE_OPERAND (e2_p->value, 0)); if (!SCALAR_FLOAT_TYPE_P (TREE_TYPE (e1_p->value)) || DECIMAL_FLOAT_TYPE_P (TREE_TYPE (e1_p->value)) || !SCALAR_FLOAT_TYPE_P (TREE_TYPE (e2_p->value)) || DECIMAL_FLOAT_TYPE_P (TREE_TYPE (e2_p->value))) { error_at (loc, "%<__builtin_complex%> operand " "not of real binary floating-point type"); expr.set_error (); break; } if (TYPE_MAIN_VARIANT (TREE_TYPE (e1_p->value)) != TYPE_MAIN_VARIANT (TREE_TYPE (e2_p->value))) { error_at (loc, "%<__builtin_complex%> operands of different types"); expr.set_error (); break; } pedwarn_c90 (loc, OPT_Wpedantic, "ISO C90 does not support complex types"); expr.value = build2_loc (loc, COMPLEX_EXPR, build_complex_type (TYPE_MAIN_VARIANT (TREE_TYPE (e1_p->value))), e1_p->value, e2_p->value); set_c_expr_source_range (&expr, loc, close_paren_loc); break; } case RID_BUILTIN_SHUFFLE: { vec<c_expr_t, va_gc> *cexpr_list; unsigned int i; c_expr_t *p; location_t close_paren_loc; c_parser_consume_token (parser); if (!c_parser_get_builtin_args (parser, "__builtin_shuffle", &cexpr_list, false, &close_paren_loc)) { expr.set_error (); break; } FOR_EACH_VEC_SAFE_ELT (cexpr_list, i, p) *p = convert_lvalue_to_rvalue (loc, *p, true, true); if (vec_safe_length (cexpr_list) == 2) expr.value = c_build_vec_perm_expr (loc, (*cexpr_list)[0].value, NULL_TREE, (*cexpr_list)[1].value); else if (vec_safe_length (cexpr_list) == 3) expr.value = c_build_vec_perm_expr (loc, (*cexpr_list)[0].value, (*cexpr_list)[1].value, (*cexpr_list)[2].value); else { error_at (loc, "wrong number of arguments to " "%<__builtin_shuffle%>"); expr.set_error (); } set_c_expr_source_range (&expr, loc, close_paren_loc); break; } case RID_AT_SELECTOR: { gcc_assert (c_dialect_objc ()); c_parser_consume_token (parser); matching_parens parens; if (!parens.require_open (parser)) { expr.set_error (); break; } tree sel = c_parser_objc_selector_arg (parser); location_t close_loc = c_parser_peek_token (parser)->location; parens.skip_until_found_close (parser); expr.value = objc_build_selector_expr (loc, sel); set_c_expr_source_range (&expr, loc, close_loc); } break; case RID_AT_PROTOCOL: { gcc_assert (c_dialect_objc ()); c_parser_consume_token (parser); matching_parens parens; if (!parens.require_open (parser)) { expr.set_error (); break; } if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); expr.set_error (); break; } tree id = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); location_t close_loc = c_parser_peek_token (parser)->location; parens.skip_until_found_close (parser); expr.value = objc_build_protocol_expr (id); set_c_expr_source_range (&expr, loc, close_loc); } break; case RID_AT_ENCODE: { /* Extension to support C-structures in the archiver. */ gcc_assert (c_dialect_objc ()); c_parser_consume_token (parser); matching_parens parens; if (!parens.require_open (parser)) { expr.set_error (); break; } t1 = c_parser_type_name (parser); if (t1 == NULL) { expr.set_error (); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); break; } location_t close_loc = c_parser_peek_token (parser)->location; parens.skip_until_found_close (parser); tree type = groktypename (t1, NULL, NULL); expr.value = objc_build_encode_expr (type); set_c_expr_source_range (&expr, loc, close_loc); } break; case RID_GENERIC: expr = c_parser_generic_selection (parser); break; default: c_parser_error (parser, "expected expression"); expr.set_error (); break; } break; case CPP_OPEN_SQUARE: if (c_dialect_objc ()) { tree receiver, args; c_parser_consume_token (parser); receiver = c_parser_objc_receiver (parser); args = c_parser_objc_message_args (parser); location_t close_loc = c_parser_peek_token (parser)->location; c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, "expected %<]%>"); expr.value = objc_build_message_expr (receiver, args); set_c_expr_source_range (&expr, loc, close_loc); break; } /* Else fall through to report error. */ /* FALLTHRU */ default: c_parser_error (parser, "expected expression"); expr.set_error (); break; } out: return c_parser_postfix_expression_after_primary (parser, EXPR_LOC_OR_LOC (expr.value, loc), expr); } /* Parse a postfix expression after a parenthesized type name: the brace-enclosed initializer of a compound literal, possibly followed by some postfix operators. This is separate because it is not possible to tell until after the type name whether a cast expression has a cast or a compound literal, or whether the operand of sizeof is a parenthesized type name or starts with a compound literal. TYPE_LOC is the location where TYPE_NAME starts--the location of the first token after the parentheses around the type name. */ static struct c_expr c_parser_postfix_expression_after_paren_type (c_parser *parser, struct c_type_name *type_name, location_t type_loc) { tree type; struct c_expr init; bool non_const; struct c_expr expr; location_t start_loc; tree type_expr = NULL_TREE; bool type_expr_const = true; check_compound_literal_type (type_loc, type_name); rich_location richloc (line_table, type_loc); start_init (NULL_TREE, NULL, 0, &richloc); type = groktypename (type_name, &type_expr, &type_expr_const); start_loc = c_parser_peek_token (parser)->location; if (type != error_mark_node && C_TYPE_VARIABLE_SIZE (type)) { error_at (type_loc, "compound literal has variable size"); type = error_mark_node; } init = c_parser_braced_init (parser, type, false, NULL); finish_init (); maybe_warn_string_init (type_loc, type, init); if (type != error_mark_node && !ADDR_SPACE_GENERIC_P (TYPE_ADDR_SPACE (type)) && current_function_decl) { error ("compound literal qualified by address-space qualifier"); type = error_mark_node; } pedwarn_c90 (start_loc, OPT_Wpedantic, "ISO C90 forbids compound literals"); non_const = ((init.value && TREE_CODE (init.value) == CONSTRUCTOR) ? CONSTRUCTOR_NON_CONST (init.value) : init.original_code == C_MAYBE_CONST_EXPR); non_const |= !type_expr_const; unsigned int alignas_align = 0; if (type != error_mark_node && type_name->specs->align_log != -1) { alignas_align = 1U << type_name->specs->align_log; if (alignas_align < min_align_of_type (type)) { error_at (type_name->specs->locations[cdw_alignas], "%<_Alignas%> specifiers cannot reduce " "alignment of compound literal"); alignas_align = 0; } } expr.value = build_compound_literal (start_loc, type, init.value, non_const, alignas_align); set_c_expr_source_range (&expr, init.src_range); expr.original_code = ERROR_MARK; expr.original_type = NULL; if (type != error_mark_node && expr.value != error_mark_node && type_expr) { if (TREE_CODE (expr.value) == C_MAYBE_CONST_EXPR) { gcc_assert (C_MAYBE_CONST_EXPR_PRE (expr.value) == NULL_TREE); C_MAYBE_CONST_EXPR_PRE (expr.value) = type_expr; } else { gcc_assert (!non_const); expr.value = build2 (C_MAYBE_CONST_EXPR, type, type_expr, expr.value); } } return c_parser_postfix_expression_after_primary (parser, start_loc, expr); } /* Callback function for sizeof_pointer_memaccess_warning to compare types. */ static bool sizeof_ptr_memacc_comptypes (tree type1, tree type2) { return comptypes (type1, type2) == 1; } /* Parse a postfix expression after the initial primary or compound literal; that is, parse a series of postfix operators. EXPR_LOC is the location of the primary expression. */ static struct c_expr c_parser_postfix_expression_after_primary (c_parser *parser, location_t expr_loc, struct c_expr expr) { struct c_expr orig_expr; tree ident, idx; location_t sizeof_arg_loc[3], comp_loc; tree sizeof_arg[3]; unsigned int literal_zero_mask; unsigned int i; vec<tree, va_gc> *exprlist; vec<tree, va_gc> *origtypes = NULL; vec<location_t> arg_loc = vNULL; location_t start; location_t finish; while (true) { location_t op_loc = c_parser_peek_token (parser)->location; switch (c_parser_peek_token (parser)->type) { case CPP_OPEN_SQUARE: /* Array reference. */ c_parser_consume_token (parser); idx = c_parser_expression (parser).value; c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, "expected %<]%>"); start = expr.get_start (); finish = parser->tokens_buf[0].location; expr.value = build_array_ref (op_loc, expr.value, idx); set_c_expr_source_range (&expr, start, finish); expr.original_code = ERROR_MARK; expr.original_type = NULL; break; case CPP_OPEN_PAREN: /* Function call. */ c_parser_consume_token (parser); for (i = 0; i < 3; i++) { sizeof_arg[i] = NULL_TREE; sizeof_arg_loc[i] = UNKNOWN_LOCATION; } literal_zero_mask = 0; if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) exprlist = NULL; else exprlist = c_parser_expr_list (parser, true, false, &origtypes, sizeof_arg_loc, sizeof_arg, &arg_loc, &literal_zero_mask); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); orig_expr = expr; mark_exp_read (expr.value); if (warn_sizeof_pointer_memaccess) sizeof_pointer_memaccess_warning (sizeof_arg_loc, expr.value, exprlist, sizeof_arg, sizeof_ptr_memacc_comptypes); if (TREE_CODE (expr.value) == FUNCTION_DECL && DECL_BUILT_IN_CLASS (expr.value) == BUILT_IN_NORMAL && DECL_FUNCTION_CODE (expr.value) == BUILT_IN_MEMSET && vec_safe_length (exprlist) == 3) { tree arg0 = (*exprlist)[0]; tree arg2 = (*exprlist)[2]; warn_for_memset (expr_loc, arg0, arg2, literal_zero_mask); } start = expr.get_start (); finish = parser->tokens_buf[0].get_finish (); expr.value = c_build_function_call_vec (expr_loc, arg_loc, expr.value, exprlist, origtypes); set_c_expr_source_range (&expr, start, finish); expr.original_code = ERROR_MARK; if (TREE_CODE (expr.value) == INTEGER_CST && TREE_CODE (orig_expr.value) == FUNCTION_DECL && DECL_BUILT_IN_CLASS (orig_expr.value) == BUILT_IN_NORMAL && DECL_FUNCTION_CODE (orig_expr.value) == BUILT_IN_CONSTANT_P) expr.original_code = C_MAYBE_CONST_EXPR; expr.original_type = NULL; if (exprlist) { release_tree_vector (exprlist); release_tree_vector (origtypes); } arg_loc.release (); break; case CPP_DOT: /* Structure element reference. */ c_parser_consume_token (parser); expr = default_function_array_conversion (expr_loc, expr); if (c_parser_next_token_is (parser, CPP_NAME)) { c_token *comp_tok = c_parser_peek_token (parser); ident = comp_tok->value; comp_loc = comp_tok->location; } else { c_parser_error (parser, "expected identifier"); expr.set_error (); expr.original_code = ERROR_MARK; expr.original_type = NULL; return expr; } start = expr.get_start (); finish = c_parser_peek_token (parser)->get_finish (); c_parser_consume_token (parser); expr.value = build_component_ref (op_loc, expr.value, ident, comp_loc); set_c_expr_source_range (&expr, start, finish); expr.original_code = ERROR_MARK; if (TREE_CODE (expr.value) != COMPONENT_REF) expr.original_type = NULL; else { /* Remember the original type of a bitfield. */ tree field = TREE_OPERAND (expr.value, 1); if (TREE_CODE (field) != FIELD_DECL) expr.original_type = NULL; else expr.original_type = DECL_BIT_FIELD_TYPE (field); } break; case CPP_DEREF: /* Structure element reference. */ c_parser_consume_token (parser); expr = convert_lvalue_to_rvalue (expr_loc, expr, true, false); if (c_parser_next_token_is (parser, CPP_NAME)) { c_token *comp_tok = c_parser_peek_token (parser); ident = comp_tok->value; comp_loc = comp_tok->location; } else { c_parser_error (parser, "expected identifier"); expr.set_error (); expr.original_code = ERROR_MARK; expr.original_type = NULL; return expr; } start = expr.get_start (); finish = c_parser_peek_token (parser)->get_finish (); c_parser_consume_token (parser); expr.value = build_component_ref (op_loc, build_indirect_ref (op_loc, expr.value, RO_ARROW), ident, comp_loc); set_c_expr_source_range (&expr, start, finish); expr.original_code = ERROR_MARK; if (TREE_CODE (expr.value) != COMPONENT_REF) expr.original_type = NULL; else { /* Remember the original type of a bitfield. */ tree field = TREE_OPERAND (expr.value, 1); if (TREE_CODE (field) != FIELD_DECL) expr.original_type = NULL; else expr.original_type = DECL_BIT_FIELD_TYPE (field); } break; case CPP_PLUS_PLUS: /* Postincrement. */ start = expr.get_start (); finish = c_parser_peek_token (parser)->get_finish (); c_parser_consume_token (parser); expr = default_function_array_read_conversion (expr_loc, expr); expr.value = build_unary_op (op_loc, POSTINCREMENT_EXPR, expr.value, false); set_c_expr_source_range (&expr, start, finish); expr.original_code = ERROR_MARK; expr.original_type = NULL; break; case CPP_MINUS_MINUS: /* Postdecrement. */ start = expr.get_start (); finish = c_parser_peek_token (parser)->get_finish (); c_parser_consume_token (parser); expr = default_function_array_read_conversion (expr_loc, expr); expr.value = build_unary_op (op_loc, POSTDECREMENT_EXPR, expr.value, false); set_c_expr_source_range (&expr, start, finish); expr.original_code = ERROR_MARK; expr.original_type = NULL; break; default: return expr; } } } /* Parse an expression (C90 6.3.17, C99 6.5.17, C11 6.5.17). expression: assignment-expression expression , assignment-expression */ static struct c_expr c_parser_expression (c_parser *parser) { location_t tloc = c_parser_peek_token (parser)->location; struct c_expr expr; expr = c_parser_expr_no_commas (parser, NULL); if (c_parser_next_token_is (parser, CPP_COMMA)) expr = convert_lvalue_to_rvalue (tloc, expr, true, false); while (c_parser_next_token_is (parser, CPP_COMMA)) { struct c_expr next; tree lhsval; location_t loc = c_parser_peek_token (parser)->location; location_t expr_loc; c_parser_consume_token (parser); expr_loc = c_parser_peek_token (parser)->location; lhsval = expr.value; while (TREE_CODE (lhsval) == COMPOUND_EXPR) lhsval = TREE_OPERAND (lhsval, 1); if (DECL_P (lhsval) || handled_component_p (lhsval)) mark_exp_read (lhsval); next = c_parser_expr_no_commas (parser, NULL); next = convert_lvalue_to_rvalue (expr_loc, next, true, false); expr.value = build_compound_expr (loc, expr.value, next.value); expr.original_code = COMPOUND_EXPR; expr.original_type = next.original_type; } return expr; } /* Parse an expression and convert functions or arrays to pointers and lvalues to rvalues. */ static struct c_expr c_parser_expression_conv (c_parser *parser) { struct c_expr expr; location_t loc = c_parser_peek_token (parser)->location; expr = c_parser_expression (parser); expr = convert_lvalue_to_rvalue (loc, expr, true, false); return expr; } /* Helper function of c_parser_expr_list. Check if IDXth (0 based) argument is a literal zero alone and if so, set it in literal_zero_mask. */ static inline void c_parser_check_literal_zero (c_parser *parser, unsigned *literal_zero_mask, unsigned int idx) { if (idx >= HOST_BITS_PER_INT) return; c_token *tok = c_parser_peek_token (parser); switch (tok->type) { case CPP_NUMBER: case CPP_CHAR: case CPP_WCHAR: case CPP_CHAR16: case CPP_CHAR32: /* If a parameter is literal zero alone, remember it for -Wmemset-transposed-args warning. */ if (integer_zerop (tok->value) && !TREE_OVERFLOW (tok->value) && (c_parser_peek_2nd_token (parser)->type == CPP_COMMA || c_parser_peek_2nd_token (parser)->type == CPP_CLOSE_PAREN)) *literal_zero_mask |= 1U << idx; default: break; } } /* Parse a non-empty list of expressions. If CONVERT_P, convert functions and arrays to pointers and lvalues to rvalues. If FOLD_P, fold the expressions. If LOCATIONS is non-NULL, save the locations of function arguments into this vector. nonempty-expr-list: assignment-expression nonempty-expr-list , assignment-expression */ static vec<tree, va_gc> * c_parser_expr_list (c_parser *parser, bool convert_p, bool fold_p, vec<tree, va_gc> **p_orig_types, location_t *sizeof_arg_loc, tree *sizeof_arg, vec<location_t> *locations, unsigned int *literal_zero_mask) { vec<tree, va_gc> *ret; vec<tree, va_gc> *orig_types; struct c_expr expr; unsigned int idx = 0; ret = make_tree_vector (); if (p_orig_types == NULL) orig_types = NULL; else orig_types = make_tree_vector (); if (literal_zero_mask) c_parser_check_literal_zero (parser, literal_zero_mask, 0); expr = c_parser_expr_no_commas (parser, NULL); if (convert_p) expr = convert_lvalue_to_rvalue (expr.get_location (), expr, true, true); if (fold_p) expr.value = c_fully_fold (expr.value, false, NULL); ret->quick_push (expr.value); if (orig_types) orig_types->quick_push (expr.original_type); if (locations) locations->safe_push (expr.get_location ()); if (sizeof_arg != NULL && expr.original_code == SIZEOF_EXPR) { sizeof_arg[0] = c_last_sizeof_arg; sizeof_arg_loc[0] = c_last_sizeof_loc; } while (c_parser_next_token_is (parser, CPP_COMMA)) { c_parser_consume_token (parser); if (literal_zero_mask) c_parser_check_literal_zero (parser, literal_zero_mask, idx + 1); expr = c_parser_expr_no_commas (parser, NULL); if (convert_p) expr = convert_lvalue_to_rvalue (expr.get_location (), expr, true, true); if (fold_p) expr.value = c_fully_fold (expr.value, false, NULL); vec_safe_push (ret, expr.value); if (orig_types) vec_safe_push (orig_types, expr.original_type); if (locations) locations->safe_push (expr.get_location ()); if (++idx < 3 && sizeof_arg != NULL && expr.original_code == SIZEOF_EXPR) { sizeof_arg[idx] = c_last_sizeof_arg; sizeof_arg_loc[idx] = c_last_sizeof_loc; } } if (orig_types) *p_orig_types = orig_types; return ret; } /* Parse Objective-C-specific constructs. */ /* Parse an objc-class-definition. objc-class-definition: @interface identifier objc-superclass[opt] objc-protocol-refs[opt] objc-class-instance-variables[opt] objc-methodprotolist @end @implementation identifier objc-superclass[opt] objc-class-instance-variables[opt] @interface identifier ( identifier ) objc-protocol-refs[opt] objc-methodprotolist @end @interface identifier ( ) objc-protocol-refs[opt] objc-methodprotolist @end @implementation identifier ( identifier ) objc-superclass: : identifier "@interface identifier (" must start "@interface identifier ( identifier ) ...": objc-methodprotolist in the first production may not start with a parenthesized identifier as a declarator of a data definition with no declaration specifiers if the objc-superclass, objc-protocol-refs and objc-class-instance-variables are omitted. */ static void c_parser_objc_class_definition (c_parser *parser, tree attributes) { bool iface_p; tree id1; tree superclass; if (c_parser_next_token_is_keyword (parser, RID_AT_INTERFACE)) iface_p = true; else if (c_parser_next_token_is_keyword (parser, RID_AT_IMPLEMENTATION)) iface_p = false; else gcc_unreachable (); c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); return; } id1 = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { /* We have a category or class extension. */ tree id2; tree proto = NULL_TREE; matching_parens parens; parens.consume_open (parser); if (c_parser_next_token_is_not (parser, CPP_NAME)) { if (iface_p && c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { /* We have a class extension. */ id2 = NULL_TREE; } else { c_parser_error (parser, "expected identifier or %<)%>"); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return; } } else { id2 = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); } parens.skip_until_found_close (parser); if (!iface_p) { objc_start_category_implementation (id1, id2); return; } if (c_parser_next_token_is (parser, CPP_LESS)) proto = c_parser_objc_protocol_refs (parser); objc_start_category_interface (id1, id2, proto, attributes); c_parser_objc_methodprotolist (parser); c_parser_require_keyword (parser, RID_AT_END, "expected %<@end%>"); objc_finish_interface (); return; } if (c_parser_next_token_is (parser, CPP_COLON)) { c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); return; } superclass = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); } else superclass = NULL_TREE; if (iface_p) { tree proto = NULL_TREE; if (c_parser_next_token_is (parser, CPP_LESS)) proto = c_parser_objc_protocol_refs (parser); objc_start_class_interface (id1, superclass, proto, attributes); } else objc_start_class_implementation (id1, superclass); if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) c_parser_objc_class_instance_variables (parser); if (iface_p) { objc_continue_interface (); c_parser_objc_methodprotolist (parser); c_parser_require_keyword (parser, RID_AT_END, "expected %<@end%>"); objc_finish_interface (); } else { objc_continue_implementation (); return; } } /* Parse objc-class-instance-variables. objc-class-instance-variables: { objc-instance-variable-decl-list[opt] } objc-instance-variable-decl-list: objc-visibility-spec objc-instance-variable-decl ; ; objc-instance-variable-decl-list objc-visibility-spec objc-instance-variable-decl-list objc-instance-variable-decl ; objc-instance-variable-decl-list ; objc-visibility-spec: @private @protected @public objc-instance-variable-decl: struct-declaration */ static void c_parser_objc_class_instance_variables (c_parser *parser) { gcc_assert (c_parser_next_token_is (parser, CPP_OPEN_BRACE)); c_parser_consume_token (parser); while (c_parser_next_token_is_not (parser, CPP_EOF)) { tree decls; /* Parse any stray semicolon. */ if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { pedwarn (c_parser_peek_token (parser)->location, OPT_Wpedantic, "extra semicolon"); c_parser_consume_token (parser); continue; } /* Stop if at the end of the instance variables. */ if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { c_parser_consume_token (parser); break; } /* Parse any objc-visibility-spec. */ if (c_parser_next_token_is_keyword (parser, RID_AT_PRIVATE)) { c_parser_consume_token (parser); objc_set_visibility (OBJC_IVAR_VIS_PRIVATE); continue; } else if (c_parser_next_token_is_keyword (parser, RID_AT_PROTECTED)) { c_parser_consume_token (parser); objc_set_visibility (OBJC_IVAR_VIS_PROTECTED); continue; } else if (c_parser_next_token_is_keyword (parser, RID_AT_PUBLIC)) { c_parser_consume_token (parser); objc_set_visibility (OBJC_IVAR_VIS_PUBLIC); continue; } else if (c_parser_next_token_is_keyword (parser, RID_AT_PACKAGE)) { c_parser_consume_token (parser); objc_set_visibility (OBJC_IVAR_VIS_PACKAGE); continue; } else if (c_parser_next_token_is (parser, CPP_PRAGMA)) { c_parser_pragma (parser, pragma_external, NULL); continue; } /* Parse some comma-separated declarations. */ decls = c_parser_struct_declaration (parser); if (decls == NULL) { /* There is a syntax error. We want to skip the offending tokens up to the next ';' (included) or '}' (excluded). */ /* First, skip manually a ')' or ']'. This is because they reduce the nesting level, so c_parser_skip_until_found() wouldn't be able to skip past them. */ c_token *token = c_parser_peek_token (parser); if (token->type == CPP_CLOSE_PAREN || token->type == CPP_CLOSE_SQUARE) c_parser_consume_token (parser); /* Then, do the standard skipping. */ c_parser_skip_until_found (parser, CPP_SEMICOLON, NULL); /* We hopefully recovered. Start normal parsing again. */ parser->error = false; continue; } else { /* Comma-separated instance variables are chained together in reverse order; add them one by one. */ tree ivar = nreverse (decls); for (; ivar; ivar = DECL_CHAIN (ivar)) objc_add_instance_variable (copy_node (ivar)); } c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } } /* Parse an objc-class-declaration. objc-class-declaration: @class identifier-list ; */ static void c_parser_objc_class_declaration (c_parser *parser) { gcc_assert (c_parser_next_token_is_keyword (parser, RID_AT_CLASS)); c_parser_consume_token (parser); /* Any identifiers, including those declared as type names, are OK here. */ while (true) { tree id; if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_SEMICOLON, NULL); parser->error = false; return; } id = c_parser_peek_token (parser)->value; objc_declare_class (id); c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; } c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } /* Parse an objc-alias-declaration. objc-alias-declaration: @compatibility_alias identifier identifier ; */ static void c_parser_objc_alias_declaration (c_parser *parser) { tree id1, id2; gcc_assert (c_parser_next_token_is_keyword (parser, RID_AT_ALIAS)); c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_SEMICOLON, NULL); return; } id1 = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_SEMICOLON, NULL); return; } id2 = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); objc_declare_alias (id1, id2); } /* Parse an objc-protocol-definition. objc-protocol-definition: @protocol identifier objc-protocol-refs[opt] objc-methodprotolist @end @protocol identifier-list ; "@protocol identifier ;" should be resolved as "@protocol identifier-list ;": objc-methodprotolist may not start with a semicolon in the first alternative if objc-protocol-refs are omitted. */ static void c_parser_objc_protocol_definition (c_parser *parser, tree attributes) { gcc_assert (c_parser_next_token_is_keyword (parser, RID_AT_PROTOCOL)); c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); return; } if (c_parser_peek_2nd_token (parser)->type == CPP_COMMA || c_parser_peek_2nd_token (parser)->type == CPP_SEMICOLON) { /* Any identifiers, including those declared as type names, are OK here. */ while (true) { tree id; if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); break; } id = c_parser_peek_token (parser)->value; objc_declare_protocol (id, attributes); c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; } c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } else { tree id = c_parser_peek_token (parser)->value; tree proto = NULL_TREE; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_LESS)) proto = c_parser_objc_protocol_refs (parser); parser->objc_pq_context = true; objc_start_protocol (id, proto, attributes); c_parser_objc_methodprotolist (parser); c_parser_require_keyword (parser, RID_AT_END, "expected %<@end%>"); parser->objc_pq_context = false; objc_finish_interface (); } } /* Parse an objc-method-type. objc-method-type: + - Return true if it is a class method (+) and false if it is an instance method (-). */ static inline bool c_parser_objc_method_type (c_parser *parser) { switch (c_parser_peek_token (parser)->type) { case CPP_PLUS: c_parser_consume_token (parser); return true; case CPP_MINUS: c_parser_consume_token (parser); return false; default: gcc_unreachable (); } } /* Parse an objc-method-definition. objc-method-definition: objc-method-type objc-method-decl ;[opt] compound-statement */ static void c_parser_objc_method_definition (c_parser *parser) { bool is_class_method = c_parser_objc_method_type (parser); tree decl, attributes = NULL_TREE, expr = NULL_TREE; parser->objc_pq_context = true; decl = c_parser_objc_method_decl (parser, is_class_method, &attributes, &expr); if (decl == error_mark_node) return; /* Bail here. */ if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { c_parser_consume_token (parser); pedwarn (c_parser_peek_token (parser)->location, OPT_Wpedantic, "extra semicolon in method definition specified"); } if (!c_parser_next_token_is (parser, CPP_OPEN_BRACE)) { c_parser_error (parser, "expected %<{%>"); return; } parser->objc_pq_context = false; if (objc_start_method_definition (is_class_method, decl, attributes, expr)) { add_stmt (c_parser_compound_statement (parser)); objc_finish_method_definition (current_function_decl); } else { /* This code is executed when we find a method definition outside of an @implementation context (or invalid for other reasons). Parse the method (to keep going) but do not emit any code. */ c_parser_compound_statement (parser); } } /* Parse an objc-methodprotolist. objc-methodprotolist: empty objc-methodprotolist objc-methodproto objc-methodprotolist declaration objc-methodprotolist ; @optional @required The declaration is a data definition, which may be missing declaration specifiers under the same rules and diagnostics as other data definitions outside functions, and the stray semicolon is diagnosed the same way as a stray semicolon outside a function. */ static void c_parser_objc_methodprotolist (c_parser *parser) { while (true) { /* The list is terminated by @end. */ switch (c_parser_peek_token (parser)->type) { case CPP_SEMICOLON: pedwarn (c_parser_peek_token (parser)->location, OPT_Wpedantic, "ISO C does not allow extra %<;%> outside of a function"); c_parser_consume_token (parser); break; case CPP_PLUS: case CPP_MINUS: c_parser_objc_methodproto (parser); break; case CPP_PRAGMA: c_parser_pragma (parser, pragma_external, NULL); break; case CPP_EOF: return; default: if (c_parser_next_token_is_keyword (parser, RID_AT_END)) return; else if (c_parser_next_token_is_keyword (parser, RID_AT_PROPERTY)) c_parser_objc_at_property_declaration (parser); else if (c_parser_next_token_is_keyword (parser, RID_AT_OPTIONAL)) { objc_set_method_opt (true); c_parser_consume_token (parser); } else if (c_parser_next_token_is_keyword (parser, RID_AT_REQUIRED)) { objc_set_method_opt (false); c_parser_consume_token (parser); } else c_parser_declaration_or_fndef (parser, false, false, true, false, true, NULL, vNULL); break; } } } /* Parse an objc-methodproto. objc-methodproto: objc-method-type objc-method-decl ; */ static void c_parser_objc_methodproto (c_parser *parser) { bool is_class_method = c_parser_objc_method_type (parser); tree decl, attributes = NULL_TREE; /* Remember protocol qualifiers in prototypes. */ parser->objc_pq_context = true; decl = c_parser_objc_method_decl (parser, is_class_method, &attributes, NULL); /* Forget protocol qualifiers now. */ parser->objc_pq_context = false; /* Do not allow the presence of attributes to hide an erroneous method implementation in the interface section. */ if (!c_parser_next_token_is (parser, CPP_SEMICOLON)) { c_parser_error (parser, "expected %<;%>"); return; } if (decl != error_mark_node) objc_add_method_declaration (is_class_method, decl, attributes); c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } /* If we are at a position that method attributes may be present, check that there are not any parsed already (a syntax error) and then collect any specified at the current location. Finally, if new attributes were present, check that the next token is legal ( ';' for decls and '{' for defs). */ static bool c_parser_objc_maybe_method_attributes (c_parser* parser, tree* attributes) { bool bad = false; if (*attributes) { c_parser_error (parser, "method attributes must be specified at the end only"); *attributes = NULL_TREE; bad = true; } if (c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) *attributes = c_parser_attributes (parser); /* If there were no attributes here, just report any earlier error. */ if (*attributes == NULL_TREE || bad) return bad; /* If the attributes are followed by a ; or {, then just report any earlier error. */ if (c_parser_next_token_is (parser, CPP_SEMICOLON) || c_parser_next_token_is (parser, CPP_OPEN_BRACE)) return bad; /* We've got attributes, but not at the end. */ c_parser_error (parser, "expected %<;%> or %<{%> after method attribute definition"); return true; } /* Parse an objc-method-decl. objc-method-decl: ( objc-type-name ) objc-selector objc-selector ( objc-type-name ) objc-keyword-selector objc-optparmlist objc-keyword-selector objc-optparmlist attributes objc-keyword-selector: objc-keyword-decl objc-keyword-selector objc-keyword-decl objc-keyword-decl: objc-selector : ( objc-type-name ) identifier objc-selector : identifier : ( objc-type-name ) identifier : identifier objc-optparmlist: objc-optparms objc-optellipsis objc-optparms: empty objc-opt-parms , parameter-declaration objc-optellipsis: empty , ... */ static tree c_parser_objc_method_decl (c_parser *parser, bool is_class_method, tree *attributes, tree *expr) { tree type = NULL_TREE; tree sel; tree parms = NULL_TREE; bool ellipsis = false; bool attr_err = false; *attributes = NULL_TREE; if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { matching_parens parens; parens.consume_open (parser); type = c_parser_objc_type_name (parser); parens.skip_until_found_close (parser); } sel = c_parser_objc_selector (parser); /* If there is no selector, or a colon follows, we have an objc-keyword-selector. If there is a selector, and a colon does not follow, that selector ends the objc-method-decl. */ if (!sel || c_parser_next_token_is (parser, CPP_COLON)) { tree tsel = sel; tree list = NULL_TREE; while (true) { tree atype = NULL_TREE, id, keyworddecl; tree param_attr = NULL_TREE; if (!c_parser_require (parser, CPP_COLON, "expected %<:%>")) break; if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { c_parser_consume_token (parser); atype = c_parser_objc_type_name (parser); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); } /* New ObjC allows attributes on method parameters. */ if (c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) param_attr = c_parser_attributes (parser); if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); return error_mark_node; } id = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); keyworddecl = objc_build_keyword_decl (tsel, atype, id, param_attr); list = chainon (list, keyworddecl); tsel = c_parser_objc_selector (parser); if (!tsel && c_parser_next_token_is_not (parser, CPP_COLON)) break; } attr_err |= c_parser_objc_maybe_method_attributes (parser, attributes) ; /* Parse the optional parameter list. Optional Objective-C method parameters follow the C syntax, and may include '...' to denote a variable number of arguments. */ parms = make_node (TREE_LIST); while (c_parser_next_token_is (parser, CPP_COMMA)) { struct c_parm *parm; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_ELLIPSIS)) { ellipsis = true; c_parser_consume_token (parser); attr_err |= c_parser_objc_maybe_method_attributes (parser, attributes) ; break; } parm = c_parser_parameter_declaration (parser, NULL_TREE); if (parm == NULL) break; parms = chainon (parms, build_tree_list (NULL_TREE, grokparm (parm, expr))); } sel = list; } else attr_err |= c_parser_objc_maybe_method_attributes (parser, attributes) ; if (sel == NULL) { c_parser_error (parser, "objective-c method declaration is expected"); return error_mark_node; } if (attr_err) return error_mark_node; return objc_build_method_signature (is_class_method, type, sel, parms, ellipsis); } /* Parse an objc-type-name. objc-type-name: objc-type-qualifiers[opt] type-name objc-type-qualifiers[opt] objc-type-qualifiers: objc-type-qualifier objc-type-qualifiers objc-type-qualifier objc-type-qualifier: one of in out inout bycopy byref oneway */ static tree c_parser_objc_type_name (c_parser *parser) { tree quals = NULL_TREE; struct c_type_name *type_name = NULL; tree type = NULL_TREE; while (true) { c_token *token = c_parser_peek_token (parser); if (token->type == CPP_KEYWORD && (token->keyword == RID_IN || token->keyword == RID_OUT || token->keyword == RID_INOUT || token->keyword == RID_BYCOPY || token->keyword == RID_BYREF || token->keyword == RID_ONEWAY)) { quals = chainon (build_tree_list (NULL_TREE, token->value), quals); c_parser_consume_token (parser); } else break; } if (c_parser_next_tokens_start_typename (parser, cla_prefer_type)) type_name = c_parser_type_name (parser); if (type_name) type = groktypename (type_name, NULL, NULL); /* If the type is unknown, and error has already been produced and we need to recover from the error. In that case, use NULL_TREE for the type, as if no type had been specified; this will use the default type ('id') which is good for error recovery. */ if (type == error_mark_node) type = NULL_TREE; return build_tree_list (quals, type); } /* Parse objc-protocol-refs. objc-protocol-refs: < identifier-list > */ static tree c_parser_objc_protocol_refs (c_parser *parser) { tree list = NULL_TREE; gcc_assert (c_parser_next_token_is (parser, CPP_LESS)); c_parser_consume_token (parser); /* Any identifiers, including those declared as type names, are OK here. */ while (true) { tree id; if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); break; } id = c_parser_peek_token (parser)->value; list = chainon (list, build_tree_list (NULL_TREE, id)); c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; } c_parser_require (parser, CPP_GREATER, "expected %<>%>"); return list; } /* Parse an objc-try-catch-finally-statement. objc-try-catch-finally-statement: @try compound-statement objc-catch-list[opt] @try compound-statement objc-catch-list[opt] @finally compound-statement objc-catch-list: @catch ( objc-catch-parameter-declaration ) compound-statement objc-catch-list @catch ( objc-catch-parameter-declaration ) compound-statement objc-catch-parameter-declaration: parameter-declaration '...' where '...' is to be interpreted literally, that is, it means CPP_ELLIPSIS. PS: This function is identical to cp_parser_objc_try_catch_finally_statement for C++. Keep them in sync. */ static void c_parser_objc_try_catch_finally_statement (c_parser *parser) { location_t location; tree stmt; gcc_assert (c_parser_next_token_is_keyword (parser, RID_AT_TRY)); c_parser_consume_token (parser); location = c_parser_peek_token (parser)->location; objc_maybe_warn_exceptions (location); stmt = c_parser_compound_statement (parser); objc_begin_try_stmt (location, stmt); while (c_parser_next_token_is_keyword (parser, RID_AT_CATCH)) { struct c_parm *parm; tree parameter_declaration = error_mark_node; bool seen_open_paren = false; c_parser_consume_token (parser); matching_parens parens; if (!parens.require_open (parser)) seen_open_paren = true; if (c_parser_next_token_is (parser, CPP_ELLIPSIS)) { /* We have "@catch (...)" (where the '...' are literally what is in the code). Skip the '...'. parameter_declaration is set to NULL_TREE, and objc_being_catch_clauses() knows that that means '...'. */ c_parser_consume_token (parser); parameter_declaration = NULL_TREE; } else { /* We have "@catch (NSException *exception)" or something like that. Parse the parameter declaration. */ parm = c_parser_parameter_declaration (parser, NULL_TREE); if (parm == NULL) parameter_declaration = error_mark_node; else parameter_declaration = grokparm (parm, NULL); } if (seen_open_paren) parens.require_close (parser); else { /* If there was no open parenthesis, we are recovering from an error, and we are trying to figure out what mistake the user has made. */ /* If there is an immediate closing parenthesis, the user probably forgot the opening one (ie, they typed "@catch NSException *e)". Parse the closing parenthesis and keep going. */ if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) c_parser_consume_token (parser); /* If these is no immediate closing parenthesis, the user probably doesn't know that parenthesis are required at all (ie, they typed "@catch NSException *e"). So, just forget about the closing parenthesis and keep going. */ } objc_begin_catch_clause (parameter_declaration); if (c_parser_require (parser, CPP_OPEN_BRACE, "expected %<{%>")) c_parser_compound_statement_nostart (parser); objc_finish_catch_clause (); } if (c_parser_next_token_is_keyword (parser, RID_AT_FINALLY)) { c_parser_consume_token (parser); location = c_parser_peek_token (parser)->location; stmt = c_parser_compound_statement (parser); objc_build_finally_clause (location, stmt); } objc_finish_try_stmt (); } /* Parse an objc-synchronized-statement. objc-synchronized-statement: @synchronized ( expression ) compound-statement */ static void c_parser_objc_synchronized_statement (c_parser *parser) { location_t loc; tree expr, stmt; gcc_assert (c_parser_next_token_is_keyword (parser, RID_AT_SYNCHRONIZED)); c_parser_consume_token (parser); loc = c_parser_peek_token (parser)->location; objc_maybe_warn_exceptions (loc); matching_parens parens; if (parens.require_open (parser)) { struct c_expr ce = c_parser_expression (parser); ce = convert_lvalue_to_rvalue (loc, ce, false, false); expr = ce.value; expr = c_fully_fold (expr, false, NULL); parens.skip_until_found_close (parser); } else expr = error_mark_node; stmt = c_parser_compound_statement (parser); objc_build_synchronized (loc, expr, stmt); } /* Parse an objc-selector; return NULL_TREE without an error if the next token is not an objc-selector. objc-selector: identifier one of enum struct union if else while do for switch case default break continue return goto asm sizeof typeof __alignof unsigned long const short volatile signed restrict _Complex in out inout bycopy byref oneway int char float double void _Bool _Atomic ??? Why this selection of keywords but not, for example, storage class specifiers? */ static tree c_parser_objc_selector (c_parser *parser) { c_token *token = c_parser_peek_token (parser); tree value = token->value; if (token->type == CPP_NAME) { c_parser_consume_token (parser); return value; } if (token->type != CPP_KEYWORD) return NULL_TREE; switch (token->keyword) { case RID_ENUM: case RID_STRUCT: case RID_UNION: case RID_IF: case RID_ELSE: case RID_WHILE: case RID_DO: case RID_FOR: case RID_SWITCH: case RID_CASE: case RID_DEFAULT: case RID_BREAK: case RID_CONTINUE: case RID_RETURN: case RID_GOTO: case RID_ASM: case RID_SIZEOF: case RID_TYPEOF: case RID_ALIGNOF: case RID_UNSIGNED: case RID_LONG: case RID_CONST: case RID_SHORT: case RID_VOLATILE: case RID_SIGNED: case RID_RESTRICT: case RID_COMPLEX: case RID_IN: case RID_OUT: case RID_INOUT: case RID_BYCOPY: case RID_BYREF: case RID_ONEWAY: case RID_INT: case RID_CHAR: case RID_FLOAT: case RID_DOUBLE: CASE_RID_FLOATN_NX: case RID_VOID: case RID_BOOL: case RID_ATOMIC: case RID_AUTO_TYPE: case RID_INT_N_0: case RID_INT_N_1: case RID_INT_N_2: case RID_INT_N_3: c_parser_consume_token (parser); return value; default: return NULL_TREE; } } /* Parse an objc-selector-arg. objc-selector-arg: objc-selector objc-keywordname-list objc-keywordname-list: objc-keywordname objc-keywordname-list objc-keywordname objc-keywordname: objc-selector : : */ static tree c_parser_objc_selector_arg (c_parser *parser) { tree sel = c_parser_objc_selector (parser); tree list = NULL_TREE; if (sel && c_parser_next_token_is_not (parser, CPP_COLON)) return sel; while (true) { if (!c_parser_require (parser, CPP_COLON, "expected %<:%>")) return list; list = chainon (list, build_tree_list (sel, NULL_TREE)); sel = c_parser_objc_selector (parser); if (!sel && c_parser_next_token_is_not (parser, CPP_COLON)) break; } return list; } /* Parse an objc-receiver. objc-receiver: expression class-name type-name */ static tree c_parser_objc_receiver (c_parser *parser) { location_t loc = c_parser_peek_token (parser)->location; if (c_parser_peek_token (parser)->type == CPP_NAME && (c_parser_peek_token (parser)->id_kind == C_ID_TYPENAME || c_parser_peek_token (parser)->id_kind == C_ID_CLASSNAME)) { tree id = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); return objc_get_class_reference (id); } struct c_expr ce = c_parser_expression (parser); ce = convert_lvalue_to_rvalue (loc, ce, false, false); return c_fully_fold (ce.value, false, NULL); } /* Parse objc-message-args. objc-message-args: objc-selector objc-keywordarg-list objc-keywordarg-list: objc-keywordarg objc-keywordarg-list objc-keywordarg objc-keywordarg: objc-selector : objc-keywordexpr : objc-keywordexpr */ static tree c_parser_objc_message_args (c_parser *parser) { tree sel = c_parser_objc_selector (parser); tree list = NULL_TREE; if (sel && c_parser_next_token_is_not (parser, CPP_COLON)) return sel; while (true) { tree keywordexpr; if (!c_parser_require (parser, CPP_COLON, "expected %<:%>")) return error_mark_node; keywordexpr = c_parser_objc_keywordexpr (parser); list = chainon (list, build_tree_list (sel, keywordexpr)); sel = c_parser_objc_selector (parser); if (!sel && c_parser_next_token_is_not (parser, CPP_COLON)) break; } return list; } /* Parse an objc-keywordexpr. objc-keywordexpr: nonempty-expr-list */ static tree c_parser_objc_keywordexpr (c_parser *parser) { tree ret; vec<tree, va_gc> *expr_list = c_parser_expr_list (parser, true, true, NULL, NULL, NULL, NULL); if (vec_safe_length (expr_list) == 1) { /* Just return the expression, remove a level of indirection. */ ret = (*expr_list)[0]; } else { /* We have a comma expression, we will collapse later. */ ret = build_tree_list_vec (expr_list); } release_tree_vector (expr_list); return ret; } /* A check, needed in several places, that ObjC interface, implementation or method definitions are not prefixed by incorrect items. */ static bool c_parser_objc_diagnose_bad_element_prefix (c_parser *parser, struct c_declspecs *specs) { if (!specs->declspecs_seen_p || specs->non_sc_seen_p || specs->typespec_kind != ctsk_none) { c_parser_error (parser, "no type or storage class may be specified here,"); c_parser_skip_to_end_of_block_or_statement (parser); return true; } return false; } /* Parse an Objective-C @property declaration. The syntax is: objc-property-declaration: '@property' objc-property-attributes[opt] struct-declaration ; objc-property-attributes: '(' objc-property-attribute-list ')' objc-property-attribute-list: objc-property-attribute objc-property-attribute-list, objc-property-attribute objc-property-attribute 'getter' = identifier 'setter' = identifier 'readonly' 'readwrite' 'assign' 'retain' 'copy' 'nonatomic' For example: @property NSString *name; @property (readonly) id object; @property (retain, nonatomic, getter=getTheName) id name; @property int a, b, c; PS: This function is identical to cp_parser_objc_at_propery_declaration for C++. Keep them in sync. */ static void c_parser_objc_at_property_declaration (c_parser *parser) { /* The following variables hold the attributes of the properties as parsed. They are 'false' or 'NULL_TREE' if the attribute was not seen. When we see an attribute, we set them to 'true' (if they are boolean properties) or to the identifier (if they have an argument, ie, for getter and setter). Note that here we only parse the list of attributes, check the syntax and accumulate the attributes that we find. objc_add_property_declaration() will then process the information. */ bool property_assign = false; bool property_copy = false; tree property_getter_ident = NULL_TREE; bool property_nonatomic = false; bool property_readonly = false; bool property_readwrite = false; bool property_retain = false; tree property_setter_ident = NULL_TREE; /* 'properties' is the list of properties that we read. Usually a single one, but maybe more (eg, in "@property int a, b, c;" there are three). */ tree properties; location_t loc; loc = c_parser_peek_token (parser)->location; gcc_assert (c_parser_next_token_is_keyword (parser, RID_AT_PROPERTY)); c_parser_consume_token (parser); /* Eat '@property'. */ /* Parse the optional attribute list... */ if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { matching_parens parens; /* Eat the '(' */ parens.consume_open (parser); /* Property attribute keywords are valid now. */ parser->objc_property_attr_context = true; while (true) { bool syntax_error = false; c_token *token = c_parser_peek_token (parser); enum rid keyword; if (token->type != CPP_KEYWORD) { if (token->type == CPP_CLOSE_PAREN) c_parser_error (parser, "expected identifier"); else { c_parser_consume_token (parser); c_parser_error (parser, "unknown property attribute"); } break; } keyword = token->keyword; c_parser_consume_token (parser); switch (keyword) { case RID_ASSIGN: property_assign = true; break; case RID_COPY: property_copy = true; break; case RID_NONATOMIC: property_nonatomic = true; break; case RID_READONLY: property_readonly = true; break; case RID_READWRITE: property_readwrite = true; break; case RID_RETAIN: property_retain = true; break; case RID_GETTER: case RID_SETTER: if (c_parser_next_token_is_not (parser, CPP_EQ)) { if (keyword == RID_GETTER) c_parser_error (parser, "missing %<=%> (after %<getter%> attribute)"); else c_parser_error (parser, "missing %<=%> (after %<setter%> attribute)"); syntax_error = true; break; } c_parser_consume_token (parser); /* eat the = */ if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); syntax_error = true; break; } if (keyword == RID_SETTER) { if (property_setter_ident != NULL_TREE) c_parser_error (parser, "the %<setter%> attribute may only be specified once"); else property_setter_ident = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_COLON)) c_parser_error (parser, "setter name must terminate with %<:%>"); else c_parser_consume_token (parser); } else { if (property_getter_ident != NULL_TREE) c_parser_error (parser, "the %<getter%> attribute may only be specified once"); else property_getter_ident = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); } break; default: c_parser_error (parser, "unknown property attribute"); syntax_error = true; break; } if (syntax_error) break; if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; } parser->objc_property_attr_context = false; parens.skip_until_found_close (parser); } /* ... and the property declaration(s). */ properties = c_parser_struct_declaration (parser); if (properties == error_mark_node) { c_parser_skip_until_found (parser, CPP_SEMICOLON, NULL); parser->error = false; return; } if (properties == NULL_TREE) c_parser_error (parser, "expected identifier"); else { /* Comma-separated properties are chained together in reverse order; add them one by one. */ properties = nreverse (properties); for (; properties; properties = TREE_CHAIN (properties)) objc_add_property_declaration (loc, copy_node (properties), property_readonly, property_readwrite, property_assign, property_retain, property_copy, property_nonatomic, property_getter_ident, property_setter_ident); } c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); parser->error = false; } /* Parse an Objective-C @synthesize declaration. The syntax is: objc-synthesize-declaration: @synthesize objc-synthesize-identifier-list ; objc-synthesize-identifier-list: objc-synthesize-identifier objc-synthesize-identifier-list, objc-synthesize-identifier objc-synthesize-identifier identifier identifier = identifier For example: @synthesize MyProperty; @synthesize OneProperty, AnotherProperty=MyIvar, YetAnotherProperty; PS: This function is identical to cp_parser_objc_at_synthesize_declaration for C++. Keep them in sync. */ static void c_parser_objc_at_synthesize_declaration (c_parser *parser) { tree list = NULL_TREE; location_t loc; gcc_assert (c_parser_next_token_is_keyword (parser, RID_AT_SYNTHESIZE)); loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); while (true) { tree property, ivar; if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_SEMICOLON, NULL); /* Once we find the semicolon, we can resume normal parsing. We have to reset parser->error manually because c_parser_skip_until_found() won't reset it for us if the next token is precisely a semicolon. */ parser->error = false; return; } property = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_EQ)) { c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_SEMICOLON, NULL); parser->error = false; return; } ivar = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); } else ivar = NULL_TREE; list = chainon (list, build_tree_list (ivar, property)); if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; } c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); objc_add_synthesize_declaration (loc, list); } /* Parse an Objective-C @dynamic declaration. The syntax is: objc-dynamic-declaration: @dynamic identifier-list ; For example: @dynamic MyProperty; @dynamic MyProperty, AnotherProperty; PS: This function is identical to cp_parser_objc_at_dynamic_declaration for C++. Keep them in sync. */ static void c_parser_objc_at_dynamic_declaration (c_parser *parser) { tree list = NULL_TREE; location_t loc; gcc_assert (c_parser_next_token_is_keyword (parser, RID_AT_DYNAMIC)); loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); while (true) { tree property; if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_SEMICOLON, NULL); parser->error = false; return; } property = c_parser_peek_token (parser)->value; list = chainon (list, build_tree_list (NULL_TREE, property)); c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; } c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); objc_add_dynamic_declaration (loc, list); } /* Parse a pragma GCC ivdep. */ static bool c_parse_pragma_ivdep (c_parser *parser) { c_parser_consume_pragma (parser); c_parser_skip_to_pragma_eol (parser); return true; } /* Parse a pragma GCC unroll. */ static unsigned short c_parser_pragma_unroll (c_parser *parser) { unsigned short unroll; c_parser_consume_pragma (parser); location_t location = c_parser_peek_token (parser)->location; tree expr = c_parser_expr_no_commas (parser, NULL).value; mark_exp_read (expr); expr = c_fully_fold (expr, false, NULL); HOST_WIDE_INT lunroll = 0; if (!INTEGRAL_TYPE_P (TREE_TYPE (expr)) || TREE_CODE (expr) != INTEGER_CST || (lunroll = tree_to_shwi (expr)) < 0 || lunroll >= USHRT_MAX) { error_at (location, "%<#pragma GCC unroll%> requires an" " assignment-expression that evaluates to a non-negative" " integral constant less than %u", USHRT_MAX); unroll = 0; } else { unroll = (unsigned short)lunroll; if (unroll == 0) unroll = 1; } c_parser_skip_to_pragma_eol (parser); return unroll; } /* Handle pragmas. Some OpenMP pragmas are associated with, and therefore should be considered, statements. ALLOW_STMT is true if we're within the context of a function and such pragmas are to be allowed. Returns true if we actually parsed such a pragma. */ static bool c_parser_pragma (c_parser *parser, enum pragma_context context, bool *if_p) { unsigned int id; const char *construct = NULL; id = c_parser_peek_token (parser)->pragma_kind; gcc_assert (id != PRAGMA_NONE); switch (id) { case PRAGMA_OACC_DECLARE: c_parser_oacc_declare (parser); return false; case PRAGMA_OACC_ENTER_DATA: if (context != pragma_compound) { construct = "acc enter data"; in_compound: if (context == pragma_stmt) { error_at (c_parser_peek_token (parser)->location, "%<#pragma %s%> may only be used in compound " "statements", construct); c_parser_skip_until_found (parser, CPP_PRAGMA_EOL, NULL); return false; } goto bad_stmt; } c_parser_oacc_enter_exit_data (parser, true); return false; case PRAGMA_OACC_EXIT_DATA: if (context != pragma_compound) { construct = "acc exit data"; goto in_compound; } c_parser_oacc_enter_exit_data (parser, false); return false; case PRAGMA_OACC_ROUTINE: if (context != pragma_external) { error_at (c_parser_peek_token (parser)->location, "%<#pragma acc routine%> must be at file scope"); c_parser_skip_until_found (parser, CPP_PRAGMA_EOL, NULL); return false; } c_parser_oacc_routine (parser, context); return false; case PRAGMA_OACC_UPDATE: if (context != pragma_compound) { construct = "acc update"; goto in_compound; } c_parser_oacc_update (parser); return false; case PRAGMA_OMP_BARRIER: if (context != pragma_compound) { construct = "omp barrier"; goto in_compound; } c_parser_omp_barrier (parser); return false; case PRAGMA_OMP_FLUSH: if (context != pragma_compound) { construct = "omp flush"; goto in_compound; } c_parser_omp_flush (parser); return false; case PRAGMA_OMP_TASKWAIT: if (context != pragma_compound) { construct = "omp taskwait"; goto in_compound; } c_parser_omp_taskwait (parser); return false; case PRAGMA_OMP_TASKYIELD: if (context != pragma_compound) { construct = "omp taskyield"; goto in_compound; } c_parser_omp_taskyield (parser); return false; case PRAGMA_OMP_CANCEL: if (context != pragma_compound) { construct = "omp cancel"; goto in_compound; } c_parser_omp_cancel (parser); return false; case PRAGMA_OMP_CANCELLATION_POINT: c_parser_omp_cancellation_point (parser, context); return false; case PRAGMA_OMP_THREADPRIVATE: c_parser_omp_threadprivate (parser); return false; case PRAGMA_OMP_TARGET: return c_parser_omp_target (parser, context, if_p); case PRAGMA_OMP_END_DECLARE_TARGET: c_parser_omp_end_declare_target (parser); return false; case PRAGMA_OMP_SECTION: error_at (c_parser_peek_token (parser)->location, "%<#pragma omp section%> may only be used in " "%<#pragma omp sections%> construct"); c_parser_skip_until_found (parser, CPP_PRAGMA_EOL, NULL); return false; case PRAGMA_OMP_DECLARE: c_parser_omp_declare (parser, context); return false; case PRAGMA_OMP_ORDERED: return c_parser_omp_ordered (parser, context, if_p); case PRAGMA_IVDEP: { const bool ivdep = c_parse_pragma_ivdep (parser); unsigned short unroll; if (c_parser_peek_token (parser)->pragma_kind == PRAGMA_UNROLL) unroll = c_parser_pragma_unroll (parser); else unroll = 0; if (!c_parser_next_token_is_keyword (parser, RID_FOR) && !c_parser_next_token_is_keyword (parser, RID_WHILE) && !c_parser_next_token_is_keyword (parser, RID_DO)) { c_parser_error (parser, "for, while or do statement expected"); return false; } if (c_parser_next_token_is_keyword (parser, RID_FOR)) c_parser_for_statement (parser, ivdep, unroll, if_p); else if (c_parser_next_token_is_keyword (parser, RID_WHILE)) c_parser_while_statement (parser, ivdep, unroll, if_p); else c_parser_do_statement (parser, ivdep, unroll); } return false; case PRAGMA_UNROLL: { unsigned short unroll = c_parser_pragma_unroll (parser); bool ivdep; if (c_parser_peek_token (parser)->pragma_kind == PRAGMA_IVDEP) ivdep = c_parse_pragma_ivdep (parser); else ivdep = false; if (!c_parser_next_token_is_keyword (parser, RID_FOR) && !c_parser_next_token_is_keyword (parser, RID_WHILE) && !c_parser_next_token_is_keyword (parser, RID_DO)) { c_parser_error (parser, "for, while or do statement expected"); return false; } if (c_parser_next_token_is_keyword (parser, RID_FOR)) c_parser_for_statement (parser, ivdep, unroll, if_p); else if (c_parser_next_token_is_keyword (parser, RID_WHILE)) c_parser_while_statement (parser, ivdep, unroll, if_p); else c_parser_do_statement (parser, ivdep, unroll); } return false; case PRAGMA_GCC_PCH_PREPROCESS: c_parser_error (parser, "%<#pragma GCC pch_preprocess%> must be first"); c_parser_skip_until_found (parser, CPP_PRAGMA_EOL, NULL); return false; case PRAGMA_OACC_WAIT: if (context != pragma_compound) { construct = "acc wait"; goto in_compound; } /* FALL THROUGH. */ default: if (id < PRAGMA_FIRST_EXTERNAL) { if (context != pragma_stmt && context != pragma_compound) { bad_stmt: c_parser_error (parser, "expected declaration specifiers"); c_parser_skip_until_found (parser, CPP_PRAGMA_EOL, NULL); return false; } c_parser_omp_construct (parser, if_p); return true; } break; } c_parser_consume_pragma (parser); c_invoke_pragma_handler (id); /* Skip to EOL, but suppress any error message. Those will have been generated by the handler routine through calling error, as opposed to calling c_parser_error. */ parser->error = true; c_parser_skip_to_pragma_eol (parser); return false; } /* The interface the pragma parsers have to the lexer. */ enum cpp_ttype pragma_lex (tree *value, location_t *loc) { c_token *tok = c_parser_peek_token (the_parser); enum cpp_ttype ret = tok->type; *value = tok->value; if (loc) *loc = tok->location; if (ret == CPP_PRAGMA_EOL || ret == CPP_EOF) ret = CPP_EOF; else { if (ret == CPP_KEYWORD) ret = CPP_NAME; c_parser_consume_token (the_parser); } return ret; } static void c_parser_pragma_pch_preprocess (c_parser *parser) { tree name = NULL; c_parser_consume_pragma (parser); if (c_parser_next_token_is (parser, CPP_STRING)) { name = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); } else c_parser_error (parser, "expected string literal"); c_parser_skip_to_pragma_eol (parser); if (name) c_common_pch_pragma (parse_in, TREE_STRING_POINTER (name)); } /* OpenACC and OpenMP parsing routines. */ /* Returns name of the next clause. If the clause is not recognized PRAGMA_OMP_CLAUSE_NONE is returned and the token is not consumed. Otherwise appropriate pragma_omp_clause is returned and the token is consumed. */ static pragma_omp_clause c_parser_omp_clause_name (c_parser *parser) { pragma_omp_clause result = PRAGMA_OMP_CLAUSE_NONE; if (c_parser_next_token_is_keyword (parser, RID_AUTO)) result = PRAGMA_OACC_CLAUSE_AUTO; else if (c_parser_next_token_is_keyword (parser, RID_IF)) result = PRAGMA_OMP_CLAUSE_IF; else if (c_parser_next_token_is_keyword (parser, RID_DEFAULT)) result = PRAGMA_OMP_CLAUSE_DEFAULT; else if (c_parser_next_token_is_keyword (parser, RID_FOR)) result = PRAGMA_OMP_CLAUSE_FOR; else if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); switch (p[0]) { case 'a': if (!strcmp ("aligned", p)) result = PRAGMA_OMP_CLAUSE_ALIGNED; else if (!strcmp ("async", p)) result = PRAGMA_OACC_CLAUSE_ASYNC; break; case 'c': if (!strcmp ("collapse", p)) result = PRAGMA_OMP_CLAUSE_COLLAPSE; else if (!strcmp ("copy", p)) result = PRAGMA_OACC_CLAUSE_COPY; else if (!strcmp ("copyin", p)) result = PRAGMA_OMP_CLAUSE_COPYIN; else if (!strcmp ("copyout", p)) result = PRAGMA_OACC_CLAUSE_COPYOUT; else if (!strcmp ("copyprivate", p)) result = PRAGMA_OMP_CLAUSE_COPYPRIVATE; else if (!strcmp ("create", p)) result = PRAGMA_OACC_CLAUSE_CREATE; break; case 'd': if (!strcmp ("defaultmap", p)) result = PRAGMA_OMP_CLAUSE_DEFAULTMAP; else if (!strcmp ("delete", p)) result = PRAGMA_OACC_CLAUSE_DELETE; else if (!strcmp ("depend", p)) result = PRAGMA_OMP_CLAUSE_DEPEND; else if (!strcmp ("device", p)) result = PRAGMA_OMP_CLAUSE_DEVICE; else if (!strcmp ("deviceptr", p)) result = PRAGMA_OACC_CLAUSE_DEVICEPTR; else if (!strcmp ("device_resident", p)) result = PRAGMA_OACC_CLAUSE_DEVICE_RESIDENT; else if (!strcmp ("dist_schedule", p)) result = PRAGMA_OMP_CLAUSE_DIST_SCHEDULE; break; case 'f': if (!strcmp ("final", p)) result = PRAGMA_OMP_CLAUSE_FINAL; else if (!strcmp ("firstprivate", p)) result = PRAGMA_OMP_CLAUSE_FIRSTPRIVATE; else if (!strcmp ("from", p)) result = PRAGMA_OMP_CLAUSE_FROM; break; case 'g': if (!strcmp ("gang", p)) result = PRAGMA_OACC_CLAUSE_GANG; else if (!strcmp ("grainsize", p)) result = PRAGMA_OMP_CLAUSE_GRAINSIZE; break; case 'h': if (!strcmp ("hint", p)) result = PRAGMA_OMP_CLAUSE_HINT; else if (!strcmp ("host", p)) result = PRAGMA_OACC_CLAUSE_HOST; break; case 'i': if (!strcmp ("inbranch", p)) result = PRAGMA_OMP_CLAUSE_INBRANCH; else if (!strcmp ("independent", p)) result = PRAGMA_OACC_CLAUSE_INDEPENDENT; else if (!strcmp ("is_device_ptr", p)) result = PRAGMA_OMP_CLAUSE_IS_DEVICE_PTR; break; case 'l': if (!strcmp ("lastprivate", p)) result = PRAGMA_OMP_CLAUSE_LASTPRIVATE; else if (!strcmp ("linear", p)) result = PRAGMA_OMP_CLAUSE_LINEAR; else if (!strcmp ("link", p)) result = PRAGMA_OMP_CLAUSE_LINK; break; case 'm': if (!strcmp ("map", p)) result = PRAGMA_OMP_CLAUSE_MAP; else if (!strcmp ("mergeable", p)) result = PRAGMA_OMP_CLAUSE_MERGEABLE; break; case 'n': if (!strcmp ("nogroup", p)) result = PRAGMA_OMP_CLAUSE_NOGROUP; else if (!strcmp ("notinbranch", p)) result = PRAGMA_OMP_CLAUSE_NOTINBRANCH; else if (!strcmp ("nowait", p)) result = PRAGMA_OMP_CLAUSE_NOWAIT; else if (!strcmp ("num_gangs", p)) result = PRAGMA_OACC_CLAUSE_NUM_GANGS; else if (!strcmp ("num_tasks", p)) result = PRAGMA_OMP_CLAUSE_NUM_TASKS; else if (!strcmp ("num_teams", p)) result = PRAGMA_OMP_CLAUSE_NUM_TEAMS; else if (!strcmp ("num_threads", p)) result = PRAGMA_OMP_CLAUSE_NUM_THREADS; else if (!strcmp ("num_workers", p)) result = PRAGMA_OACC_CLAUSE_NUM_WORKERS; break; case 'o': if (!strcmp ("ordered", p)) result = PRAGMA_OMP_CLAUSE_ORDERED; break; case 'p': if (!strcmp ("parallel", p)) result = PRAGMA_OMP_CLAUSE_PARALLEL; else if (!strcmp ("present", p)) result = PRAGMA_OACC_CLAUSE_PRESENT; else if (!strcmp ("present_or_copy", p) || !strcmp ("pcopy", p)) result = PRAGMA_OACC_CLAUSE_PRESENT_OR_COPY; else if (!strcmp ("present_or_copyin", p) || !strcmp ("pcopyin", p)) result = PRAGMA_OACC_CLAUSE_PRESENT_OR_COPYIN; else if (!strcmp ("present_or_copyout", p) || !strcmp ("pcopyout", p)) result = PRAGMA_OACC_CLAUSE_PRESENT_OR_COPYOUT; else if (!strcmp ("present_or_create", p) || !strcmp ("pcreate", p)) result = PRAGMA_OACC_CLAUSE_PRESENT_OR_CREATE; else if (!strcmp ("priority", p)) result = PRAGMA_OMP_CLAUSE_PRIORITY; else if (!strcmp ("private", p)) result = PRAGMA_OMP_CLAUSE_PRIVATE; else if (!strcmp ("proc_bind", p)) result = PRAGMA_OMP_CLAUSE_PROC_BIND; break; case 'r': if (!strcmp ("reduction", p)) result = PRAGMA_OMP_CLAUSE_REDUCTION; break; case 's': if (!strcmp ("safelen", p)) result = PRAGMA_OMP_CLAUSE_SAFELEN; else if (!strcmp ("schedule", p)) result = PRAGMA_OMP_CLAUSE_SCHEDULE; else if (!strcmp ("sections", p)) result = PRAGMA_OMP_CLAUSE_SECTIONS; else if (!strcmp ("seq", p)) result = PRAGMA_OACC_CLAUSE_SEQ; else if (!strcmp ("shared", p)) result = PRAGMA_OMP_CLAUSE_SHARED; else if (!strcmp ("simd", p)) result = PRAGMA_OMP_CLAUSE_SIMD; else if (!strcmp ("simdlen", p)) result = PRAGMA_OMP_CLAUSE_SIMDLEN; else if (!strcmp ("self", p)) result = PRAGMA_OACC_CLAUSE_SELF; break; case 't': if (!strcmp ("taskgroup", p)) result = PRAGMA_OMP_CLAUSE_TASKGROUP; else if (!strcmp ("thread_limit", p)) result = PRAGMA_OMP_CLAUSE_THREAD_LIMIT; else if (!strcmp ("threads", p)) result = PRAGMA_OMP_CLAUSE_THREADS; else if (!strcmp ("tile", p)) result = PRAGMA_OACC_CLAUSE_TILE; else if (!strcmp ("to", p)) result = PRAGMA_OMP_CLAUSE_TO; break; case 'u': if (!strcmp ("uniform", p)) result = PRAGMA_OMP_CLAUSE_UNIFORM; else if (!strcmp ("untied", p)) result = PRAGMA_OMP_CLAUSE_UNTIED; else if (!strcmp ("use_device", p)) result = PRAGMA_OACC_CLAUSE_USE_DEVICE; else if (!strcmp ("use_device_ptr", p)) result = PRAGMA_OMP_CLAUSE_USE_DEVICE_PTR; break; case 'v': if (!strcmp ("vector", p)) result = PRAGMA_OACC_CLAUSE_VECTOR; else if (!strcmp ("vector_length", p)) result = PRAGMA_OACC_CLAUSE_VECTOR_LENGTH; break; case 'w': if (!strcmp ("wait", p)) result = PRAGMA_OACC_CLAUSE_WAIT; else if (!strcmp ("worker", p)) result = PRAGMA_OACC_CLAUSE_WORKER; break; } } if (result != PRAGMA_OMP_CLAUSE_NONE) c_parser_consume_token (parser); return result; } /* Validate that a clause of the given type does not already exist. */ static void check_no_duplicate_clause (tree clauses, enum omp_clause_code code, const char *name) { tree c; for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == code) { location_t loc = OMP_CLAUSE_LOCATION (c); error_at (loc, "too many %qs clauses", name); break; } } /* OpenACC 2.0 Parse wait clause or wait directive parameters. */ static tree c_parser_oacc_wait_list (c_parser *parser, location_t clause_loc, tree list) { vec<tree, va_gc> *args; tree t, args_tree; matching_parens parens; if (!parens.require_open (parser)) return list; args = c_parser_expr_list (parser, false, true, NULL, NULL, NULL, NULL); if (args->length () == 0) { c_parser_error (parser, "expected integer expression before ')'"); release_tree_vector (args); return list; } args_tree = build_tree_list_vec (args); for (t = args_tree; t; t = TREE_CHAIN (t)) { tree targ = TREE_VALUE (t); if (targ != error_mark_node) { if (!INTEGRAL_TYPE_P (TREE_TYPE (targ))) { c_parser_error (parser, "expression must be integral"); targ = error_mark_node; } else { tree c = build_omp_clause (clause_loc, OMP_CLAUSE_WAIT); OMP_CLAUSE_DECL (c) = targ; OMP_CLAUSE_CHAIN (c) = list; list = c; } } } release_tree_vector (args); parens.require_close (parser); return list; } /* OpenACC 2.0, OpenMP 2.5: variable-list: identifier variable-list , identifier If KIND is nonzero, create the appropriate node and install the decl in OMP_CLAUSE_DECL and add the node to the head of the list. If KIND is nonzero, CLAUSE_LOC is the location of the clause. If KIND is zero, create a TREE_LIST with the decl in TREE_PURPOSE; return the list created. */ static tree c_parser_omp_variable_list (c_parser *parser, location_t clause_loc, enum omp_clause_code kind, tree list) { if (c_parser_next_token_is_not (parser, CPP_NAME) || c_parser_peek_token (parser)->id_kind != C_ID_ID) c_parser_error (parser, "expected identifier"); while (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_token (parser)->id_kind == C_ID_ID) { tree t = lookup_name (c_parser_peek_token (parser)->value); if (t == NULL_TREE) { undeclared_variable (c_parser_peek_token (parser)->location, c_parser_peek_token (parser)->value); t = error_mark_node; } c_parser_consume_token (parser); if (t == error_mark_node) ; else if (kind != 0) { switch (kind) { case OMP_CLAUSE__CACHE_: /* The OpenACC cache directive explicitly only allows "array elements or subarrays". */ if (c_parser_peek_token (parser)->type != CPP_OPEN_SQUARE) { c_parser_error (parser, "expected %<[%>"); t = error_mark_node; break; } /* FALLTHROUGH */ case OMP_CLAUSE_MAP: case OMP_CLAUSE_FROM: case OMP_CLAUSE_TO: while (c_parser_next_token_is (parser, CPP_DOT)) { location_t op_loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); if (!c_parser_next_token_is (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); t = error_mark_node; break; } c_token *comp_tok = c_parser_peek_token (parser); tree ident = comp_tok->value; location_t comp_loc = comp_tok->location; c_parser_consume_token (parser); t = build_component_ref (op_loc, t, ident, comp_loc); } /* FALLTHROUGH */ case OMP_CLAUSE_DEPEND: case OMP_CLAUSE_REDUCTION: while (c_parser_next_token_is (parser, CPP_OPEN_SQUARE)) { tree low_bound = NULL_TREE, length = NULL_TREE; c_parser_consume_token (parser); if (!c_parser_next_token_is (parser, CPP_COLON)) { location_t expr_loc = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expression (parser); expr = convert_lvalue_to_rvalue (expr_loc, expr, false, true); low_bound = expr.value; } if (c_parser_next_token_is (parser, CPP_CLOSE_SQUARE)) length = integer_one_node; else { /* Look for `:'. */ if (!c_parser_require (parser, CPP_COLON, "expected %<:%>")) { t = error_mark_node; break; } if (!c_parser_next_token_is (parser, CPP_CLOSE_SQUARE)) { location_t expr_loc = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expression (parser); expr = convert_lvalue_to_rvalue (expr_loc, expr, false, true); length = expr.value; } } /* Look for the closing `]'. */ if (!c_parser_require (parser, CPP_CLOSE_SQUARE, "expected %<]%>")) { t = error_mark_node; break; } t = tree_cons (low_bound, length, t); } break; default: break; } if (t != error_mark_node) { tree u = build_omp_clause (clause_loc, kind); OMP_CLAUSE_DECL (u) = t; OMP_CLAUSE_CHAIN (u) = list; list = u; } } else list = tree_cons (t, NULL_TREE, list); if (c_parser_next_token_is_not (parser, CPP_COMMA)) break; c_parser_consume_token (parser); } return list; } /* Similarly, but expect leading and trailing parenthesis. This is a very common case for OpenACC and OpenMP clauses. */ static tree c_parser_omp_var_list_parens (c_parser *parser, enum omp_clause_code kind, tree list) { /* The clauses location. */ location_t loc = c_parser_peek_token (parser)->location; matching_parens parens; if (parens.require_open (parser)) { list = c_parser_omp_variable_list (parser, loc, kind, list); parens.skip_until_found_close (parser); } return list; } /* OpenACC 2.0: copy ( variable-list ) copyin ( variable-list ) copyout ( variable-list ) create ( variable-list ) delete ( variable-list ) present ( variable-list ) present_or_copy ( variable-list ) pcopy ( variable-list ) present_or_copyin ( variable-list ) pcopyin ( variable-list ) present_or_copyout ( variable-list ) pcopyout ( variable-list ) present_or_create ( variable-list ) pcreate ( variable-list ) */ static tree c_parser_oacc_data_clause (c_parser *parser, pragma_omp_clause c_kind, tree list) { enum gomp_map_kind kind; switch (c_kind) { case PRAGMA_OACC_CLAUSE_COPY: kind = GOMP_MAP_FORCE_TOFROM; break; case PRAGMA_OACC_CLAUSE_COPYIN: kind = GOMP_MAP_FORCE_TO; break; case PRAGMA_OACC_CLAUSE_COPYOUT: kind = GOMP_MAP_FORCE_FROM; break; case PRAGMA_OACC_CLAUSE_CREATE: kind = GOMP_MAP_FORCE_ALLOC; break; case PRAGMA_OACC_CLAUSE_DELETE: kind = GOMP_MAP_DELETE; break; case PRAGMA_OACC_CLAUSE_DEVICE: kind = GOMP_MAP_FORCE_TO; break; case PRAGMA_OACC_CLAUSE_DEVICE_RESIDENT: kind = GOMP_MAP_DEVICE_RESIDENT; break; case PRAGMA_OACC_CLAUSE_HOST: case PRAGMA_OACC_CLAUSE_SELF: kind = GOMP_MAP_FORCE_FROM; break; case PRAGMA_OACC_CLAUSE_LINK: kind = GOMP_MAP_LINK; break; case PRAGMA_OACC_CLAUSE_PRESENT: kind = GOMP_MAP_FORCE_PRESENT; break; case PRAGMA_OACC_CLAUSE_PRESENT_OR_COPY: kind = GOMP_MAP_TOFROM; break; case PRAGMA_OACC_CLAUSE_PRESENT_OR_COPYIN: kind = GOMP_MAP_TO; break; case PRAGMA_OACC_CLAUSE_PRESENT_OR_COPYOUT: kind = GOMP_MAP_FROM; break; case PRAGMA_OACC_CLAUSE_PRESENT_OR_CREATE: kind = GOMP_MAP_ALLOC; break; default: gcc_unreachable (); } tree nl, c; nl = c_parser_omp_var_list_parens (parser, OMP_CLAUSE_MAP, list); for (c = nl; c != list; c = OMP_CLAUSE_CHAIN (c)) OMP_CLAUSE_SET_MAP_KIND (c, kind); return nl; } /* OpenACC 2.0: deviceptr ( variable-list ) */ static tree c_parser_oacc_data_clause_deviceptr (c_parser *parser, tree list) { location_t loc = c_parser_peek_token (parser)->location; tree vars, t; /* Can't use OMP_CLAUSE_MAP here (that is, can't use the generic c_parser_oacc_data_clause), as for PRAGMA_OACC_CLAUSE_DEVICEPTR, variable-list must only allow for pointer variables. */ vars = c_parser_omp_var_list_parens (parser, OMP_CLAUSE_ERROR, NULL); for (t = vars; t && t; t = TREE_CHAIN (t)) { tree v = TREE_PURPOSE (t); /* FIXME diagnostics: Ideally we should keep individual locations for all the variables in the var list to make the following errors more precise. Perhaps c_parser_omp_var_list_parens() should construct a list of locations to go along with the var list. */ if (!VAR_P (v) && TREE_CODE (v) != PARM_DECL) error_at (loc, "%qD is not a variable", v); else if (TREE_TYPE (v) == error_mark_node) ; else if (!POINTER_TYPE_P (TREE_TYPE (v))) error_at (loc, "%qD is not a pointer variable", v); tree u = build_omp_clause (loc, OMP_CLAUSE_MAP); OMP_CLAUSE_SET_MAP_KIND (u, GOMP_MAP_FORCE_DEVICEPTR); OMP_CLAUSE_DECL (u) = v; OMP_CLAUSE_CHAIN (u) = list; list = u; } return list; } /* OpenACC 2.0, OpenMP 3.0: collapse ( constant-expression ) */ static tree c_parser_omp_clause_collapse (c_parser *parser, tree list) { tree c, num = error_mark_node; HOST_WIDE_INT n; location_t loc; check_no_duplicate_clause (list, OMP_CLAUSE_COLLAPSE, "collapse"); check_no_duplicate_clause (list, OMP_CLAUSE_TILE, "tile"); loc = c_parser_peek_token (parser)->location; matching_parens parens; if (parens.require_open (parser)) { num = c_parser_expr_no_commas (parser, NULL).value; parens.skip_until_found_close (parser); } if (num == error_mark_node) return list; mark_exp_read (num); num = c_fully_fold (num, false, NULL); if (!INTEGRAL_TYPE_P (TREE_TYPE (num)) || !tree_fits_shwi_p (num) || (n = tree_to_shwi (num)) <= 0 || (int) n != n) { error_at (loc, "collapse argument needs positive constant integer expression"); return list; } c = build_omp_clause (loc, OMP_CLAUSE_COLLAPSE); OMP_CLAUSE_COLLAPSE_EXPR (c) = num; OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenMP 2.5: copyin ( variable-list ) */ static tree c_parser_omp_clause_copyin (c_parser *parser, tree list) { return c_parser_omp_var_list_parens (parser, OMP_CLAUSE_COPYIN, list); } /* OpenMP 2.5: copyprivate ( variable-list ) */ static tree c_parser_omp_clause_copyprivate (c_parser *parser, tree list) { return c_parser_omp_var_list_parens (parser, OMP_CLAUSE_COPYPRIVATE, list); } /* OpenMP 2.5: default ( none | shared ) OpenACC: default ( none | present ) */ static tree c_parser_omp_clause_default (c_parser *parser, tree list, bool is_oacc) { enum omp_clause_default_kind kind = OMP_CLAUSE_DEFAULT_UNSPECIFIED; location_t loc = c_parser_peek_token (parser)->location; tree c; matching_parens parens; if (!parens.require_open (parser)) return list; if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); switch (p[0]) { case 'n': if (strcmp ("none", p) != 0) goto invalid_kind; kind = OMP_CLAUSE_DEFAULT_NONE; break; case 'p': if (strcmp ("present", p) != 0 || !is_oacc) goto invalid_kind; kind = OMP_CLAUSE_DEFAULT_PRESENT; break; case 's': if (strcmp ("shared", p) != 0 || is_oacc) goto invalid_kind; kind = OMP_CLAUSE_DEFAULT_SHARED; break; default: goto invalid_kind; } c_parser_consume_token (parser); } else { invalid_kind: if (is_oacc) c_parser_error (parser, "expected %<none%> or %<present%>"); else c_parser_error (parser, "expected %<none%> or %<shared%>"); } parens.skip_until_found_close (parser); if (kind == OMP_CLAUSE_DEFAULT_UNSPECIFIED) return list; check_no_duplicate_clause (list, OMP_CLAUSE_DEFAULT, "default"); c = build_omp_clause (loc, OMP_CLAUSE_DEFAULT); OMP_CLAUSE_CHAIN (c) = list; OMP_CLAUSE_DEFAULT_KIND (c) = kind; return c; } /* OpenMP 2.5: firstprivate ( variable-list ) */ static tree c_parser_omp_clause_firstprivate (c_parser *parser, tree list) { return c_parser_omp_var_list_parens (parser, OMP_CLAUSE_FIRSTPRIVATE, list); } /* OpenMP 3.1: final ( expression ) */ static tree c_parser_omp_clause_final (c_parser *parser, tree list) { location_t loc = c_parser_peek_token (parser)->location; if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { tree t = c_parser_paren_condition (parser); tree c; check_no_duplicate_clause (list, OMP_CLAUSE_FINAL, "final"); c = build_omp_clause (loc, OMP_CLAUSE_FINAL); OMP_CLAUSE_FINAL_EXPR (c) = t; OMP_CLAUSE_CHAIN (c) = list; list = c; } else c_parser_error (parser, "expected %<(%>"); return list; } /* OpenACC, OpenMP 2.5: if ( expression ) OpenMP 4.5: if ( directive-name-modifier : expression ) directive-name-modifier: parallel | task | taskloop | target data | target | target update | target enter data | target exit data */ static tree c_parser_omp_clause_if (c_parser *parser, tree list, bool is_omp) { location_t location = c_parser_peek_token (parser)->location; enum tree_code if_modifier = ERROR_MARK; matching_parens parens; if (!parens.require_open (parser)) return list; if (is_omp && c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); int n = 2; if (strcmp (p, "parallel") == 0) if_modifier = OMP_PARALLEL; else if (strcmp (p, "task") == 0) if_modifier = OMP_TASK; else if (strcmp (p, "taskloop") == 0) if_modifier = OMP_TASKLOOP; else if (strcmp (p, "target") == 0) { if_modifier = OMP_TARGET; if (c_parser_peek_2nd_token (parser)->type == CPP_NAME) { p = IDENTIFIER_POINTER (c_parser_peek_2nd_token (parser)->value); if (strcmp ("data", p) == 0) if_modifier = OMP_TARGET_DATA; else if (strcmp ("update", p) == 0) if_modifier = OMP_TARGET_UPDATE; else if (strcmp ("enter", p) == 0) if_modifier = OMP_TARGET_ENTER_DATA; else if (strcmp ("exit", p) == 0) if_modifier = OMP_TARGET_EXIT_DATA; if (if_modifier != OMP_TARGET) { n = 3; c_parser_consume_token (parser); } else { location_t loc = c_parser_peek_2nd_token (parser)->location; error_at (loc, "expected %<data%>, %<update%>, %<enter%> " "or %<exit%>"); if_modifier = ERROR_MARK; } if (if_modifier == OMP_TARGET_ENTER_DATA || if_modifier == OMP_TARGET_EXIT_DATA) { if (c_parser_peek_2nd_token (parser)->type == CPP_NAME) { p = IDENTIFIER_POINTER (c_parser_peek_2nd_token (parser)->value); if (strcmp ("data", p) == 0) n = 4; } if (n == 4) c_parser_consume_token (parser); else { location_t loc = c_parser_peek_2nd_token (parser)->location; error_at (loc, "expected %<data%>"); if_modifier = ERROR_MARK; } } } } if (if_modifier != ERROR_MARK) { if (c_parser_peek_2nd_token (parser)->type == CPP_COLON) { c_parser_consume_token (parser); c_parser_consume_token (parser); } else { if (n > 2) { location_t loc = c_parser_peek_2nd_token (parser)->location; error_at (loc, "expected %<:%>"); } if_modifier = ERROR_MARK; } } } tree t = c_parser_condition (parser), c; parens.skip_until_found_close (parser); for (c = list; c ; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_IF) { if (if_modifier != ERROR_MARK && OMP_CLAUSE_IF_MODIFIER (c) == if_modifier) { const char *p = NULL; switch (if_modifier) { case OMP_PARALLEL: p = "parallel"; break; case OMP_TASK: p = "task"; break; case OMP_TASKLOOP: p = "taskloop"; break; case OMP_TARGET_DATA: p = "target data"; break; case OMP_TARGET: p = "target"; break; case OMP_TARGET_UPDATE: p = "target update"; break; case OMP_TARGET_ENTER_DATA: p = "enter data"; break; case OMP_TARGET_EXIT_DATA: p = "exit data"; break; default: gcc_unreachable (); } error_at (location, "too many %<if%> clauses with %qs modifier", p); return list; } else if (OMP_CLAUSE_IF_MODIFIER (c) == if_modifier) { if (!is_omp) error_at (location, "too many %<if%> clauses"); else error_at (location, "too many %<if%> clauses without modifier"); return list; } else if (if_modifier == ERROR_MARK || OMP_CLAUSE_IF_MODIFIER (c) == ERROR_MARK) { error_at (location, "if any %<if%> clause has modifier, then all " "%<if%> clauses have to use modifier"); return list; } } c = build_omp_clause (location, OMP_CLAUSE_IF); OMP_CLAUSE_IF_MODIFIER (c) = if_modifier; OMP_CLAUSE_IF_EXPR (c) = t; OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenMP 2.5: lastprivate ( variable-list ) */ static tree c_parser_omp_clause_lastprivate (c_parser *parser, tree list) { return c_parser_omp_var_list_parens (parser, OMP_CLAUSE_LASTPRIVATE, list); } /* OpenMP 3.1: mergeable */ static tree c_parser_omp_clause_mergeable (c_parser *parser ATTRIBUTE_UNUSED, tree list) { tree c; /* FIXME: Should we allow duplicates? */ check_no_duplicate_clause (list, OMP_CLAUSE_MERGEABLE, "mergeable"); c = build_omp_clause (c_parser_peek_token (parser)->location, OMP_CLAUSE_MERGEABLE); OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenMP 2.5: nowait */ static tree c_parser_omp_clause_nowait (c_parser *parser ATTRIBUTE_UNUSED, tree list) { tree c; location_t loc = c_parser_peek_token (parser)->location; check_no_duplicate_clause (list, OMP_CLAUSE_NOWAIT, "nowait"); c = build_omp_clause (loc, OMP_CLAUSE_NOWAIT); OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenMP 2.5: num_threads ( expression ) */ static tree c_parser_omp_clause_num_threads (c_parser *parser, tree list) { location_t num_threads_loc = c_parser_peek_token (parser)->location; matching_parens parens; if (parens.require_open (parser)) { location_t expr_loc = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expression (parser); expr = convert_lvalue_to_rvalue (expr_loc, expr, false, true); tree c, t = expr.value; t = c_fully_fold (t, false, NULL); parens.skip_until_found_close (parser); if (!INTEGRAL_TYPE_P (TREE_TYPE (t))) { c_parser_error (parser, "expected integer expression"); return list; } /* Attempt to statically determine when the number isn't positive. */ c = fold_build2_loc (expr_loc, LE_EXPR, boolean_type_node, t, build_int_cst (TREE_TYPE (t), 0)); protected_set_expr_location (c, expr_loc); if (c == boolean_true_node) { warning_at (expr_loc, 0, "%<num_threads%> value must be positive"); t = integer_one_node; } check_no_duplicate_clause (list, OMP_CLAUSE_NUM_THREADS, "num_threads"); c = build_omp_clause (num_threads_loc, OMP_CLAUSE_NUM_THREADS); OMP_CLAUSE_NUM_THREADS_EXPR (c) = t; OMP_CLAUSE_CHAIN (c) = list; list = c; } return list; } /* OpenMP 4.5: num_tasks ( expression ) */ static tree c_parser_omp_clause_num_tasks (c_parser *parser, tree list) { location_t num_tasks_loc = c_parser_peek_token (parser)->location; matching_parens parens; if (parens.require_open (parser)) { location_t expr_loc = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expression (parser); expr = convert_lvalue_to_rvalue (expr_loc, expr, false, true); tree c, t = expr.value; t = c_fully_fold (t, false, NULL); parens.skip_until_found_close (parser); if (!INTEGRAL_TYPE_P (TREE_TYPE (t))) { c_parser_error (parser, "expected integer expression"); return list; } /* Attempt to statically determine when the number isn't positive. */ c = fold_build2_loc (expr_loc, LE_EXPR, boolean_type_node, t, build_int_cst (TREE_TYPE (t), 0)); if (CAN_HAVE_LOCATION_P (c)) SET_EXPR_LOCATION (c, expr_loc); if (c == boolean_true_node) { warning_at (expr_loc, 0, "%<num_tasks%> value must be positive"); t = integer_one_node; } check_no_duplicate_clause (list, OMP_CLAUSE_NUM_TASKS, "num_tasks"); c = build_omp_clause (num_tasks_loc, OMP_CLAUSE_NUM_TASKS); OMP_CLAUSE_NUM_TASKS_EXPR (c) = t; OMP_CLAUSE_CHAIN (c) = list; list = c; } return list; } /* OpenMP 4.5: grainsize ( expression ) */ static tree c_parser_omp_clause_grainsize (c_parser *parser, tree list) { location_t grainsize_loc = c_parser_peek_token (parser)->location; matching_parens parens; if (parens.require_open (parser)) { location_t expr_loc = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expression (parser); expr = convert_lvalue_to_rvalue (expr_loc, expr, false, true); tree c, t = expr.value; t = c_fully_fold (t, false, NULL); parens.skip_until_found_close (parser); if (!INTEGRAL_TYPE_P (TREE_TYPE (t))) { c_parser_error (parser, "expected integer expression"); return list; } /* Attempt to statically determine when the number isn't positive. */ c = fold_build2_loc (expr_loc, LE_EXPR, boolean_type_node, t, build_int_cst (TREE_TYPE (t), 0)); if (CAN_HAVE_LOCATION_P (c)) SET_EXPR_LOCATION (c, expr_loc); if (c == boolean_true_node) { warning_at (expr_loc, 0, "%<grainsize%> value must be positive"); t = integer_one_node; } check_no_duplicate_clause (list, OMP_CLAUSE_GRAINSIZE, "grainsize"); c = build_omp_clause (grainsize_loc, OMP_CLAUSE_GRAINSIZE); OMP_CLAUSE_GRAINSIZE_EXPR (c) = t; OMP_CLAUSE_CHAIN (c) = list; list = c; } return list; } /* OpenMP 4.5: priority ( expression ) */ static tree c_parser_omp_clause_priority (c_parser *parser, tree list) { location_t priority_loc = c_parser_peek_token (parser)->location; matching_parens parens; if (parens.require_open (parser)) { location_t expr_loc = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expression (parser); expr = convert_lvalue_to_rvalue (expr_loc, expr, false, true); tree c, t = expr.value; t = c_fully_fold (t, false, NULL); parens.skip_until_found_close (parser); if (!INTEGRAL_TYPE_P (TREE_TYPE (t))) { c_parser_error (parser, "expected integer expression"); return list; } /* Attempt to statically determine when the number isn't non-negative. */ c = fold_build2_loc (expr_loc, LT_EXPR, boolean_type_node, t, build_int_cst (TREE_TYPE (t), 0)); if (CAN_HAVE_LOCATION_P (c)) SET_EXPR_LOCATION (c, expr_loc); if (c == boolean_true_node) { warning_at (expr_loc, 0, "%<priority%> value must be non-negative"); t = integer_one_node; } check_no_duplicate_clause (list, OMP_CLAUSE_PRIORITY, "priority"); c = build_omp_clause (priority_loc, OMP_CLAUSE_PRIORITY); OMP_CLAUSE_PRIORITY_EXPR (c) = t; OMP_CLAUSE_CHAIN (c) = list; list = c; } return list; } /* OpenMP 4.5: hint ( expression ) */ static tree c_parser_omp_clause_hint (c_parser *parser, tree list) { location_t hint_loc = c_parser_peek_token (parser)->location; matching_parens parens; if (parens.require_open (parser)) { location_t expr_loc = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expression (parser); expr = convert_lvalue_to_rvalue (expr_loc, expr, false, true); tree c, t = expr.value; t = c_fully_fold (t, false, NULL); parens.skip_until_found_close (parser); if (!INTEGRAL_TYPE_P (TREE_TYPE (t))) { c_parser_error (parser, "expected integer expression"); return list; } check_no_duplicate_clause (list, OMP_CLAUSE_HINT, "hint"); c = build_omp_clause (hint_loc, OMP_CLAUSE_HINT); OMP_CLAUSE_HINT_EXPR (c) = t; OMP_CLAUSE_CHAIN (c) = list; list = c; } return list; } /* OpenMP 4.5: defaultmap ( tofrom : scalar ) */ static tree c_parser_omp_clause_defaultmap (c_parser *parser, tree list) { location_t loc = c_parser_peek_token (parser)->location; tree c; const char *p; matching_parens parens; if (!parens.require_open (parser)) return list; if (!c_parser_next_token_is (parser, CPP_NAME)) { c_parser_error (parser, "expected %<tofrom%>"); goto out_err; } p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp (p, "tofrom") != 0) { c_parser_error (parser, "expected %<tofrom%>"); goto out_err; } c_parser_consume_token (parser); if (!c_parser_require (parser, CPP_COLON, "expected %<:%>")) goto out_err; if (!c_parser_next_token_is (parser, CPP_NAME)) { c_parser_error (parser, "expected %<scalar%>"); goto out_err; } p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp (p, "scalar") != 0) { c_parser_error (parser, "expected %<scalar%>"); goto out_err; } c_parser_consume_token (parser); parens.skip_until_found_close (parser); check_no_duplicate_clause (list, OMP_CLAUSE_DEFAULTMAP, "defaultmap"); c = build_omp_clause (loc, OMP_CLAUSE_DEFAULTMAP); OMP_CLAUSE_CHAIN (c) = list; return c; out_err: parens.skip_until_found_close (parser); return list; } /* OpenACC 2.0: use_device ( variable-list ) OpenMP 4.5: use_device_ptr ( variable-list ) */ static tree c_parser_omp_clause_use_device_ptr (c_parser *parser, tree list) { return c_parser_omp_var_list_parens (parser, OMP_CLAUSE_USE_DEVICE_PTR, list); } /* OpenMP 4.5: is_device_ptr ( variable-list ) */ static tree c_parser_omp_clause_is_device_ptr (c_parser *parser, tree list) { return c_parser_omp_var_list_parens (parser, OMP_CLAUSE_IS_DEVICE_PTR, list); } /* OpenACC: num_gangs ( expression ) num_workers ( expression ) vector_length ( expression ) */ static tree c_parser_oacc_single_int_clause (c_parser *parser, omp_clause_code code, tree list) { location_t loc = c_parser_peek_token (parser)->location; matching_parens parens; if (!parens.require_open (parser)) return list; location_t expr_loc = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expression (parser); expr = convert_lvalue_to_rvalue (expr_loc, expr, false, true); tree c, t = expr.value; t = c_fully_fold (t, false, NULL); parens.skip_until_found_close (parser); if (t == error_mark_node) return list; else if (!INTEGRAL_TYPE_P (TREE_TYPE (t))) { error_at (expr_loc, "%qs expression must be integral", omp_clause_code_name[code]); return list; } /* Attempt to statically determine when the number isn't positive. */ c = fold_build2_loc (expr_loc, LE_EXPR, boolean_type_node, t, build_int_cst (TREE_TYPE (t), 0)); protected_set_expr_location (c, expr_loc); if (c == boolean_true_node) { warning_at (expr_loc, 0, "%qs value must be positive", omp_clause_code_name[code]); t = integer_one_node; } check_no_duplicate_clause (list, code, omp_clause_code_name[code]); c = build_omp_clause (loc, code); OMP_CLAUSE_OPERAND (c, 0) = t; OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenACC: gang [( gang-arg-list )] worker [( [num:] int-expr )] vector [( [length:] int-expr )] where gang-arg is one of: [num:] int-expr static: size-expr and size-expr may be: * int-expr */ static tree c_parser_oacc_shape_clause (c_parser *parser, omp_clause_code kind, const char *str, tree list) { const char *id = "num"; tree ops[2] = { NULL_TREE, NULL_TREE }, c; location_t loc = c_parser_peek_token (parser)->location; if (kind == OMP_CLAUSE_VECTOR) id = "length"; if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { c_parser_consume_token (parser); do { c_token *next = c_parser_peek_token (parser); int idx = 0; /* Gang static argument. */ if (kind == OMP_CLAUSE_GANG && c_parser_next_token_is_keyword (parser, RID_STATIC)) { c_parser_consume_token (parser); if (!c_parser_require (parser, CPP_COLON, "expected %<:%>")) goto cleanup_error; idx = 1; if (ops[idx] != NULL_TREE) { c_parser_error (parser, "too many %<static%> arguments"); goto cleanup_error; } /* Check for the '*' argument. */ if (c_parser_next_token_is (parser, CPP_MULT) && (c_parser_peek_2nd_token (parser)->type == CPP_COMMA || c_parser_peek_2nd_token (parser)->type == CPP_CLOSE_PAREN)) { c_parser_consume_token (parser); ops[idx] = integer_minus_one_node; if (c_parser_next_token_is (parser, CPP_COMMA)) { c_parser_consume_token (parser); continue; } else break; } } /* Worker num: argument and vector length: arguments. */ else if (c_parser_next_token_is (parser, CPP_NAME) && strcmp (id, IDENTIFIER_POINTER (next->value)) == 0 && c_parser_peek_2nd_token (parser)->type == CPP_COLON) { c_parser_consume_token (parser); /* id */ c_parser_consume_token (parser); /* ':' */ } /* Now collect the actual argument. */ if (ops[idx] != NULL_TREE) { c_parser_error (parser, "unexpected argument"); goto cleanup_error; } location_t expr_loc = c_parser_peek_token (parser)->location; c_expr cexpr = c_parser_expr_no_commas (parser, NULL); cexpr = convert_lvalue_to_rvalue (expr_loc, cexpr, false, true); tree expr = cexpr.value; if (expr == error_mark_node) goto cleanup_error; expr = c_fully_fold (expr, false, NULL); /* Attempt to statically determine when the number isn't a positive integer. */ if (!INTEGRAL_TYPE_P (TREE_TYPE (expr))) { c_parser_error (parser, "expected integer expression"); return list; } tree c = fold_build2_loc (expr_loc, LE_EXPR, boolean_type_node, expr, build_int_cst (TREE_TYPE (expr), 0)); if (c == boolean_true_node) { warning_at (loc, 0, "%qs value must be positive", str); expr = integer_one_node; } ops[idx] = expr; if (kind == OMP_CLAUSE_GANG && c_parser_next_token_is (parser, CPP_COMMA)) { c_parser_consume_token (parser); continue; } break; } while (1); if (!c_parser_require (parser, CPP_CLOSE_PAREN, "expected %<)%>")) goto cleanup_error; } check_no_duplicate_clause (list, kind, str); c = build_omp_clause (loc, kind); if (ops[1]) OMP_CLAUSE_OPERAND (c, 1) = ops[1]; OMP_CLAUSE_OPERAND (c, 0) = ops[0]; OMP_CLAUSE_CHAIN (c) = list; return c; cleanup_error: c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, 0); return list; } /* OpenACC: auto independent nohost seq */ static tree c_parser_oacc_simple_clause (c_parser *parser, enum omp_clause_code code, tree list) { check_no_duplicate_clause (list, code, omp_clause_code_name[code]); tree c = build_omp_clause (c_parser_peek_token (parser)->location, code); OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenACC: async [( int-expr )] */ static tree c_parser_oacc_clause_async (c_parser *parser, tree list) { tree c, t; location_t loc = c_parser_peek_token (parser)->location; t = build_int_cst (integer_type_node, GOMP_ASYNC_NOVAL); if (c_parser_peek_token (parser)->type == CPP_OPEN_PAREN) { c_parser_consume_token (parser); t = c_parser_expression (parser).value; if (!INTEGRAL_TYPE_P (TREE_TYPE (t))) c_parser_error (parser, "expected integer expression"); else if (t == error_mark_node || !c_parser_require (parser, CPP_CLOSE_PAREN, "expected %<)%>")) return list; } else t = c_fully_fold (t, false, NULL); check_no_duplicate_clause (list, OMP_CLAUSE_ASYNC, "async"); c = build_omp_clause (loc, OMP_CLAUSE_ASYNC); OMP_CLAUSE_ASYNC_EXPR (c) = t; OMP_CLAUSE_CHAIN (c) = list; list = c; return list; } /* OpenACC 2.0: tile ( size-expr-list ) */ static tree c_parser_oacc_clause_tile (c_parser *parser, tree list) { tree c, expr = error_mark_node; location_t loc; tree tile = NULL_TREE; check_no_duplicate_clause (list, OMP_CLAUSE_TILE, "tile"); check_no_duplicate_clause (list, OMP_CLAUSE_COLLAPSE, "collapse"); loc = c_parser_peek_token (parser)->location; if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) return list; do { if (tile && !c_parser_require (parser, CPP_COMMA, "expected %<,%>")) return list; if (c_parser_next_token_is (parser, CPP_MULT) && (c_parser_peek_2nd_token (parser)->type == CPP_COMMA || c_parser_peek_2nd_token (parser)->type == CPP_CLOSE_PAREN)) { c_parser_consume_token (parser); expr = integer_zero_node; } else { location_t expr_loc = c_parser_peek_token (parser)->location; c_expr cexpr = c_parser_expr_no_commas (parser, NULL); cexpr = convert_lvalue_to_rvalue (expr_loc, cexpr, false, true); expr = cexpr.value; if (expr == error_mark_node) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return list; } expr = c_fully_fold (expr, false, NULL); if (!INTEGRAL_TYPE_P (TREE_TYPE (expr)) || !tree_fits_shwi_p (expr) || tree_to_shwi (expr) <= 0) { error_at (expr_loc, "%<tile%> argument needs positive" " integral constant"); expr = integer_zero_node; } } tile = tree_cons (NULL_TREE, expr, tile); } while (c_parser_next_token_is_not (parser, CPP_CLOSE_PAREN)); /* Consume the trailing ')'. */ c_parser_consume_token (parser); c = build_omp_clause (loc, OMP_CLAUSE_TILE); tile = nreverse (tile); OMP_CLAUSE_TILE_LIST (c) = tile; OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenACC: wait ( int-expr-list ) */ static tree c_parser_oacc_clause_wait (c_parser *parser, tree list) { location_t clause_loc = c_parser_peek_token (parser)->location; if (c_parser_peek_token (parser)->type == CPP_OPEN_PAREN) list = c_parser_oacc_wait_list (parser, clause_loc, list); return list; } /* OpenMP 2.5: ordered OpenMP 4.5: ordered ( constant-expression ) */ static tree c_parser_omp_clause_ordered (c_parser *parser, tree list) { check_no_duplicate_clause (list, OMP_CLAUSE_ORDERED, "ordered"); tree c, num = NULL_TREE; HOST_WIDE_INT n; location_t loc = c_parser_peek_token (parser)->location; if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { matching_parens parens; parens.consume_open (parser); num = c_parser_expr_no_commas (parser, NULL).value; parens.skip_until_found_close (parser); } if (num == error_mark_node) return list; if (num) { mark_exp_read (num); num = c_fully_fold (num, false, NULL); if (!INTEGRAL_TYPE_P (TREE_TYPE (num)) || !tree_fits_shwi_p (num) || (n = tree_to_shwi (num)) <= 0 || (int) n != n) { error_at (loc, "ordered argument needs positive " "constant integer expression"); return list; } } c = build_omp_clause (loc, OMP_CLAUSE_ORDERED); OMP_CLAUSE_ORDERED_EXPR (c) = num; OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenMP 2.5: private ( variable-list ) */ static tree c_parser_omp_clause_private (c_parser *parser, tree list) { return c_parser_omp_var_list_parens (parser, OMP_CLAUSE_PRIVATE, list); } /* OpenMP 2.5: reduction ( reduction-operator : variable-list ) reduction-operator: One of: + * - & ^ | && || OpenMP 3.1: reduction-operator: One of: + * - & ^ | && || max min OpenMP 4.0: reduction-operator: One of: + * - & ^ | && || identifier */ static tree c_parser_omp_clause_reduction (c_parser *parser, tree list) { location_t clause_loc = c_parser_peek_token (parser)->location; matching_parens parens; if (parens.require_open (parser)) { enum tree_code code = ERROR_MARK; tree reduc_id = NULL_TREE; switch (c_parser_peek_token (parser)->type) { case CPP_PLUS: code = PLUS_EXPR; break; case CPP_MULT: code = MULT_EXPR; break; case CPP_MINUS: code = MINUS_EXPR; break; case CPP_AND: code = BIT_AND_EXPR; break; case CPP_XOR: code = BIT_XOR_EXPR; break; case CPP_OR: code = BIT_IOR_EXPR; break; case CPP_AND_AND: code = TRUTH_ANDIF_EXPR; break; case CPP_OR_OR: code = TRUTH_ORIF_EXPR; break; case CPP_NAME: { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp (p, "min") == 0) { code = MIN_EXPR; break; } if (strcmp (p, "max") == 0) { code = MAX_EXPR; break; } reduc_id = c_parser_peek_token (parser)->value; break; } default: c_parser_error (parser, "expected %<+%>, %<*%>, %<-%>, %<&%>, " "%<^%>, %<|%>, %<&&%>, %<||%> or identifier"); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, 0); return list; } c_parser_consume_token (parser); reduc_id = c_omp_reduction_id (code, reduc_id); if (c_parser_require (parser, CPP_COLON, "expected %<:%>")) { tree nl, c; nl = c_parser_omp_variable_list (parser, clause_loc, OMP_CLAUSE_REDUCTION, list); for (c = nl; c != list; c = OMP_CLAUSE_CHAIN (c)) { tree d = OMP_CLAUSE_DECL (c), type; if (TREE_CODE (d) != TREE_LIST) type = TREE_TYPE (d); else { int cnt = 0; tree t; for (t = d; TREE_CODE (t) == TREE_LIST; t = TREE_CHAIN (t)) cnt++; type = TREE_TYPE (t); while (cnt > 0) { if (TREE_CODE (type) != POINTER_TYPE && TREE_CODE (type) != ARRAY_TYPE) break; type = TREE_TYPE (type); cnt--; } } while (TREE_CODE (type) == ARRAY_TYPE) type = TREE_TYPE (type); OMP_CLAUSE_REDUCTION_CODE (c) = code; if (code == ERROR_MARK || !(INTEGRAL_TYPE_P (type) || TREE_CODE (type) == REAL_TYPE || TREE_CODE (type) == COMPLEX_TYPE)) OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) = c_omp_reduction_lookup (reduc_id, TYPE_MAIN_VARIANT (type)); } list = nl; } parens.skip_until_found_close (parser); } return list; } /* OpenMP 2.5: schedule ( schedule-kind ) schedule ( schedule-kind , expression ) schedule-kind: static | dynamic | guided | runtime | auto OpenMP 4.5: schedule ( schedule-modifier : schedule-kind ) schedule ( schedule-modifier [ , schedule-modifier ] : schedule-kind , expression ) schedule-modifier: simd monotonic nonmonotonic */ static tree c_parser_omp_clause_schedule (c_parser *parser, tree list) { tree c, t; location_t loc = c_parser_peek_token (parser)->location; int modifiers = 0, nmodifiers = 0; matching_parens parens; if (!parens.require_open (parser)) return list; c = build_omp_clause (loc, OMP_CLAUSE_SCHEDULE); while (c_parser_next_token_is (parser, CPP_NAME)) { tree kind = c_parser_peek_token (parser)->value; const char *p = IDENTIFIER_POINTER (kind); if (strcmp ("simd", p) == 0) OMP_CLAUSE_SCHEDULE_SIMD (c) = 1; else if (strcmp ("monotonic", p) == 0) modifiers |= OMP_CLAUSE_SCHEDULE_MONOTONIC; else if (strcmp ("nonmonotonic", p) == 0) modifiers |= OMP_CLAUSE_SCHEDULE_NONMONOTONIC; else break; c_parser_consume_token (parser); if (nmodifiers++ == 0 && c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else { c_parser_require (parser, CPP_COLON, "expected %<:%>"); break; } } if ((modifiers & (OMP_CLAUSE_SCHEDULE_MONOTONIC | OMP_CLAUSE_SCHEDULE_NONMONOTONIC)) == (OMP_CLAUSE_SCHEDULE_MONOTONIC | OMP_CLAUSE_SCHEDULE_NONMONOTONIC)) { error_at (loc, "both %<monotonic%> and %<nonmonotonic%> modifiers " "specified"); modifiers = 0; } if (c_parser_next_token_is (parser, CPP_NAME)) { tree kind = c_parser_peek_token (parser)->value; const char *p = IDENTIFIER_POINTER (kind); switch (p[0]) { case 'd': if (strcmp ("dynamic", p) != 0) goto invalid_kind; OMP_CLAUSE_SCHEDULE_KIND (c) = OMP_CLAUSE_SCHEDULE_DYNAMIC; break; case 'g': if (strcmp ("guided", p) != 0) goto invalid_kind; OMP_CLAUSE_SCHEDULE_KIND (c) = OMP_CLAUSE_SCHEDULE_GUIDED; break; case 'r': if (strcmp ("runtime", p) != 0) goto invalid_kind; OMP_CLAUSE_SCHEDULE_KIND (c) = OMP_CLAUSE_SCHEDULE_RUNTIME; break; default: goto invalid_kind; } } else if (c_parser_next_token_is_keyword (parser, RID_STATIC)) OMP_CLAUSE_SCHEDULE_KIND (c) = OMP_CLAUSE_SCHEDULE_STATIC; else if (c_parser_next_token_is_keyword (parser, RID_AUTO)) OMP_CLAUSE_SCHEDULE_KIND (c) = OMP_CLAUSE_SCHEDULE_AUTO; else goto invalid_kind; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_COMMA)) { location_t here; c_parser_consume_token (parser); here = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expr_no_commas (parser, NULL); expr = convert_lvalue_to_rvalue (here, expr, false, true); t = expr.value; t = c_fully_fold (t, false, NULL); if (OMP_CLAUSE_SCHEDULE_KIND (c) == OMP_CLAUSE_SCHEDULE_RUNTIME) error_at (here, "schedule %<runtime%> does not take " "a %<chunk_size%> parameter"); else if (OMP_CLAUSE_SCHEDULE_KIND (c) == OMP_CLAUSE_SCHEDULE_AUTO) error_at (here, "schedule %<auto%> does not take " "a %<chunk_size%> parameter"); else if (TREE_CODE (TREE_TYPE (t)) == INTEGER_TYPE) { /* Attempt to statically determine when the number isn't positive. */ tree s = fold_build2_loc (loc, LE_EXPR, boolean_type_node, t, build_int_cst (TREE_TYPE (t), 0)); protected_set_expr_location (s, loc); if (s == boolean_true_node) { warning_at (loc, 0, "chunk size value must be positive"); t = integer_one_node; } OMP_CLAUSE_SCHEDULE_CHUNK_EXPR (c) = t; } else c_parser_error (parser, "expected integer expression"); parens.skip_until_found_close (parser); } else c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<,%> or %<)%>"); OMP_CLAUSE_SCHEDULE_KIND (c) = (enum omp_clause_schedule_kind) (OMP_CLAUSE_SCHEDULE_KIND (c) | modifiers); check_no_duplicate_clause (list, OMP_CLAUSE_SCHEDULE, "schedule"); OMP_CLAUSE_CHAIN (c) = list; return c; invalid_kind: c_parser_error (parser, "invalid schedule kind"); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, 0); return list; } /* OpenMP 2.5: shared ( variable-list ) */ static tree c_parser_omp_clause_shared (c_parser *parser, tree list) { return c_parser_omp_var_list_parens (parser, OMP_CLAUSE_SHARED, list); } /* OpenMP 3.0: untied */ static tree c_parser_omp_clause_untied (c_parser *parser ATTRIBUTE_UNUSED, tree list) { tree c; /* FIXME: Should we allow duplicates? */ check_no_duplicate_clause (list, OMP_CLAUSE_UNTIED, "untied"); c = build_omp_clause (c_parser_peek_token (parser)->location, OMP_CLAUSE_UNTIED); OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenMP 4.0: inbranch notinbranch */ static tree c_parser_omp_clause_branch (c_parser *parser ATTRIBUTE_UNUSED, enum omp_clause_code code, tree list) { check_no_duplicate_clause (list, code, omp_clause_code_name[code]); tree c = build_omp_clause (c_parser_peek_token (parser)->location, code); OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenMP 4.0: parallel for sections taskgroup */ static tree c_parser_omp_clause_cancelkind (c_parser *parser ATTRIBUTE_UNUSED, enum omp_clause_code code, tree list) { tree c = build_omp_clause (c_parser_peek_token (parser)->location, code); OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenMP 4.5: nogroup */ static tree c_parser_omp_clause_nogroup (c_parser *parser ATTRIBUTE_UNUSED, tree list) { check_no_duplicate_clause (list, OMP_CLAUSE_NOGROUP, "nogroup"); tree c = build_omp_clause (c_parser_peek_token (parser)->location, OMP_CLAUSE_NOGROUP); OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenMP 4.5: simd threads */ static tree c_parser_omp_clause_orderedkind (c_parser *parser ATTRIBUTE_UNUSED, enum omp_clause_code code, tree list) { check_no_duplicate_clause (list, code, omp_clause_code_name[code]); tree c = build_omp_clause (c_parser_peek_token (parser)->location, code); OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenMP 4.0: num_teams ( expression ) */ static tree c_parser_omp_clause_num_teams (c_parser *parser, tree list) { location_t num_teams_loc = c_parser_peek_token (parser)->location; matching_parens parens; if (parens.require_open (parser)) { location_t expr_loc = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expression (parser); expr = convert_lvalue_to_rvalue (expr_loc, expr, false, true); tree c, t = expr.value; t = c_fully_fold (t, false, NULL); parens.skip_until_found_close (parser); if (!INTEGRAL_TYPE_P (TREE_TYPE (t))) { c_parser_error (parser, "expected integer expression"); return list; } /* Attempt to statically determine when the number isn't positive. */ c = fold_build2_loc (expr_loc, LE_EXPR, boolean_type_node, t, build_int_cst (TREE_TYPE (t), 0)); protected_set_expr_location (c, expr_loc); if (c == boolean_true_node) { warning_at (expr_loc, 0, "%<num_teams%> value must be positive"); t = integer_one_node; } check_no_duplicate_clause (list, OMP_CLAUSE_NUM_TEAMS, "num_teams"); c = build_omp_clause (num_teams_loc, OMP_CLAUSE_NUM_TEAMS); OMP_CLAUSE_NUM_TEAMS_EXPR (c) = t; OMP_CLAUSE_CHAIN (c) = list; list = c; } return list; } /* OpenMP 4.0: thread_limit ( expression ) */ static tree c_parser_omp_clause_thread_limit (c_parser *parser, tree list) { location_t num_thread_limit_loc = c_parser_peek_token (parser)->location; matching_parens parens; if (parens.require_open (parser)) { location_t expr_loc = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expression (parser); expr = convert_lvalue_to_rvalue (expr_loc, expr, false, true); tree c, t = expr.value; t = c_fully_fold (t, false, NULL); parens.skip_until_found_close (parser); if (!INTEGRAL_TYPE_P (TREE_TYPE (t))) { c_parser_error (parser, "expected integer expression"); return list; } /* Attempt to statically determine when the number isn't positive. */ c = fold_build2_loc (expr_loc, LE_EXPR, boolean_type_node, t, build_int_cst (TREE_TYPE (t), 0)); protected_set_expr_location (c, expr_loc); if (c == boolean_true_node) { warning_at (expr_loc, 0, "%<thread_limit%> value must be positive"); t = integer_one_node; } check_no_duplicate_clause (list, OMP_CLAUSE_THREAD_LIMIT, "thread_limit"); c = build_omp_clause (num_thread_limit_loc, OMP_CLAUSE_THREAD_LIMIT); OMP_CLAUSE_THREAD_LIMIT_EXPR (c) = t; OMP_CLAUSE_CHAIN (c) = list; list = c; } return list; } /* OpenMP 4.0: aligned ( variable-list ) aligned ( variable-list : constant-expression ) */ static tree c_parser_omp_clause_aligned (c_parser *parser, tree list) { location_t clause_loc = c_parser_peek_token (parser)->location; tree nl, c; matching_parens parens; if (!parens.require_open (parser)) return list; nl = c_parser_omp_variable_list (parser, clause_loc, OMP_CLAUSE_ALIGNED, list); if (c_parser_next_token_is (parser, CPP_COLON)) { c_parser_consume_token (parser); location_t expr_loc = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expr_no_commas (parser, NULL); expr = convert_lvalue_to_rvalue (expr_loc, expr, false, true); tree alignment = expr.value; alignment = c_fully_fold (alignment, false, NULL); if (TREE_CODE (alignment) != INTEGER_CST || !INTEGRAL_TYPE_P (TREE_TYPE (alignment)) || tree_int_cst_sgn (alignment) != 1) { error_at (clause_loc, "%<aligned%> clause alignment expression must " "be positive constant integer expression"); alignment = NULL_TREE; } for (c = nl; c != list; c = OMP_CLAUSE_CHAIN (c)) OMP_CLAUSE_ALIGNED_ALIGNMENT (c) = alignment; } parens.skip_until_found_close (parser); return nl; } /* OpenMP 4.0: linear ( variable-list ) linear ( variable-list : expression ) OpenMP 4.5: linear ( modifier ( variable-list ) ) linear ( modifier ( variable-list ) : expression ) */ static tree c_parser_omp_clause_linear (c_parser *parser, tree list) { location_t clause_loc = c_parser_peek_token (parser)->location; tree nl, c, step; enum omp_clause_linear_kind kind = OMP_CLAUSE_LINEAR_DEFAULT; matching_parens parens; if (!parens.require_open (parser)) return list; if (c_parser_next_token_is (parser, CPP_NAME)) { c_token *tok = c_parser_peek_token (parser); const char *p = IDENTIFIER_POINTER (tok->value); if (strcmp ("val", p) == 0) kind = OMP_CLAUSE_LINEAR_VAL; if (c_parser_peek_2nd_token (parser)->type != CPP_OPEN_PAREN) kind = OMP_CLAUSE_LINEAR_DEFAULT; if (kind != OMP_CLAUSE_LINEAR_DEFAULT) { c_parser_consume_token (parser); c_parser_consume_token (parser); } } nl = c_parser_omp_variable_list (parser, clause_loc, OMP_CLAUSE_LINEAR, list); if (kind != OMP_CLAUSE_LINEAR_DEFAULT) parens.skip_until_found_close (parser); if (c_parser_next_token_is (parser, CPP_COLON)) { c_parser_consume_token (parser); location_t expr_loc = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expression (parser); expr = convert_lvalue_to_rvalue (expr_loc, expr, false, true); step = expr.value; step = c_fully_fold (step, false, NULL); if (!INTEGRAL_TYPE_P (TREE_TYPE (step))) { error_at (clause_loc, "%<linear%> clause step expression must " "be integral"); step = integer_one_node; } } else step = integer_one_node; for (c = nl; c != list; c = OMP_CLAUSE_CHAIN (c)) { OMP_CLAUSE_LINEAR_STEP (c) = step; OMP_CLAUSE_LINEAR_KIND (c) = kind; } parens.skip_until_found_close (parser); return nl; } /* OpenMP 4.0: safelen ( constant-expression ) */ static tree c_parser_omp_clause_safelen (c_parser *parser, tree list) { location_t clause_loc = c_parser_peek_token (parser)->location; tree c, t; matching_parens parens; if (!parens.require_open (parser)) return list; location_t expr_loc = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expr_no_commas (parser, NULL); expr = convert_lvalue_to_rvalue (expr_loc, expr, false, true); t = expr.value; t = c_fully_fold (t, false, NULL); if (TREE_CODE (t) != INTEGER_CST || !INTEGRAL_TYPE_P (TREE_TYPE (t)) || tree_int_cst_sgn (t) != 1) { error_at (clause_loc, "%<safelen%> clause expression must " "be positive constant integer expression"); t = NULL_TREE; } parens.skip_until_found_close (parser); if (t == NULL_TREE || t == error_mark_node) return list; check_no_duplicate_clause (list, OMP_CLAUSE_SAFELEN, "safelen"); c = build_omp_clause (clause_loc, OMP_CLAUSE_SAFELEN); OMP_CLAUSE_SAFELEN_EXPR (c) = t; OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenMP 4.0: simdlen ( constant-expression ) */ static tree c_parser_omp_clause_simdlen (c_parser *parser, tree list) { location_t clause_loc = c_parser_peek_token (parser)->location; tree c, t; matching_parens parens; if (!parens.require_open (parser)) return list; location_t expr_loc = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expr_no_commas (parser, NULL); expr = convert_lvalue_to_rvalue (expr_loc, expr, false, true); t = expr.value; t = c_fully_fold (t, false, NULL); if (TREE_CODE (t) != INTEGER_CST || !INTEGRAL_TYPE_P (TREE_TYPE (t)) || tree_int_cst_sgn (t) != 1) { error_at (clause_loc, "%<simdlen%> clause expression must " "be positive constant integer expression"); t = NULL_TREE; } parens.skip_until_found_close (parser); if (t == NULL_TREE || t == error_mark_node) return list; check_no_duplicate_clause (list, OMP_CLAUSE_SIMDLEN, "simdlen"); c = build_omp_clause (clause_loc, OMP_CLAUSE_SIMDLEN); OMP_CLAUSE_SIMDLEN_EXPR (c) = t; OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenMP 4.5: vec: identifier [+/- integer] vec , identifier [+/- integer] */ static tree c_parser_omp_clause_depend_sink (c_parser *parser, location_t clause_loc, tree list) { tree vec = NULL; if (c_parser_next_token_is_not (parser, CPP_NAME) || c_parser_peek_token (parser)->id_kind != C_ID_ID) { c_parser_error (parser, "expected identifier"); return list; } while (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_token (parser)->id_kind == C_ID_ID) { tree t = lookup_name (c_parser_peek_token (parser)->value); tree addend = NULL; if (t == NULL_TREE) { undeclared_variable (c_parser_peek_token (parser)->location, c_parser_peek_token (parser)->value); t = error_mark_node; } c_parser_consume_token (parser); bool neg = false; if (c_parser_next_token_is (parser, CPP_MINUS)) neg = true; else if (!c_parser_next_token_is (parser, CPP_PLUS)) { addend = integer_zero_node; neg = false; goto add_to_vector; } c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_NUMBER)) { c_parser_error (parser, "expected integer"); return list; } addend = c_parser_peek_token (parser)->value; if (TREE_CODE (addend) != INTEGER_CST) { c_parser_error (parser, "expected integer"); return list; } c_parser_consume_token (parser); add_to_vector: if (t != error_mark_node) { vec = tree_cons (addend, t, vec); if (neg) OMP_CLAUSE_DEPEND_SINK_NEGATIVE (vec) = 1; } if (c_parser_next_token_is_not (parser, CPP_COMMA)) break; c_parser_consume_token (parser); } if (vec == NULL_TREE) return list; tree u = build_omp_clause (clause_loc, OMP_CLAUSE_DEPEND); OMP_CLAUSE_DEPEND_KIND (u) = OMP_CLAUSE_DEPEND_SINK; OMP_CLAUSE_DECL (u) = nreverse (vec); OMP_CLAUSE_CHAIN (u) = list; return u; } /* OpenMP 4.0: depend ( depend-kind: variable-list ) depend-kind: in | out | inout OpenMP 4.5: depend ( source ) depend ( sink : vec ) */ static tree c_parser_omp_clause_depend (c_parser *parser, tree list) { location_t clause_loc = c_parser_peek_token (parser)->location; enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_INOUT; tree nl, c; matching_parens parens; if (!parens.require_open (parser)) return list; if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp ("in", p) == 0) kind = OMP_CLAUSE_DEPEND_IN; else if (strcmp ("inout", p) == 0) kind = OMP_CLAUSE_DEPEND_INOUT; else if (strcmp ("out", p) == 0) kind = OMP_CLAUSE_DEPEND_OUT; else if (strcmp ("source", p) == 0) kind = OMP_CLAUSE_DEPEND_SOURCE; else if (strcmp ("sink", p) == 0) kind = OMP_CLAUSE_DEPEND_SINK; else goto invalid_kind; } else goto invalid_kind; c_parser_consume_token (parser); if (kind == OMP_CLAUSE_DEPEND_SOURCE) { c = build_omp_clause (clause_loc, OMP_CLAUSE_DEPEND); OMP_CLAUSE_DEPEND_KIND (c) = kind; OMP_CLAUSE_DECL (c) = NULL_TREE; OMP_CLAUSE_CHAIN (c) = list; parens.skip_until_found_close (parser); return c; } if (!c_parser_require (parser, CPP_COLON, "expected %<:%>")) goto resync_fail; if (kind == OMP_CLAUSE_DEPEND_SINK) nl = c_parser_omp_clause_depend_sink (parser, clause_loc, list); else { nl = c_parser_omp_variable_list (parser, clause_loc, OMP_CLAUSE_DEPEND, list); for (c = nl; c != list; c = OMP_CLAUSE_CHAIN (c)) OMP_CLAUSE_DEPEND_KIND (c) = kind; } parens.skip_until_found_close (parser); return nl; invalid_kind: c_parser_error (parser, "invalid depend kind"); resync_fail: parens.skip_until_found_close (parser); return list; } /* OpenMP 4.0: map ( map-kind: variable-list ) map ( variable-list ) map-kind: alloc | to | from | tofrom OpenMP 4.5: map-kind: alloc | to | from | tofrom | release | delete map ( always [,] map-kind: variable-list ) */ static tree c_parser_omp_clause_map (c_parser *parser, tree list) { location_t clause_loc = c_parser_peek_token (parser)->location; enum gomp_map_kind kind = GOMP_MAP_TOFROM; int always = 0; enum c_id_kind always_id_kind = C_ID_NONE; location_t always_loc = UNKNOWN_LOCATION; tree always_id = NULL_TREE; tree nl, c; matching_parens parens; if (!parens.require_open (parser)) return list; if (c_parser_next_token_is (parser, CPP_NAME)) { c_token *tok = c_parser_peek_token (parser); const char *p = IDENTIFIER_POINTER (tok->value); always_id_kind = tok->id_kind; always_loc = tok->location; always_id = tok->value; if (strcmp ("always", p) == 0) { c_token *sectok = c_parser_peek_2nd_token (parser); if (sectok->type == CPP_COMMA) { c_parser_consume_token (parser); c_parser_consume_token (parser); always = 2; } else if (sectok->type == CPP_NAME) { p = IDENTIFIER_POINTER (sectok->value); if (strcmp ("alloc", p) == 0 || strcmp ("to", p) == 0 || strcmp ("from", p) == 0 || strcmp ("tofrom", p) == 0 || strcmp ("release", p) == 0 || strcmp ("delete", p) == 0) { c_parser_consume_token (parser); always = 1; } } } } if (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_2nd_token (parser)->type == CPP_COLON) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp ("alloc", p) == 0) kind = GOMP_MAP_ALLOC; else if (strcmp ("to", p) == 0) kind = always ? GOMP_MAP_ALWAYS_TO : GOMP_MAP_TO; else if (strcmp ("from", p) == 0) kind = always ? GOMP_MAP_ALWAYS_FROM : GOMP_MAP_FROM; else if (strcmp ("tofrom", p) == 0) kind = always ? GOMP_MAP_ALWAYS_TOFROM : GOMP_MAP_TOFROM; else if (strcmp ("release", p) == 0) kind = GOMP_MAP_RELEASE; else if (strcmp ("delete", p) == 0) kind = GOMP_MAP_DELETE; else { c_parser_error (parser, "invalid map kind"); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return list; } c_parser_consume_token (parser); c_parser_consume_token (parser); } else if (always) { if (always_id_kind != C_ID_ID) { c_parser_error (parser, "expected identifier"); parens.skip_until_found_close (parser); return list; } tree t = lookup_name (always_id); if (t == NULL_TREE) { undeclared_variable (always_loc, always_id); t = error_mark_node; } if (t != error_mark_node) { tree u = build_omp_clause (clause_loc, OMP_CLAUSE_MAP); OMP_CLAUSE_DECL (u) = t; OMP_CLAUSE_CHAIN (u) = list; OMP_CLAUSE_SET_MAP_KIND (u, kind); list = u; } if (always == 1) { parens.skip_until_found_close (parser); return list; } } nl = c_parser_omp_variable_list (parser, clause_loc, OMP_CLAUSE_MAP, list); for (c = nl; c != list; c = OMP_CLAUSE_CHAIN (c)) OMP_CLAUSE_SET_MAP_KIND (c, kind); parens.skip_until_found_close (parser); return nl; } /* OpenMP 4.0: device ( expression ) */ static tree c_parser_omp_clause_device (c_parser *parser, tree list) { location_t clause_loc = c_parser_peek_token (parser)->location; matching_parens parens; if (parens.require_open (parser)) { location_t expr_loc = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expr_no_commas (parser, NULL); expr = convert_lvalue_to_rvalue (expr_loc, expr, false, true); tree c, t = expr.value; t = c_fully_fold (t, false, NULL); parens.skip_until_found_close (parser); if (!INTEGRAL_TYPE_P (TREE_TYPE (t))) { c_parser_error (parser, "expected integer expression"); return list; } check_no_duplicate_clause (list, OMP_CLAUSE_DEVICE, "device"); c = build_omp_clause (clause_loc, OMP_CLAUSE_DEVICE); OMP_CLAUSE_DEVICE_ID (c) = t; OMP_CLAUSE_CHAIN (c) = list; list = c; } return list; } /* OpenMP 4.0: dist_schedule ( static ) dist_schedule ( static , expression ) */ static tree c_parser_omp_clause_dist_schedule (c_parser *parser, tree list) { tree c, t = NULL_TREE; location_t loc = c_parser_peek_token (parser)->location; matching_parens parens; if (!parens.require_open (parser)) return list; if (!c_parser_next_token_is_keyword (parser, RID_STATIC)) { c_parser_error (parser, "invalid dist_schedule kind"); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return list; } c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_COMMA)) { c_parser_consume_token (parser); location_t expr_loc = c_parser_peek_token (parser)->location; c_expr expr = c_parser_expr_no_commas (parser, NULL); expr = convert_lvalue_to_rvalue (expr_loc, expr, false, true); t = expr.value; t = c_fully_fold (t, false, NULL); parens.skip_until_found_close (parser); } else c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<,%> or %<)%>"); check_no_duplicate_clause (list, OMP_CLAUSE_SCHEDULE, "schedule"); if (t == error_mark_node) return list; c = build_omp_clause (loc, OMP_CLAUSE_DIST_SCHEDULE); OMP_CLAUSE_DIST_SCHEDULE_CHUNK_EXPR (c) = t; OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenMP 4.0: proc_bind ( proc-bind-kind ) proc-bind-kind: master | close | spread */ static tree c_parser_omp_clause_proc_bind (c_parser *parser, tree list) { location_t clause_loc = c_parser_peek_token (parser)->location; enum omp_clause_proc_bind_kind kind; tree c; matching_parens parens; if (!parens.require_open (parser)) return list; if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp ("master", p) == 0) kind = OMP_CLAUSE_PROC_BIND_MASTER; else if (strcmp ("close", p) == 0) kind = OMP_CLAUSE_PROC_BIND_CLOSE; else if (strcmp ("spread", p) == 0) kind = OMP_CLAUSE_PROC_BIND_SPREAD; else goto invalid_kind; } else goto invalid_kind; c_parser_consume_token (parser); parens.skip_until_found_close (parser); c = build_omp_clause (clause_loc, OMP_CLAUSE_PROC_BIND); OMP_CLAUSE_PROC_BIND_KIND (c) = kind; OMP_CLAUSE_CHAIN (c) = list; return c; invalid_kind: c_parser_error (parser, "invalid proc_bind kind"); parens.skip_until_found_close (parser); return list; } /* OpenMP 4.0: to ( variable-list ) */ static tree c_parser_omp_clause_to (c_parser *parser, tree list) { return c_parser_omp_var_list_parens (parser, OMP_CLAUSE_TO, list); } /* OpenMP 4.0: from ( variable-list ) */ static tree c_parser_omp_clause_from (c_parser *parser, tree list) { return c_parser_omp_var_list_parens (parser, OMP_CLAUSE_FROM, list); } /* OpenMP 4.0: uniform ( variable-list ) */ static tree c_parser_omp_clause_uniform (c_parser *parser, tree list) { /* The clauses location. */ location_t loc = c_parser_peek_token (parser)->location; matching_parens parens; if (parens.require_open (parser)) { list = c_parser_omp_variable_list (parser, loc, OMP_CLAUSE_UNIFORM, list); parens.skip_until_found_close (parser); } return list; } /* Parse all OpenACC clauses. The set clauses allowed by the directive is a bitmask in MASK. Return the list of clauses found. */ static tree c_parser_oacc_all_clauses (c_parser *parser, omp_clause_mask mask, const char *where, bool finish_p = true) { tree clauses = NULL; bool first = true; while (c_parser_next_token_is_not (parser, CPP_PRAGMA_EOL)) { location_t here; pragma_omp_clause c_kind; const char *c_name; tree prev = clauses; if (!first && c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); here = c_parser_peek_token (parser)->location; c_kind = c_parser_omp_clause_name (parser); switch (c_kind) { case PRAGMA_OACC_CLAUSE_ASYNC: clauses = c_parser_oacc_clause_async (parser, clauses); c_name = "async"; break; case PRAGMA_OACC_CLAUSE_AUTO: clauses = c_parser_oacc_simple_clause (parser, OMP_CLAUSE_AUTO, clauses); c_name = "auto"; break; case PRAGMA_OACC_CLAUSE_COLLAPSE: clauses = c_parser_omp_clause_collapse (parser, clauses); c_name = "collapse"; break; case PRAGMA_OACC_CLAUSE_COPY: clauses = c_parser_oacc_data_clause (parser, c_kind, clauses); c_name = "copy"; break; case PRAGMA_OACC_CLAUSE_COPYIN: clauses = c_parser_oacc_data_clause (parser, c_kind, clauses); c_name = "copyin"; break; case PRAGMA_OACC_CLAUSE_COPYOUT: clauses = c_parser_oacc_data_clause (parser, c_kind, clauses); c_name = "copyout"; break; case PRAGMA_OACC_CLAUSE_CREATE: clauses = c_parser_oacc_data_clause (parser, c_kind, clauses); c_name = "create"; break; case PRAGMA_OACC_CLAUSE_DELETE: clauses = c_parser_oacc_data_clause (parser, c_kind, clauses); c_name = "delete"; break; case PRAGMA_OMP_CLAUSE_DEFAULT: clauses = c_parser_omp_clause_default (parser, clauses, true); c_name = "default"; break; case PRAGMA_OACC_CLAUSE_DEVICE: clauses = c_parser_oacc_data_clause (parser, c_kind, clauses); c_name = "device"; break; case PRAGMA_OACC_CLAUSE_DEVICEPTR: clauses = c_parser_oacc_data_clause_deviceptr (parser, clauses); c_name = "deviceptr"; break; case PRAGMA_OACC_CLAUSE_DEVICE_RESIDENT: clauses = c_parser_oacc_data_clause (parser, c_kind, clauses); c_name = "device_resident"; break; case PRAGMA_OACC_CLAUSE_FIRSTPRIVATE: clauses = c_parser_omp_clause_firstprivate (parser, clauses); c_name = "firstprivate"; break; case PRAGMA_OACC_CLAUSE_GANG: c_name = "gang"; clauses = c_parser_oacc_shape_clause (parser, OMP_CLAUSE_GANG, c_name, clauses); break; case PRAGMA_OACC_CLAUSE_HOST: clauses = c_parser_oacc_data_clause (parser, c_kind, clauses); c_name = "host"; break; case PRAGMA_OACC_CLAUSE_IF: clauses = c_parser_omp_clause_if (parser, clauses, false); c_name = "if"; break; case PRAGMA_OACC_CLAUSE_INDEPENDENT: clauses = c_parser_oacc_simple_clause (parser, OMP_CLAUSE_INDEPENDENT, clauses); c_name = "independent"; break; case PRAGMA_OACC_CLAUSE_LINK: clauses = c_parser_oacc_data_clause (parser, c_kind, clauses); c_name = "link"; break; case PRAGMA_OACC_CLAUSE_NUM_GANGS: clauses = c_parser_oacc_single_int_clause (parser, OMP_CLAUSE_NUM_GANGS, clauses); c_name = "num_gangs"; break; case PRAGMA_OACC_CLAUSE_NUM_WORKERS: clauses = c_parser_oacc_single_int_clause (parser, OMP_CLAUSE_NUM_WORKERS, clauses); c_name = "num_workers"; break; case PRAGMA_OACC_CLAUSE_PRESENT: clauses = c_parser_oacc_data_clause (parser, c_kind, clauses); c_name = "present"; break; case PRAGMA_OACC_CLAUSE_PRESENT_OR_COPY: clauses = c_parser_oacc_data_clause (parser, c_kind, clauses); c_name = "present_or_copy"; break; case PRAGMA_OACC_CLAUSE_PRESENT_OR_COPYIN: clauses = c_parser_oacc_data_clause (parser, c_kind, clauses); c_name = "present_or_copyin"; break; case PRAGMA_OACC_CLAUSE_PRESENT_OR_COPYOUT: clauses = c_parser_oacc_data_clause (parser, c_kind, clauses); c_name = "present_or_copyout"; break; case PRAGMA_OACC_CLAUSE_PRESENT_OR_CREATE: clauses = c_parser_oacc_data_clause (parser, c_kind, clauses); c_name = "present_or_create"; break; case PRAGMA_OACC_CLAUSE_PRIVATE: clauses = c_parser_omp_clause_private (parser, clauses); c_name = "private"; break; case PRAGMA_OACC_CLAUSE_REDUCTION: clauses = c_parser_omp_clause_reduction (parser, clauses); c_name = "reduction"; break; case PRAGMA_OACC_CLAUSE_SELF: clauses = c_parser_oacc_data_clause (parser, c_kind, clauses); c_name = "self"; break; case PRAGMA_OACC_CLAUSE_SEQ: clauses = c_parser_oacc_simple_clause (parser, OMP_CLAUSE_SEQ, clauses); c_name = "seq"; break; case PRAGMA_OACC_CLAUSE_TILE: clauses = c_parser_oacc_clause_tile (parser, clauses); c_name = "tile"; break; case PRAGMA_OACC_CLAUSE_USE_DEVICE: clauses = c_parser_omp_clause_use_device_ptr (parser, clauses); c_name = "use_device"; break; case PRAGMA_OACC_CLAUSE_VECTOR: c_name = "vector"; clauses = c_parser_oacc_shape_clause (parser, OMP_CLAUSE_VECTOR, c_name, clauses); break; case PRAGMA_OACC_CLAUSE_VECTOR_LENGTH: clauses = c_parser_oacc_single_int_clause (parser, OMP_CLAUSE_VECTOR_LENGTH, clauses); c_name = "vector_length"; break; case PRAGMA_OACC_CLAUSE_WAIT: clauses = c_parser_oacc_clause_wait (parser, clauses); c_name = "wait"; break; case PRAGMA_OACC_CLAUSE_WORKER: c_name = "worker"; clauses = c_parser_oacc_shape_clause (parser, OMP_CLAUSE_WORKER, c_name, clauses); break; default: c_parser_error (parser, "expected %<#pragma acc%> clause"); goto saw_error; } first = false; if (((mask >> c_kind) & 1) == 0) { /* Remove the invalid clause(s) from the list to avoid confusing the rest of the compiler. */ clauses = prev; error_at (here, "%qs is not valid for %qs", c_name, where); } } saw_error: c_parser_skip_to_pragma_eol (parser); if (finish_p) return c_finish_omp_clauses (clauses, C_ORT_ACC); return clauses; } /* Parse all OpenMP clauses. The set clauses allowed by the directive is a bitmask in MASK. Return the list of clauses found. */ static tree c_parser_omp_all_clauses (c_parser *parser, omp_clause_mask mask, const char *where, bool finish_p = true) { tree clauses = NULL; bool first = true; while (c_parser_next_token_is_not (parser, CPP_PRAGMA_EOL)) { location_t here; pragma_omp_clause c_kind; const char *c_name; tree prev = clauses; if (!first && c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); here = c_parser_peek_token (parser)->location; c_kind = c_parser_omp_clause_name (parser); switch (c_kind) { case PRAGMA_OMP_CLAUSE_COLLAPSE: clauses = c_parser_omp_clause_collapse (parser, clauses); c_name = "collapse"; break; case PRAGMA_OMP_CLAUSE_COPYIN: clauses = c_parser_omp_clause_copyin (parser, clauses); c_name = "copyin"; break; case PRAGMA_OMP_CLAUSE_COPYPRIVATE: clauses = c_parser_omp_clause_copyprivate (parser, clauses); c_name = "copyprivate"; break; case PRAGMA_OMP_CLAUSE_DEFAULT: clauses = c_parser_omp_clause_default (parser, clauses, false); c_name = "default"; break; case PRAGMA_OMP_CLAUSE_FIRSTPRIVATE: clauses = c_parser_omp_clause_firstprivate (parser, clauses); c_name = "firstprivate"; break; case PRAGMA_OMP_CLAUSE_FINAL: clauses = c_parser_omp_clause_final (parser, clauses); c_name = "final"; break; case PRAGMA_OMP_CLAUSE_GRAINSIZE: clauses = c_parser_omp_clause_grainsize (parser, clauses); c_name = "grainsize"; break; case PRAGMA_OMP_CLAUSE_HINT: clauses = c_parser_omp_clause_hint (parser, clauses); c_name = "hint"; break; case PRAGMA_OMP_CLAUSE_DEFAULTMAP: clauses = c_parser_omp_clause_defaultmap (parser, clauses); c_name = "defaultmap"; break; case PRAGMA_OMP_CLAUSE_IF: clauses = c_parser_omp_clause_if (parser, clauses, true); c_name = "if"; break; case PRAGMA_OMP_CLAUSE_LASTPRIVATE: clauses = c_parser_omp_clause_lastprivate (parser, clauses); c_name = "lastprivate"; break; case PRAGMA_OMP_CLAUSE_MERGEABLE: clauses = c_parser_omp_clause_mergeable (parser, clauses); c_name = "mergeable"; break; case PRAGMA_OMP_CLAUSE_NOWAIT: clauses = c_parser_omp_clause_nowait (parser, clauses); c_name = "nowait"; break; case PRAGMA_OMP_CLAUSE_NUM_TASKS: clauses = c_parser_omp_clause_num_tasks (parser, clauses); c_name = "num_tasks"; break; case PRAGMA_OMP_CLAUSE_NUM_THREADS: clauses = c_parser_omp_clause_num_threads (parser, clauses); c_name = "num_threads"; break; case PRAGMA_OMP_CLAUSE_ORDERED: clauses = c_parser_omp_clause_ordered (parser, clauses); c_name = "ordered"; break; case PRAGMA_OMP_CLAUSE_PRIORITY: clauses = c_parser_omp_clause_priority (parser, clauses); c_name = "priority"; break; case PRAGMA_OMP_CLAUSE_PRIVATE: clauses = c_parser_omp_clause_private (parser, clauses); c_name = "private"; break; case PRAGMA_OMP_CLAUSE_REDUCTION: clauses = c_parser_omp_clause_reduction (parser, clauses); c_name = "reduction"; break; case PRAGMA_OMP_CLAUSE_SCHEDULE: clauses = c_parser_omp_clause_schedule (parser, clauses); c_name = "schedule"; break; case PRAGMA_OMP_CLAUSE_SHARED: clauses = c_parser_omp_clause_shared (parser, clauses); c_name = "shared"; break; case PRAGMA_OMP_CLAUSE_UNTIED: clauses = c_parser_omp_clause_untied (parser, clauses); c_name = "untied"; break; case PRAGMA_OMP_CLAUSE_INBRANCH: clauses = c_parser_omp_clause_branch (parser, OMP_CLAUSE_INBRANCH, clauses); c_name = "inbranch"; break; case PRAGMA_OMP_CLAUSE_NOTINBRANCH: clauses = c_parser_omp_clause_branch (parser, OMP_CLAUSE_NOTINBRANCH, clauses); c_name = "notinbranch"; break; case PRAGMA_OMP_CLAUSE_PARALLEL: clauses = c_parser_omp_clause_cancelkind (parser, OMP_CLAUSE_PARALLEL, clauses); c_name = "parallel"; if (!first) { clause_not_first: error_at (here, "%qs must be the first clause of %qs", c_name, where); clauses = prev; } break; case PRAGMA_OMP_CLAUSE_FOR: clauses = c_parser_omp_clause_cancelkind (parser, OMP_CLAUSE_FOR, clauses); c_name = "for"; if (!first) goto clause_not_first; break; case PRAGMA_OMP_CLAUSE_SECTIONS: clauses = c_parser_omp_clause_cancelkind (parser, OMP_CLAUSE_SECTIONS, clauses); c_name = "sections"; if (!first) goto clause_not_first; break; case PRAGMA_OMP_CLAUSE_TASKGROUP: clauses = c_parser_omp_clause_cancelkind (parser, OMP_CLAUSE_TASKGROUP, clauses); c_name = "taskgroup"; if (!first) goto clause_not_first; break; case PRAGMA_OMP_CLAUSE_LINK: clauses = c_parser_omp_var_list_parens (parser, OMP_CLAUSE_LINK, clauses); c_name = "link"; break; case PRAGMA_OMP_CLAUSE_TO: if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_LINK)) != 0) clauses = c_parser_omp_var_list_parens (parser, OMP_CLAUSE_TO_DECLARE, clauses); else clauses = c_parser_omp_clause_to (parser, clauses); c_name = "to"; break; case PRAGMA_OMP_CLAUSE_FROM: clauses = c_parser_omp_clause_from (parser, clauses); c_name = "from"; break; case PRAGMA_OMP_CLAUSE_UNIFORM: clauses = c_parser_omp_clause_uniform (parser, clauses); c_name = "uniform"; break; case PRAGMA_OMP_CLAUSE_NUM_TEAMS: clauses = c_parser_omp_clause_num_teams (parser, clauses); c_name = "num_teams"; break; case PRAGMA_OMP_CLAUSE_THREAD_LIMIT: clauses = c_parser_omp_clause_thread_limit (parser, clauses); c_name = "thread_limit"; break; case PRAGMA_OMP_CLAUSE_ALIGNED: clauses = c_parser_omp_clause_aligned (parser, clauses); c_name = "aligned"; break; case PRAGMA_OMP_CLAUSE_LINEAR: clauses = c_parser_omp_clause_linear (parser, clauses); c_name = "linear"; break; case PRAGMA_OMP_CLAUSE_DEPEND: clauses = c_parser_omp_clause_depend (parser, clauses); c_name = "depend"; break; case PRAGMA_OMP_CLAUSE_MAP: clauses = c_parser_omp_clause_map (parser, clauses); c_name = "map"; break; case PRAGMA_OMP_CLAUSE_USE_DEVICE_PTR: clauses = c_parser_omp_clause_use_device_ptr (parser, clauses); c_name = "use_device_ptr"; break; case PRAGMA_OMP_CLAUSE_IS_DEVICE_PTR: clauses = c_parser_omp_clause_is_device_ptr (parser, clauses); c_name = "is_device_ptr"; break; case PRAGMA_OMP_CLAUSE_DEVICE: clauses = c_parser_omp_clause_device (parser, clauses); c_name = "device"; break; case PRAGMA_OMP_CLAUSE_DIST_SCHEDULE: clauses = c_parser_omp_clause_dist_schedule (parser, clauses); c_name = "dist_schedule"; break; case PRAGMA_OMP_CLAUSE_PROC_BIND: clauses = c_parser_omp_clause_proc_bind (parser, clauses); c_name = "proc_bind"; break; case PRAGMA_OMP_CLAUSE_SAFELEN: clauses = c_parser_omp_clause_safelen (parser, clauses); c_name = "safelen"; break; case PRAGMA_OMP_CLAUSE_SIMDLEN: clauses = c_parser_omp_clause_simdlen (parser, clauses); c_name = "simdlen"; break; case PRAGMA_OMP_CLAUSE_NOGROUP: clauses = c_parser_omp_clause_nogroup (parser, clauses); c_name = "nogroup"; break; case PRAGMA_OMP_CLAUSE_THREADS: clauses = c_parser_omp_clause_orderedkind (parser, OMP_CLAUSE_THREADS, clauses); c_name = "threads"; break; case PRAGMA_OMP_CLAUSE_SIMD: clauses = c_parser_omp_clause_orderedkind (parser, OMP_CLAUSE_SIMD, clauses); c_name = "simd"; break; default: c_parser_error (parser, "expected %<#pragma omp%> clause"); goto saw_error; } first = false; if (((mask >> c_kind) & 1) == 0) { /* Remove the invalid clause(s) from the list to avoid confusing the rest of the compiler. */ clauses = prev; error_at (here, "%qs is not valid for %qs", c_name, where); } } saw_error: c_parser_skip_to_pragma_eol (parser); if (finish_p) { if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_UNIFORM)) != 0) return c_finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD); return c_finish_omp_clauses (clauses, C_ORT_OMP); } return clauses; } /* OpenACC 2.0, OpenMP 2.5: structured-block: statement In practice, we're also interested in adding the statement to an outer node. So it is convenient if we work around the fact that c_parser_statement calls add_stmt. */ static tree c_parser_omp_structured_block (c_parser *parser, bool *if_p) { tree stmt = push_stmt_list (); c_parser_statement (parser, if_p); return pop_stmt_list (stmt); } /* OpenACC 2.0: # pragma acc cache (variable-list) new-line LOC is the location of the #pragma token. */ static tree c_parser_oacc_cache (location_t loc, c_parser *parser) { tree stmt, clauses; clauses = c_parser_omp_var_list_parens (parser, OMP_CLAUSE__CACHE_, NULL); clauses = c_finish_omp_clauses (clauses, C_ORT_ACC); c_parser_skip_to_pragma_eol (parser); stmt = make_node (OACC_CACHE); TREE_TYPE (stmt) = void_type_node; OACC_CACHE_CLAUSES (stmt) = clauses; SET_EXPR_LOCATION (stmt, loc); add_stmt (stmt); return stmt; } /* OpenACC 2.0: # pragma acc data oacc-data-clause[optseq] new-line structured-block LOC is the location of the #pragma token. */ #define OACC_DATA_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_COPY) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_COPYIN) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_COPYOUT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_CREATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_DEVICEPTR) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_IF) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_COPY) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_COPYIN) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_COPYOUT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_CREATE) ) static tree c_parser_oacc_data (location_t loc, c_parser *parser, bool *if_p) { tree stmt, clauses, block; clauses = c_parser_oacc_all_clauses (parser, OACC_DATA_CLAUSE_MASK, "#pragma acc data"); block = c_begin_omp_parallel (); add_stmt (c_parser_omp_structured_block (parser, if_p)); stmt = c_finish_oacc_data (loc, clauses, block); return stmt; } /* OpenACC 2.0: # pragma acc declare oacc-data-clause[optseq] new-line */ #define OACC_DECLARE_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_COPY) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_COPYIN) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_COPYOUT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_CREATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_DEVICEPTR) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_DEVICE_RESIDENT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_LINK) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_COPY) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_COPYIN) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_COPYOUT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_CREATE) ) static void c_parser_oacc_declare (c_parser *parser) { location_t pragma_loc = c_parser_peek_token (parser)->location; tree clauses, stmt, t, decl; bool error = false; c_parser_consume_pragma (parser); clauses = c_parser_oacc_all_clauses (parser, OACC_DECLARE_CLAUSE_MASK, "#pragma acc declare"); if (!clauses) { error_at (pragma_loc, "no valid clauses specified in %<#pragma acc declare%>"); return; } for (t = clauses; t; t = OMP_CLAUSE_CHAIN (t)) { location_t loc = OMP_CLAUSE_LOCATION (t); decl = OMP_CLAUSE_DECL (t); if (!DECL_P (decl)) { error_at (loc, "array section in %<#pragma acc declare%>"); error = true; continue; } switch (OMP_CLAUSE_MAP_KIND (t)) { case GOMP_MAP_FIRSTPRIVATE_POINTER: case GOMP_MAP_FORCE_ALLOC: case GOMP_MAP_FORCE_TO: case GOMP_MAP_FORCE_DEVICEPTR: case GOMP_MAP_DEVICE_RESIDENT: break; case GOMP_MAP_LINK: if (!global_bindings_p () && (TREE_STATIC (decl) || !DECL_EXTERNAL (decl))) { error_at (loc, "%qD must be a global variable in " "%<#pragma acc declare link%>", decl); error = true; continue; } break; default: if (global_bindings_p ()) { error_at (loc, "invalid OpenACC clause at file scope"); error = true; continue; } if (DECL_EXTERNAL (decl)) { error_at (loc, "invalid use of %<extern%> variable %qD " "in %<#pragma acc declare%>", decl); error = true; continue; } else if (TREE_PUBLIC (decl)) { error_at (loc, "invalid use of %<global%> variable %qD " "in %<#pragma acc declare%>", decl); error = true; continue; } break; } if (lookup_attribute ("omp declare target", DECL_ATTRIBUTES (decl)) || lookup_attribute ("omp declare target link", DECL_ATTRIBUTES (decl))) { error_at (loc, "variable %qD used more than once with " "%<#pragma acc declare%>", decl); error = true; continue; } if (!error) { tree id; if (OMP_CLAUSE_MAP_KIND (t) == GOMP_MAP_LINK) id = get_identifier ("omp declare target link"); else id = get_identifier ("omp declare target"); DECL_ATTRIBUTES (decl) = tree_cons (id, NULL_TREE, DECL_ATTRIBUTES (decl)); if (global_bindings_p ()) { symtab_node *node = symtab_node::get (decl); if (node != NULL) { node->offloadable = 1; if (ENABLE_OFFLOADING) { g->have_offload = true; if (is_a <varpool_node *> (node)) vec_safe_push (offload_vars, decl); } } } } } if (error || global_bindings_p ()) return; stmt = make_node (OACC_DECLARE); TREE_TYPE (stmt) = void_type_node; OACC_DECLARE_CLAUSES (stmt) = clauses; SET_EXPR_LOCATION (stmt, pragma_loc); add_stmt (stmt); return; } /* OpenACC 2.0: # pragma acc enter data oacc-enter-data-clause[optseq] new-line or # pragma acc exit data oacc-exit-data-clause[optseq] new-line LOC is the location of the #pragma token. */ #define OACC_ENTER_DATA_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_IF) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_ASYNC) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_COPYIN) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_CREATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_COPYIN) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_CREATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_WAIT) ) #define OACC_EXIT_DATA_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_IF) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_ASYNC) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_COPYOUT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_DELETE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_WAIT) ) static void c_parser_oacc_enter_exit_data (c_parser *parser, bool enter) { location_t loc = c_parser_peek_token (parser)->location; tree clauses, stmt; const char *p = ""; c_parser_consume_pragma (parser); if (c_parser_next_token_is (parser, CPP_NAME)) { p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); c_parser_consume_token (parser); } if (strcmp (p, "data") != 0) { error_at (loc, "expected %<data%> after %<#pragma acc %s%>", enter ? "enter" : "exit"); parser->error = true; c_parser_skip_to_pragma_eol (parser); return; } if (enter) clauses = c_parser_oacc_all_clauses (parser, OACC_ENTER_DATA_CLAUSE_MASK, "#pragma acc enter data"); else clauses = c_parser_oacc_all_clauses (parser, OACC_EXIT_DATA_CLAUSE_MASK, "#pragma acc exit data"); if (omp_find_clause (clauses, OMP_CLAUSE_MAP) == NULL_TREE) { error_at (loc, "%<#pragma acc %s data%> has no data movement clause", enter ? "enter" : "exit"); return; } stmt = enter ? make_node (OACC_ENTER_DATA) : make_node (OACC_EXIT_DATA); TREE_TYPE (stmt) = void_type_node; OMP_STANDALONE_CLAUSES (stmt) = clauses; SET_EXPR_LOCATION (stmt, loc); add_stmt (stmt); } /* OpenACC 2.0: # pragma acc host_data oacc-data-clause[optseq] new-line structured-block */ #define OACC_HOST_DATA_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_USE_DEVICE) ) static tree c_parser_oacc_host_data (location_t loc, c_parser *parser, bool *if_p) { tree stmt, clauses, block; clauses = c_parser_oacc_all_clauses (parser, OACC_HOST_DATA_CLAUSE_MASK, "#pragma acc host_data"); block = c_begin_omp_parallel (); add_stmt (c_parser_omp_structured_block (parser, if_p)); stmt = c_finish_oacc_host_data (loc, clauses, block); return stmt; } /* OpenACC 2.0: # pragma acc loop oacc-loop-clause[optseq] new-line structured-block LOC is the location of the #pragma token. */ #define OACC_LOOP_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_COLLAPSE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_REDUCTION) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_GANG) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_WORKER) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_VECTOR) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_AUTO) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_INDEPENDENT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_SEQ) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_TILE) ) static tree c_parser_oacc_loop (location_t loc, c_parser *parser, char *p_name, omp_clause_mask mask, tree *cclauses, bool *if_p) { bool is_parallel = ((mask >> PRAGMA_OACC_CLAUSE_REDUCTION) & 1) == 1; strcat (p_name, " loop"); mask |= OACC_LOOP_CLAUSE_MASK; tree clauses = c_parser_oacc_all_clauses (parser, mask, p_name, cclauses == NULL); if (cclauses) { clauses = c_oacc_split_loop_clauses (clauses, cclauses, is_parallel); if (*cclauses) *cclauses = c_finish_omp_clauses (*cclauses, C_ORT_ACC); if (clauses) clauses = c_finish_omp_clauses (clauses, C_ORT_ACC); } tree block = c_begin_compound_stmt (true); tree stmt = c_parser_omp_for_loop (loc, parser, OACC_LOOP, clauses, NULL, if_p); block = c_end_compound_stmt (loc, block, true); add_stmt (block); return stmt; } /* OpenACC 2.0: # pragma acc kernels oacc-kernels-clause[optseq] new-line structured-block or # pragma acc parallel oacc-parallel-clause[optseq] new-line structured-block LOC is the location of the #pragma token. */ #define OACC_KERNELS_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_ASYNC) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_COPY) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_COPYIN) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_COPYOUT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_CREATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_DEFAULT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_DEVICEPTR) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_IF) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_NUM_GANGS) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_NUM_WORKERS) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_COPY) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_COPYIN) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_COPYOUT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_CREATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_VECTOR_LENGTH) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_WAIT) ) #define OACC_PARALLEL_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_ASYNC) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_COPY) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_COPYIN) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_COPYOUT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_CREATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_DEFAULT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_DEVICEPTR) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_IF) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_FIRSTPRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_NUM_GANGS) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_NUM_WORKERS) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_COPY) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_COPYIN) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_COPYOUT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_PRESENT_OR_CREATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_REDUCTION) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_VECTOR_LENGTH) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_WAIT) ) static tree c_parser_oacc_kernels_parallel (location_t loc, c_parser *parser, enum pragma_kind p_kind, char *p_name, bool *if_p) { omp_clause_mask mask; enum tree_code code; switch (p_kind) { case PRAGMA_OACC_KERNELS: strcat (p_name, " kernels"); mask = OACC_KERNELS_CLAUSE_MASK; code = OACC_KERNELS; break; case PRAGMA_OACC_PARALLEL: strcat (p_name, " parallel"); mask = OACC_PARALLEL_CLAUSE_MASK; code = OACC_PARALLEL; break; default: gcc_unreachable (); } if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp (p, "loop") == 0) { c_parser_consume_token (parser); tree block = c_begin_omp_parallel (); tree clauses; c_parser_oacc_loop (loc, parser, p_name, mask, &clauses, if_p); return c_finish_omp_construct (loc, code, block, clauses); } } tree clauses = c_parser_oacc_all_clauses (parser, mask, p_name); tree block = c_begin_omp_parallel (); add_stmt (c_parser_omp_structured_block (parser, if_p)); return c_finish_omp_construct (loc, code, block, clauses); } /* OpenACC 2.0: # pragma acc routine oacc-routine-clause[optseq] new-line function-definition # pragma acc routine ( name ) oacc-routine-clause[optseq] new-line */ #define OACC_ROUTINE_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_GANG) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_WORKER) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_VECTOR) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_SEQ) ) /* Parse an OpenACC routine directive. For named directives, we apply immediately to the named function. For unnamed ones we then parse a declaration or definition, which must be for a function. */ static void c_parser_oacc_routine (c_parser *parser, enum pragma_context context) { gcc_checking_assert (context == pragma_external); oacc_routine_data data; data.error_seen = false; data.fndecl_seen = false; data.clauses = NULL_TREE; data.loc = c_parser_peek_token (parser)->location; c_parser_consume_pragma (parser); /* Look for optional '( name )'. */ if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { c_parser_consume_token (parser); /* '(' */ tree decl = NULL_TREE; c_token *name_token = c_parser_peek_token (parser); location_t name_loc = name_token->location; if (name_token->type == CPP_NAME && (name_token->id_kind == C_ID_ID || name_token->id_kind == C_ID_TYPENAME)) { decl = lookup_name (name_token->value); if (!decl) error_at (name_loc, "%qE has not been declared", name_token->value); c_parser_consume_token (parser); } else c_parser_error (parser, "expected function name"); if (!decl || !c_parser_require (parser, CPP_CLOSE_PAREN, "expected %<)%>")) { c_parser_skip_to_pragma_eol (parser, false); return; } data.clauses = c_parser_oacc_all_clauses (parser, OACC_ROUTINE_CLAUSE_MASK, "#pragma acc routine"); if (TREE_CODE (decl) != FUNCTION_DECL) { error_at (name_loc, "%qD does not refer to a function", decl); return; } c_finish_oacc_routine (&data, decl, false); } else /* No optional '( name )'. */ { data.clauses = c_parser_oacc_all_clauses (parser, OACC_ROUTINE_CLAUSE_MASK, "#pragma acc routine"); /* Emit a helpful diagnostic if there's another pragma following this one. Also don't allow a static assertion declaration, as in the following we'll just parse a *single* "declaration or function definition", and the static assertion counts an one. */ if (c_parser_next_token_is (parser, CPP_PRAGMA) || c_parser_next_token_is_keyword (parser, RID_STATIC_ASSERT)) { error_at (data.loc, "%<#pragma acc routine%> not immediately followed by" " function declaration or definition"); /* ..., and then just keep going. */ return; } /* We only have to consider the pragma_external case here. */ if (c_parser_next_token_is (parser, CPP_KEYWORD) && c_parser_peek_token (parser)->keyword == RID_EXTENSION) { int ext = disable_extension_diagnostics (); do c_parser_consume_token (parser); while (c_parser_next_token_is (parser, CPP_KEYWORD) && c_parser_peek_token (parser)->keyword == RID_EXTENSION); c_parser_declaration_or_fndef (parser, true, true, true, false, true, NULL, vNULL, &data); restore_extension_diagnostics (ext); } else c_parser_declaration_or_fndef (parser, true, true, true, false, true, NULL, vNULL, &data); } } /* Finalize an OpenACC routine pragma, applying it to FNDECL. IS_DEFN is true if we're applying it to the definition. */ static void c_finish_oacc_routine (struct oacc_routine_data *data, tree fndecl, bool is_defn) { /* Keep going if we're in error reporting mode. */ if (data->error_seen || fndecl == error_mark_node) return; if (data->fndecl_seen) { error_at (data->loc, "%<#pragma acc routine%> not immediately followed by" " a single function declaration or definition"); data->error_seen = true; return; } if (fndecl == NULL_TREE || TREE_CODE (fndecl) != FUNCTION_DECL) { error_at (data->loc, "%<#pragma acc routine%> not immediately followed by" " function declaration or definition"); data->error_seen = true; return; } if (oacc_get_fn_attrib (fndecl)) { error_at (data->loc, "%<#pragma acc routine%> already applied to %qD", fndecl); data->error_seen = true; return; } if (TREE_USED (fndecl) || (!is_defn && DECL_SAVED_TREE (fndecl))) { error_at (data->loc, TREE_USED (fndecl) ? G_("%<#pragma acc routine%> must be applied before use") : G_("%<#pragma acc routine%> must be applied before " "definition")); data->error_seen = true; return; } /* Process the routine's dimension clauses. */ tree dims = oacc_build_routine_dims (data->clauses); oacc_replace_fn_attrib (fndecl, dims); /* Add an "omp declare target" attribute. */ DECL_ATTRIBUTES (fndecl) = tree_cons (get_identifier ("omp declare target"), NULL_TREE, DECL_ATTRIBUTES (fndecl)); /* Remember that we've used this "#pragma acc routine". */ data->fndecl_seen = true; } /* OpenACC 2.0: # pragma acc update oacc-update-clause[optseq] new-line */ #define OACC_UPDATE_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_ASYNC) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_DEVICE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_HOST) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_IF) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_SELF) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_WAIT) ) static void c_parser_oacc_update (c_parser *parser) { location_t loc = c_parser_peek_token (parser)->location; c_parser_consume_pragma (parser); tree clauses = c_parser_oacc_all_clauses (parser, OACC_UPDATE_CLAUSE_MASK, "#pragma acc update"); if (omp_find_clause (clauses, OMP_CLAUSE_MAP) == NULL_TREE) { error_at (loc, "%<#pragma acc update%> must contain at least one " "%<device%> or %<host%> or %<self%> clause"); return; } if (parser->error) return; tree stmt = make_node (OACC_UPDATE); TREE_TYPE (stmt) = void_type_node; OACC_UPDATE_CLAUSES (stmt) = clauses; SET_EXPR_LOCATION (stmt, loc); add_stmt (stmt); } /* OpenACC 2.0: # pragma acc wait [(intseq)] oacc-wait-clause[optseq] new-line LOC is the location of the #pragma token. */ #define OACC_WAIT_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OACC_CLAUSE_ASYNC) ) static tree c_parser_oacc_wait (location_t loc, c_parser *parser, char *p_name) { tree clauses, list = NULL_TREE, stmt = NULL_TREE; if (c_parser_peek_token (parser)->type == CPP_OPEN_PAREN) list = c_parser_oacc_wait_list (parser, loc, list); strcpy (p_name, " wait"); clauses = c_parser_oacc_all_clauses (parser, OACC_WAIT_CLAUSE_MASK, p_name); stmt = c_finish_oacc_wait (loc, list, clauses); add_stmt (stmt); return stmt; } /* OpenMP 2.5: # pragma omp atomic new-line expression-stmt expression-stmt: x binop= expr | x++ | ++x | x-- | --x binop: +, *, -, /, &, ^, |, <<, >> where x is an lvalue expression with scalar type. OpenMP 3.1: # pragma omp atomic new-line update-stmt # pragma omp atomic read new-line read-stmt # pragma omp atomic write new-line write-stmt # pragma omp atomic update new-line update-stmt # pragma omp atomic capture new-line capture-stmt # pragma omp atomic capture new-line capture-block read-stmt: v = x write-stmt: x = expr update-stmt: expression-stmt | x = x binop expr capture-stmt: v = expression-stmt capture-block: { v = x; update-stmt; } | { update-stmt; v = x; } OpenMP 4.0: update-stmt: expression-stmt | x = x binop expr | x = expr binop x capture-stmt: v = update-stmt capture-block: { v = x; update-stmt; } | { update-stmt; v = x; } | { v = x; x = expr; } where x and v are lvalue expressions with scalar type. LOC is the location of the #pragma token. */ static void c_parser_omp_atomic (location_t loc, c_parser *parser) { tree lhs = NULL_TREE, rhs = NULL_TREE, v = NULL_TREE; tree lhs1 = NULL_TREE, rhs1 = NULL_TREE; tree stmt, orig_lhs, unfolded_lhs = NULL_TREE, unfolded_lhs1 = NULL_TREE; enum tree_code code = OMP_ATOMIC, opcode = NOP_EXPR; struct c_expr expr; location_t eloc; bool structured_block = false; bool swapped = false; bool seq_cst = false; bool non_lvalue_p; if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (!strcmp (p, "seq_cst")) { seq_cst = true; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_COMMA) && c_parser_peek_2nd_token (parser)->type == CPP_NAME) c_parser_consume_token (parser); } } if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (!strcmp (p, "read")) code = OMP_ATOMIC_READ; else if (!strcmp (p, "write")) code = NOP_EXPR; else if (!strcmp (p, "update")) code = OMP_ATOMIC; else if (!strcmp (p, "capture")) code = OMP_ATOMIC_CAPTURE_NEW; else p = NULL; if (p) c_parser_consume_token (parser); } if (!seq_cst) { if (c_parser_next_token_is (parser, CPP_COMMA) && c_parser_peek_2nd_token (parser)->type == CPP_NAME) c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (!strcmp (p, "seq_cst")) { seq_cst = true; c_parser_consume_token (parser); } } } c_parser_skip_to_pragma_eol (parser); switch (code) { case OMP_ATOMIC_READ: case NOP_EXPR: /* atomic write */ v = c_parser_cast_expression (parser, NULL).value; non_lvalue_p = !lvalue_p (v); v = c_fully_fold (v, false, NULL, true); if (v == error_mark_node) goto saw_error; if (non_lvalue_p) v = non_lvalue (v); loc = c_parser_peek_token (parser)->location; if (!c_parser_require (parser, CPP_EQ, "expected %<=%>")) goto saw_error; if (code == NOP_EXPR) { lhs = c_parser_expression (parser).value; lhs = c_fully_fold (lhs, false, NULL); if (lhs == error_mark_node) goto saw_error; } else { lhs = c_parser_cast_expression (parser, NULL).value; non_lvalue_p = !lvalue_p (lhs); lhs = c_fully_fold (lhs, false, NULL, true); if (lhs == error_mark_node) goto saw_error; if (non_lvalue_p) lhs = non_lvalue (lhs); } if (code == NOP_EXPR) { /* atomic write is represented by OMP_ATOMIC with NOP_EXPR opcode. */ code = OMP_ATOMIC; rhs = lhs; lhs = v; v = NULL_TREE; } goto done; case OMP_ATOMIC_CAPTURE_NEW: if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) { c_parser_consume_token (parser); structured_block = true; } else { v = c_parser_cast_expression (parser, NULL).value; non_lvalue_p = !lvalue_p (v); v = c_fully_fold (v, false, NULL, true); if (v == error_mark_node) goto saw_error; if (non_lvalue_p) v = non_lvalue (v); if (!c_parser_require (parser, CPP_EQ, "expected %<=%>")) goto saw_error; } break; default: break; } /* For structured_block case we don't know yet whether old or new x should be captured. */ restart: eloc = c_parser_peek_token (parser)->location; expr = c_parser_cast_expression (parser, NULL); lhs = expr.value; expr = default_function_array_conversion (eloc, expr); unfolded_lhs = expr.value; lhs = c_fully_fold (lhs, false, NULL, true); orig_lhs = lhs; switch (TREE_CODE (lhs)) { case ERROR_MARK: saw_error: c_parser_skip_to_end_of_block_or_statement (parser); if (structured_block) { if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) c_parser_consume_token (parser); else if (code == OMP_ATOMIC_CAPTURE_NEW) { c_parser_skip_to_end_of_block_or_statement (parser); if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) c_parser_consume_token (parser); } } return; case POSTINCREMENT_EXPR: if (code == OMP_ATOMIC_CAPTURE_NEW && !structured_block) code = OMP_ATOMIC_CAPTURE_OLD; /* FALLTHROUGH */ case PREINCREMENT_EXPR: lhs = TREE_OPERAND (lhs, 0); unfolded_lhs = NULL_TREE; opcode = PLUS_EXPR; rhs = integer_one_node; break; case POSTDECREMENT_EXPR: if (code == OMP_ATOMIC_CAPTURE_NEW && !structured_block) code = OMP_ATOMIC_CAPTURE_OLD; /* FALLTHROUGH */ case PREDECREMENT_EXPR: lhs = TREE_OPERAND (lhs, 0); unfolded_lhs = NULL_TREE; opcode = MINUS_EXPR; rhs = integer_one_node; break; case COMPOUND_EXPR: if (TREE_CODE (TREE_OPERAND (lhs, 0)) == SAVE_EXPR && TREE_CODE (TREE_OPERAND (lhs, 1)) == COMPOUND_EXPR && TREE_CODE (TREE_OPERAND (TREE_OPERAND (lhs, 1), 0)) == MODIFY_EXPR && TREE_OPERAND (TREE_OPERAND (lhs, 1), 1) == TREE_OPERAND (lhs, 0) && TREE_CODE (TREE_TYPE (TREE_OPERAND (TREE_OPERAND (TREE_OPERAND (lhs, 1), 0), 0))) == BOOLEAN_TYPE) /* Undo effects of boolean_increment for post {in,de}crement. */ lhs = TREE_OPERAND (TREE_OPERAND (lhs, 1), 0); /* FALLTHRU */ case MODIFY_EXPR: if (TREE_CODE (lhs) == MODIFY_EXPR && TREE_CODE (TREE_TYPE (TREE_OPERAND (lhs, 0))) == BOOLEAN_TYPE) { /* Undo effects of boolean_increment. */ if (integer_onep (TREE_OPERAND (lhs, 1))) { /* This is pre or post increment. */ rhs = TREE_OPERAND (lhs, 1); lhs = TREE_OPERAND (lhs, 0); unfolded_lhs = NULL_TREE; opcode = NOP_EXPR; if (code == OMP_ATOMIC_CAPTURE_NEW && !structured_block && TREE_CODE (orig_lhs) == COMPOUND_EXPR) code = OMP_ATOMIC_CAPTURE_OLD; break; } if (TREE_CODE (TREE_OPERAND (lhs, 1)) == TRUTH_NOT_EXPR && TREE_OPERAND (lhs, 0) == TREE_OPERAND (TREE_OPERAND (lhs, 1), 0)) { /* This is pre or post decrement. */ rhs = TREE_OPERAND (lhs, 1); lhs = TREE_OPERAND (lhs, 0); unfolded_lhs = NULL_TREE; opcode = NOP_EXPR; if (code == OMP_ATOMIC_CAPTURE_NEW && !structured_block && TREE_CODE (orig_lhs) == COMPOUND_EXPR) code = OMP_ATOMIC_CAPTURE_OLD; break; } } /* FALLTHRU */ default: if (!lvalue_p (unfolded_lhs)) lhs = non_lvalue (lhs); switch (c_parser_peek_token (parser)->type) { case CPP_MULT_EQ: opcode = MULT_EXPR; break; case CPP_DIV_EQ: opcode = TRUNC_DIV_EXPR; break; case CPP_PLUS_EQ: opcode = PLUS_EXPR; break; case CPP_MINUS_EQ: opcode = MINUS_EXPR; break; case CPP_LSHIFT_EQ: opcode = LSHIFT_EXPR; break; case CPP_RSHIFT_EQ: opcode = RSHIFT_EXPR; break; case CPP_AND_EQ: opcode = BIT_AND_EXPR; break; case CPP_OR_EQ: opcode = BIT_IOR_EXPR; break; case CPP_XOR_EQ: opcode = BIT_XOR_EXPR; break; case CPP_EQ: c_parser_consume_token (parser); eloc = c_parser_peek_token (parser)->location; expr = c_parser_expr_no_commas (parser, NULL, unfolded_lhs); rhs1 = expr.value; switch (TREE_CODE (rhs1)) { case MULT_EXPR: case TRUNC_DIV_EXPR: case RDIV_EXPR: case PLUS_EXPR: case MINUS_EXPR: case LSHIFT_EXPR: case RSHIFT_EXPR: case BIT_AND_EXPR: case BIT_IOR_EXPR: case BIT_XOR_EXPR: if (c_tree_equal (TREE_OPERAND (rhs1, 0), unfolded_lhs)) { opcode = TREE_CODE (rhs1); rhs = c_fully_fold (TREE_OPERAND (rhs1, 1), false, NULL, true); rhs1 = c_fully_fold (TREE_OPERAND (rhs1, 0), false, NULL, true); goto stmt_done; } if (c_tree_equal (TREE_OPERAND (rhs1, 1), unfolded_lhs)) { opcode = TREE_CODE (rhs1); rhs = c_fully_fold (TREE_OPERAND (rhs1, 0), false, NULL, true); rhs1 = c_fully_fold (TREE_OPERAND (rhs1, 1), false, NULL, true); swapped = !commutative_tree_code (opcode); goto stmt_done; } break; case ERROR_MARK: goto saw_error; default: break; } if (c_parser_peek_token (parser)->type == CPP_SEMICOLON) { if (structured_block && code == OMP_ATOMIC_CAPTURE_NEW) { code = OMP_ATOMIC_CAPTURE_OLD; v = lhs; lhs = NULL_TREE; expr = default_function_array_read_conversion (eloc, expr); unfolded_lhs1 = expr.value; lhs1 = c_fully_fold (unfolded_lhs1, false, NULL, true); rhs1 = NULL_TREE; c_parser_consume_token (parser); goto restart; } if (structured_block) { opcode = NOP_EXPR; expr = default_function_array_read_conversion (eloc, expr); rhs = c_fully_fold (expr.value, false, NULL, true); rhs1 = NULL_TREE; goto stmt_done; } } c_parser_error (parser, "invalid form of %<#pragma omp atomic%>"); goto saw_error; default: c_parser_error (parser, "invalid operator for %<#pragma omp atomic%>"); goto saw_error; } /* Arrange to pass the location of the assignment operator to c_finish_omp_atomic. */ loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); eloc = c_parser_peek_token (parser)->location; expr = c_parser_expression (parser); expr = default_function_array_read_conversion (eloc, expr); rhs = expr.value; rhs = c_fully_fold (rhs, false, NULL, true); break; } stmt_done: if (structured_block && code == OMP_ATOMIC_CAPTURE_NEW) { if (!c_parser_require (parser, CPP_SEMICOLON, "expected %<;%>")) goto saw_error; v = c_parser_cast_expression (parser, NULL).value; non_lvalue_p = !lvalue_p (v); v = c_fully_fold (v, false, NULL, true); if (v == error_mark_node) goto saw_error; if (non_lvalue_p) v = non_lvalue (v); if (!c_parser_require (parser, CPP_EQ, "expected %<=%>")) goto saw_error; eloc = c_parser_peek_token (parser)->location; expr = c_parser_cast_expression (parser, NULL); lhs1 = expr.value; expr = default_function_array_read_conversion (eloc, expr); unfolded_lhs1 = expr.value; lhs1 = c_fully_fold (lhs1, false, NULL, true); if (lhs1 == error_mark_node) goto saw_error; if (!lvalue_p (unfolded_lhs1)) lhs1 = non_lvalue (lhs1); } if (structured_block) { c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); c_parser_require (parser, CPP_CLOSE_BRACE, "expected %<}%>"); } done: if (unfolded_lhs && unfolded_lhs1 && !c_tree_equal (unfolded_lhs, unfolded_lhs1)) { error ("%<#pragma omp atomic capture%> uses two different " "expressions for memory"); stmt = error_mark_node; } else stmt = c_finish_omp_atomic (loc, code, opcode, lhs, rhs, v, lhs1, rhs1, swapped, seq_cst); if (stmt != error_mark_node) add_stmt (stmt); if (!structured_block) c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } /* OpenMP 2.5: # pragma omp barrier new-line */ static void c_parser_omp_barrier (c_parser *parser) { location_t loc = c_parser_peek_token (parser)->location; c_parser_consume_pragma (parser); c_parser_skip_to_pragma_eol (parser); c_finish_omp_barrier (loc); } /* OpenMP 2.5: # pragma omp critical [(name)] new-line structured-block OpenMP 4.5: # pragma omp critical [(name) [hint(expression)]] new-line LOC is the location of the #pragma itself. */ #define OMP_CRITICAL_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_HINT) ) static tree c_parser_omp_critical (location_t loc, c_parser *parser, bool *if_p) { tree stmt, name = NULL_TREE, clauses = NULL_TREE; if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_NAME)) { name = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); c_parser_require (parser, CPP_CLOSE_PAREN, "expected %<)%>"); } else c_parser_error (parser, "expected identifier"); clauses = c_parser_omp_all_clauses (parser, OMP_CRITICAL_CLAUSE_MASK, "#pragma omp critical"); } else { if (c_parser_next_token_is_not (parser, CPP_PRAGMA_EOL)) c_parser_error (parser, "expected %<(%> or end of line"); c_parser_skip_to_pragma_eol (parser); } stmt = c_parser_omp_structured_block (parser, if_p); return c_finish_omp_critical (loc, stmt, name, clauses); } /* OpenMP 2.5: # pragma omp flush flush-vars[opt] new-line flush-vars: ( variable-list ) */ static void c_parser_omp_flush (c_parser *parser) { location_t loc = c_parser_peek_token (parser)->location; c_parser_consume_pragma (parser); if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) c_parser_omp_var_list_parens (parser, OMP_CLAUSE_ERROR, NULL); else if (c_parser_next_token_is_not (parser, CPP_PRAGMA_EOL)) c_parser_error (parser, "expected %<(%> or end of line"); c_parser_skip_to_pragma_eol (parser); c_finish_omp_flush (loc); } /* Parse the restricted form of loop statements allowed by OpenACC and OpenMP. The real trick here is to determine the loop control variable early so that we can push a new decl if necessary to make it private. LOC is the location of the "acc" or "omp" in "#pragma acc" or "#pragma omp", respectively. */ static tree c_parser_omp_for_loop (location_t loc, c_parser *parser, enum tree_code code, tree clauses, tree *cclauses, bool *if_p) { tree decl, cond, incr, save_break, save_cont, body, init, stmt, cl; tree declv, condv, incrv, initv, ret = NULL_TREE; tree pre_body = NULL_TREE, this_pre_body; tree ordered_cl = NULL_TREE; bool fail = false, open_brace_parsed = false; int i, collapse = 1, ordered = 0, count, nbraces = 0; location_t for_loc; bool tiling = false; vec<tree, va_gc> *for_block = make_tree_vector (); for (cl = clauses; cl; cl = OMP_CLAUSE_CHAIN (cl)) if (OMP_CLAUSE_CODE (cl) == OMP_CLAUSE_COLLAPSE) collapse = tree_to_shwi (OMP_CLAUSE_COLLAPSE_EXPR (cl)); else if (OMP_CLAUSE_CODE (cl) == OMP_CLAUSE_TILE) { tiling = true; collapse = list_length (OMP_CLAUSE_TILE_LIST (cl)); } else if (OMP_CLAUSE_CODE (cl) == OMP_CLAUSE_ORDERED && OMP_CLAUSE_ORDERED_EXPR (cl)) { ordered_cl = cl; ordered = tree_to_shwi (OMP_CLAUSE_ORDERED_EXPR (cl)); } if (ordered && ordered < collapse) { error_at (OMP_CLAUSE_LOCATION (ordered_cl), "%<ordered%> clause parameter is less than %<collapse%>"); OMP_CLAUSE_ORDERED_EXPR (ordered_cl) = build_int_cst (NULL_TREE, collapse); ordered = collapse; } if (ordered) { for (tree *pc = &clauses; *pc; ) if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LINEAR) { error_at (OMP_CLAUSE_LOCATION (*pc), "%<linear%> clause may not be specified together " "with %<ordered%> clause with a parameter"); *pc = OMP_CLAUSE_CHAIN (*pc); } else pc = &OMP_CLAUSE_CHAIN (*pc); } gcc_assert (tiling || (collapse >= 1 && ordered >= 0)); count = ordered ? ordered : collapse; declv = make_tree_vec (count); initv = make_tree_vec (count); condv = make_tree_vec (count); incrv = make_tree_vec (count); if (!c_parser_next_token_is_keyword (parser, RID_FOR)) { c_parser_error (parser, "for statement expected"); return NULL; } for_loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); for (i = 0; i < count; i++) { int bracecount = 0; matching_parens parens; if (!parens.require_open (parser)) goto pop_scopes; /* Parse the initialization declaration or expression. */ if (c_parser_next_tokens_start_declaration (parser)) { if (i > 0) vec_safe_push (for_block, c_begin_compound_stmt (true)); this_pre_body = push_stmt_list (); c_parser_declaration_or_fndef (parser, true, true, true, true, true, NULL, vNULL); if (this_pre_body) { this_pre_body = pop_stmt_list (this_pre_body); if (pre_body) { tree t = pre_body; pre_body = push_stmt_list (); add_stmt (t); add_stmt (this_pre_body); pre_body = pop_stmt_list (pre_body); } else pre_body = this_pre_body; } decl = check_for_loop_decls (for_loc, flag_isoc99); if (decl == NULL) goto error_init; if (DECL_INITIAL (decl) == error_mark_node) decl = error_mark_node; init = decl; } else if (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_2nd_token (parser)->type == CPP_EQ) { struct c_expr decl_exp; struct c_expr init_exp; location_t init_loc; decl_exp = c_parser_postfix_expression (parser); decl = decl_exp.value; c_parser_require (parser, CPP_EQ, "expected %<=%>"); init_loc = c_parser_peek_token (parser)->location; init_exp = c_parser_expr_no_commas (parser, NULL); init_exp = default_function_array_read_conversion (init_loc, init_exp); init = build_modify_expr (init_loc, decl, decl_exp.original_type, NOP_EXPR, init_loc, init_exp.value, init_exp.original_type); init = c_process_expr_stmt (init_loc, init); c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } else { error_init: c_parser_error (parser, "expected iteration declaration or initialization"); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); fail = true; goto parse_next; } /* Parse the loop condition. */ cond = NULL_TREE; if (c_parser_next_token_is_not (parser, CPP_SEMICOLON)) { location_t cond_loc = c_parser_peek_token (parser)->location; struct c_expr cond_expr = c_parser_binary_expression (parser, NULL, NULL_TREE); cond = cond_expr.value; cond = c_objc_common_truthvalue_conversion (cond_loc, cond); if (COMPARISON_CLASS_P (cond)) { tree op0 = TREE_OPERAND (cond, 0), op1 = TREE_OPERAND (cond, 1); op0 = c_fully_fold (op0, false, NULL); op1 = c_fully_fold (op1, false, NULL); TREE_OPERAND (cond, 0) = op0; TREE_OPERAND (cond, 1) = op1; } switch (cond_expr.original_code) { case GT_EXPR: case GE_EXPR: case LT_EXPR: case LE_EXPR: break; default: /* Can't be cond = error_mark_node, because we want to preserve the location until c_finish_omp_for. */ cond = build1 (NOP_EXPR, boolean_type_node, error_mark_node); break; } protected_set_expr_location (cond, cond_loc); } c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); /* Parse the increment expression. */ incr = NULL_TREE; if (c_parser_next_token_is_not (parser, CPP_CLOSE_PAREN)) { location_t incr_loc = c_parser_peek_token (parser)->location; incr = c_process_expr_stmt (incr_loc, c_parser_expression (parser).value); } parens.skip_until_found_close (parser); if (decl == NULL || decl == error_mark_node || init == error_mark_node) fail = true; else { TREE_VEC_ELT (declv, i) = decl; TREE_VEC_ELT (initv, i) = init; TREE_VEC_ELT (condv, i) = cond; TREE_VEC_ELT (incrv, i) = incr; } parse_next: if (i == count - 1) break; /* FIXME: OpenMP 3.0 draft isn't very clear on what exactly is allowed in between the collapsed for loops to be still considered perfectly nested. Hopefully the final version clarifies this. For now handle (multiple) {'s and empty statements. */ do { if (c_parser_next_token_is_keyword (parser, RID_FOR)) { c_parser_consume_token (parser); break; } else if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) { c_parser_consume_token (parser); bracecount++; } else if (bracecount && c_parser_next_token_is (parser, CPP_SEMICOLON)) c_parser_consume_token (parser); else { c_parser_error (parser, "not enough perfectly nested loops"); if (bracecount) { open_brace_parsed = true; bracecount--; } fail = true; count = 0; break; } } while (1); nbraces += bracecount; } if (nbraces) if_p = NULL; save_break = c_break_label; c_break_label = size_one_node; save_cont = c_cont_label; c_cont_label = NULL_TREE; body = push_stmt_list (); if (open_brace_parsed) { location_t here = c_parser_peek_token (parser)->location; stmt = c_begin_compound_stmt (true); c_parser_compound_statement_nostart (parser); add_stmt (c_end_compound_stmt (here, stmt, true)); } else add_stmt (c_parser_c99_block_statement (parser, if_p)); if (c_cont_label) { tree t = build1 (LABEL_EXPR, void_type_node, c_cont_label); SET_EXPR_LOCATION (t, loc); add_stmt (t); } body = pop_stmt_list (body); c_break_label = save_break; c_cont_label = save_cont; while (nbraces) { if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { c_parser_consume_token (parser); nbraces--; } else if (c_parser_next_token_is (parser, CPP_SEMICOLON)) c_parser_consume_token (parser); else { c_parser_error (parser, "collapsed loops not perfectly nested"); while (nbraces) { location_t here = c_parser_peek_token (parser)->location; stmt = c_begin_compound_stmt (true); add_stmt (body); c_parser_compound_statement_nostart (parser); body = c_end_compound_stmt (here, stmt, true); nbraces--; } goto pop_scopes; } } /* Only bother calling c_finish_omp_for if we haven't already generated an error from the initialization parsing. */ if (!fail) { stmt = c_finish_omp_for (loc, code, declv, NULL, initv, condv, incrv, body, pre_body); /* Check for iterators appearing in lb, b or incr expressions. */ if (stmt && !c_omp_check_loop_iv (stmt, declv, NULL)) stmt = NULL_TREE; if (stmt) { add_stmt (stmt); if (cclauses != NULL && cclauses[C_OMP_CLAUSE_SPLIT_PARALLEL] != NULL) { tree *c; for (c = &cclauses[C_OMP_CLAUSE_SPLIT_PARALLEL]; *c ; ) if (OMP_CLAUSE_CODE (*c) != OMP_CLAUSE_FIRSTPRIVATE && OMP_CLAUSE_CODE (*c) != OMP_CLAUSE_LASTPRIVATE) c = &OMP_CLAUSE_CHAIN (*c); else { for (i = 0; i < count; i++) if (TREE_VEC_ELT (declv, i) == OMP_CLAUSE_DECL (*c)) break; if (i == count) c = &OMP_CLAUSE_CHAIN (*c); else if (OMP_CLAUSE_CODE (*c) == OMP_CLAUSE_FIRSTPRIVATE) { error_at (loc, "iteration variable %qD should not be firstprivate", OMP_CLAUSE_DECL (*c)); *c = OMP_CLAUSE_CHAIN (*c); } else { /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES. */ tree l = *c; *c = OMP_CLAUSE_CHAIN (*c); if (code == OMP_SIMD) { OMP_CLAUSE_CHAIN (l) = cclauses[C_OMP_CLAUSE_SPLIT_FOR]; cclauses[C_OMP_CLAUSE_SPLIT_FOR] = l; } else { OMP_CLAUSE_CHAIN (l) = clauses; clauses = l; } } } } OMP_FOR_CLAUSES (stmt) = clauses; } ret = stmt; } pop_scopes: while (!for_block->is_empty ()) { /* FIXME diagnostics: LOC below should be the actual location of this particular for block. We need to build a list of locations to go along with FOR_BLOCK. */ stmt = c_end_compound_stmt (loc, for_block->pop (), true); add_stmt (stmt); } release_tree_vector (for_block); return ret; } /* Helper function for OpenMP parsing, split clauses and call finish_omp_clauses on each of the set of clauses afterwards. */ static void omp_split_clauses (location_t loc, enum tree_code code, omp_clause_mask mask, tree clauses, tree *cclauses) { int i; c_omp_split_clauses (loc, code, mask, clauses, cclauses); for (i = 0; i < C_OMP_CLAUSE_SPLIT_COUNT; i++) if (cclauses[i]) cclauses[i] = c_finish_omp_clauses (cclauses[i], C_ORT_OMP); } /* OpenMP 4.0: #pragma omp simd simd-clause[optseq] new-line for-loop LOC is the location of the #pragma token. */ #define OMP_SIMD_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_SAFELEN) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_SIMDLEN) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_LINEAR) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_ALIGNED) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_PRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_LASTPRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_REDUCTION) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_COLLAPSE)) static tree c_parser_omp_simd (location_t loc, c_parser *parser, char *p_name, omp_clause_mask mask, tree *cclauses, bool *if_p) { tree block, clauses, ret; strcat (p_name, " simd"); mask |= OMP_SIMD_CLAUSE_MASK; clauses = c_parser_omp_all_clauses (parser, mask, p_name, cclauses == NULL); if (cclauses) { omp_split_clauses (loc, OMP_SIMD, mask, clauses, cclauses); clauses = cclauses[C_OMP_CLAUSE_SPLIT_SIMD]; tree c = omp_find_clause (cclauses[C_OMP_CLAUSE_SPLIT_FOR], OMP_CLAUSE_ORDERED); if (c && OMP_CLAUSE_ORDERED_EXPR (c)) { error_at (OMP_CLAUSE_LOCATION (c), "%<ordered%> clause with parameter may not be specified " "on %qs construct", p_name); OMP_CLAUSE_ORDERED_EXPR (c) = NULL_TREE; } } block = c_begin_compound_stmt (true); ret = c_parser_omp_for_loop (loc, parser, OMP_SIMD, clauses, cclauses, if_p); block = c_end_compound_stmt (loc, block, true); add_stmt (block); return ret; } /* OpenMP 2.5: #pragma omp for for-clause[optseq] new-line for-loop OpenMP 4.0: #pragma omp for simd for-simd-clause[optseq] new-line for-loop LOC is the location of the #pragma token. */ #define OMP_FOR_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_PRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_LASTPRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_LINEAR) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_REDUCTION) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_ORDERED) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_SCHEDULE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_COLLAPSE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NOWAIT)) static tree c_parser_omp_for (location_t loc, c_parser *parser, char *p_name, omp_clause_mask mask, tree *cclauses, bool *if_p) { tree block, clauses, ret; strcat (p_name, " for"); mask |= OMP_FOR_CLAUSE_MASK; /* parallel for{, simd} disallows nowait clause, but for target {teams distribute ,}parallel for{, simd} it should be accepted. */ if (cclauses && (mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_MAP)) == 0) mask &= ~(OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NOWAIT); /* Composite distribute parallel for{, simd} disallows ordered clause. */ if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DIST_SCHEDULE)) != 0) mask &= ~(OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_ORDERED); if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp (p, "simd") == 0) { tree cclauses_buf[C_OMP_CLAUSE_SPLIT_COUNT]; if (cclauses == NULL) cclauses = cclauses_buf; c_parser_consume_token (parser); if (!flag_openmp) /* flag_openmp_simd */ return c_parser_omp_simd (loc, parser, p_name, mask, cclauses, if_p); block = c_begin_compound_stmt (true); ret = c_parser_omp_simd (loc, parser, p_name, mask, cclauses, if_p); block = c_end_compound_stmt (loc, block, true); if (ret == NULL_TREE) return ret; ret = make_node (OMP_FOR); TREE_TYPE (ret) = void_type_node; OMP_FOR_BODY (ret) = block; OMP_FOR_CLAUSES (ret) = cclauses[C_OMP_CLAUSE_SPLIT_FOR]; SET_EXPR_LOCATION (ret, loc); add_stmt (ret); return ret; } } if (!flag_openmp) /* flag_openmp_simd */ { c_parser_skip_to_pragma_eol (parser, false); return NULL_TREE; } /* Composite distribute parallel for disallows linear clause. */ if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DIST_SCHEDULE)) != 0) mask &= ~(OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_LINEAR); clauses = c_parser_omp_all_clauses (parser, mask, p_name, cclauses == NULL); if (cclauses) { omp_split_clauses (loc, OMP_FOR, mask, clauses, cclauses); clauses = cclauses[C_OMP_CLAUSE_SPLIT_FOR]; } block = c_begin_compound_stmt (true); ret = c_parser_omp_for_loop (loc, parser, OMP_FOR, clauses, cclauses, if_p); block = c_end_compound_stmt (loc, block, true); add_stmt (block); return ret; } /* OpenMP 2.5: # pragma omp master new-line structured-block LOC is the location of the #pragma token. */ static tree c_parser_omp_master (location_t loc, c_parser *parser, bool *if_p) { c_parser_skip_to_pragma_eol (parser); return c_finish_omp_master (loc, c_parser_omp_structured_block (parser, if_p)); } /* OpenMP 2.5: # pragma omp ordered new-line structured-block OpenMP 4.5: # pragma omp ordered ordered-clauses new-line structured-block # pragma omp ordered depend-clauses new-line */ #define OMP_ORDERED_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_THREADS) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_SIMD)) #define OMP_ORDERED_DEPEND_CLAUSE_MASK \ (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DEPEND) static bool c_parser_omp_ordered (c_parser *parser, enum pragma_context context, bool *if_p) { location_t loc = c_parser_peek_token (parser)->location; c_parser_consume_pragma (parser); if (context != pragma_stmt && context != pragma_compound) { c_parser_error (parser, "expected declaration specifiers"); c_parser_skip_to_pragma_eol (parser, false); return false; } if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (!strcmp ("depend", p)) { if (!flag_openmp) /* flag_openmp_simd */ { c_parser_skip_to_pragma_eol (parser, false); return false; } if (context == pragma_stmt) { error_at (loc, "%<#pragma omp ordered%> with %<depend%> clause may " "only be used in compound statements"); c_parser_skip_to_pragma_eol (parser, false); return false; } tree clauses = c_parser_omp_all_clauses (parser, OMP_ORDERED_DEPEND_CLAUSE_MASK, "#pragma omp ordered"); c_finish_omp_ordered (loc, clauses, NULL_TREE); return false; } } tree clauses = c_parser_omp_all_clauses (parser, OMP_ORDERED_CLAUSE_MASK, "#pragma omp ordered"); if (!flag_openmp /* flag_openmp_simd */ && omp_find_clause (clauses, OMP_CLAUSE_SIMD) == NULL_TREE) return false; c_finish_omp_ordered (loc, clauses, c_parser_omp_structured_block (parser, if_p)); return true; } /* OpenMP 2.5: section-scope: { section-sequence } section-sequence: section-directive[opt] structured-block section-sequence section-directive structured-block SECTIONS_LOC is the location of the #pragma omp sections. */ static tree c_parser_omp_sections_scope (location_t sections_loc, c_parser *parser) { tree stmt, substmt; bool error_suppress = false; location_t loc; loc = c_parser_peek_token (parser)->location; if (!c_parser_require (parser, CPP_OPEN_BRACE, "expected %<{%>")) { /* Avoid skipping until the end of the block. */ parser->error = false; return NULL_TREE; } stmt = push_stmt_list (); if (c_parser_peek_token (parser)->pragma_kind != PRAGMA_OMP_SECTION) { substmt = c_parser_omp_structured_block (parser, NULL); substmt = build1 (OMP_SECTION, void_type_node, substmt); SET_EXPR_LOCATION (substmt, loc); add_stmt (substmt); } while (1) { if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) break; if (c_parser_next_token_is (parser, CPP_EOF)) break; loc = c_parser_peek_token (parser)->location; if (c_parser_peek_token (parser)->pragma_kind == PRAGMA_OMP_SECTION) { c_parser_consume_pragma (parser); c_parser_skip_to_pragma_eol (parser); error_suppress = false; } else if (!error_suppress) { error_at (loc, "expected %<#pragma omp section%> or %<}%>"); error_suppress = true; } substmt = c_parser_omp_structured_block (parser, NULL); substmt = build1 (OMP_SECTION, void_type_node, substmt); SET_EXPR_LOCATION (substmt, loc); add_stmt (substmt); } c_parser_skip_until_found (parser, CPP_CLOSE_BRACE, "expected %<#pragma omp section%> or %<}%>"); substmt = pop_stmt_list (stmt); stmt = make_node (OMP_SECTIONS); SET_EXPR_LOCATION (stmt, sections_loc); TREE_TYPE (stmt) = void_type_node; OMP_SECTIONS_BODY (stmt) = substmt; return add_stmt (stmt); } /* OpenMP 2.5: # pragma omp sections sections-clause[optseq] newline sections-scope LOC is the location of the #pragma token. */ #define OMP_SECTIONS_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_PRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_LASTPRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_REDUCTION) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NOWAIT)) static tree c_parser_omp_sections (location_t loc, c_parser *parser, char *p_name, omp_clause_mask mask, tree *cclauses) { tree block, clauses, ret; strcat (p_name, " sections"); mask |= OMP_SECTIONS_CLAUSE_MASK; if (cclauses) mask &= ~(OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NOWAIT); clauses = c_parser_omp_all_clauses (parser, mask, p_name, cclauses == NULL); if (cclauses) { omp_split_clauses (loc, OMP_SECTIONS, mask, clauses, cclauses); clauses = cclauses[C_OMP_CLAUSE_SPLIT_SECTIONS]; } block = c_begin_compound_stmt (true); ret = c_parser_omp_sections_scope (loc, parser); if (ret) OMP_SECTIONS_CLAUSES (ret) = clauses; block = c_end_compound_stmt (loc, block, true); add_stmt (block); return ret; } /* OpenMP 2.5: # pragma omp parallel parallel-clause[optseq] new-line structured-block # pragma omp parallel for parallel-for-clause[optseq] new-line structured-block # pragma omp parallel sections parallel-sections-clause[optseq] new-line structured-block OpenMP 4.0: # pragma omp parallel for simd parallel-for-simd-clause[optseq] new-line structured-block LOC is the location of the #pragma token. */ #define OMP_PARALLEL_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_IF) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_PRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DEFAULT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_SHARED) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_COPYIN) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_REDUCTION) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NUM_THREADS) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_PROC_BIND)) static tree c_parser_omp_parallel (location_t loc, c_parser *parser, char *p_name, omp_clause_mask mask, tree *cclauses, bool *if_p) { tree stmt, clauses, block; strcat (p_name, " parallel"); mask |= OMP_PARALLEL_CLAUSE_MASK; /* #pragma omp target parallel{, for, for simd} disallow copyin clause. */ if ((mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_MAP)) != 0 && (mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DIST_SCHEDULE)) == 0) mask &= ~(OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_COPYIN); if (c_parser_next_token_is_keyword (parser, RID_FOR)) { tree cclauses_buf[C_OMP_CLAUSE_SPLIT_COUNT]; if (cclauses == NULL) cclauses = cclauses_buf; c_parser_consume_token (parser); if (!flag_openmp) /* flag_openmp_simd */ return c_parser_omp_for (loc, parser, p_name, mask, cclauses, if_p); block = c_begin_omp_parallel (); tree ret = c_parser_omp_for (loc, parser, p_name, mask, cclauses, if_p); stmt = c_finish_omp_parallel (loc, cclauses[C_OMP_CLAUSE_SPLIT_PARALLEL], block); if (ret == NULL_TREE) return ret; OMP_PARALLEL_COMBINED (stmt) = 1; return stmt; } /* When combined with distribute, parallel has to be followed by for. #pragma omp target parallel is allowed though. */ else if (cclauses && (mask & (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DIST_SCHEDULE)) != 0) { error_at (loc, "expected %<for%> after %qs", p_name); c_parser_skip_to_pragma_eol (parser); return NULL_TREE; } else if (!flag_openmp) /* flag_openmp_simd */ { c_parser_skip_to_pragma_eol (parser, false); return NULL_TREE; } else if (cclauses == NULL && c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp (p, "sections") == 0) { tree cclauses_buf[C_OMP_CLAUSE_SPLIT_COUNT]; if (cclauses == NULL) cclauses = cclauses_buf; c_parser_consume_token (parser); block = c_begin_omp_parallel (); c_parser_omp_sections (loc, parser, p_name, mask, cclauses); stmt = c_finish_omp_parallel (loc, cclauses[C_OMP_CLAUSE_SPLIT_PARALLEL], block); OMP_PARALLEL_COMBINED (stmt) = 1; return stmt; } } clauses = c_parser_omp_all_clauses (parser, mask, p_name, cclauses == NULL); if (cclauses) { omp_split_clauses (loc, OMP_PARALLEL, mask, clauses, cclauses); clauses = cclauses[C_OMP_CLAUSE_SPLIT_PARALLEL]; } block = c_begin_omp_parallel (); c_parser_statement (parser, if_p); stmt = c_finish_omp_parallel (loc, clauses, block); return stmt; } /* OpenMP 2.5: # pragma omp single single-clause[optseq] new-line structured-block LOC is the location of the #pragma. */ #define OMP_SINGLE_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_PRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_COPYPRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NOWAIT)) static tree c_parser_omp_single (location_t loc, c_parser *parser, bool *if_p) { tree stmt = make_node (OMP_SINGLE); SET_EXPR_LOCATION (stmt, loc); TREE_TYPE (stmt) = void_type_node; OMP_SINGLE_CLAUSES (stmt) = c_parser_omp_all_clauses (parser, OMP_SINGLE_CLAUSE_MASK, "#pragma omp single"); OMP_SINGLE_BODY (stmt) = c_parser_omp_structured_block (parser, if_p); return add_stmt (stmt); } /* OpenMP 3.0: # pragma omp task task-clause[optseq] new-line LOC is the location of the #pragma. */ #define OMP_TASK_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_IF) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_UNTIED) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DEFAULT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_PRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_SHARED) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_FINAL) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_MERGEABLE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DEPEND) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_PRIORITY)) static tree c_parser_omp_task (location_t loc, c_parser *parser, bool *if_p) { tree clauses, block; clauses = c_parser_omp_all_clauses (parser, OMP_TASK_CLAUSE_MASK, "#pragma omp task"); block = c_begin_omp_task (); c_parser_statement (parser, if_p); return c_finish_omp_task (loc, clauses, block); } /* OpenMP 3.0: # pragma omp taskwait new-line */ static void c_parser_omp_taskwait (c_parser *parser) { location_t loc = c_parser_peek_token (parser)->location; c_parser_consume_pragma (parser); c_parser_skip_to_pragma_eol (parser); c_finish_omp_taskwait (loc); } /* OpenMP 3.1: # pragma omp taskyield new-line */ static void c_parser_omp_taskyield (c_parser *parser) { location_t loc = c_parser_peek_token (parser)->location; c_parser_consume_pragma (parser); c_parser_skip_to_pragma_eol (parser); c_finish_omp_taskyield (loc); } /* OpenMP 4.0: # pragma omp taskgroup new-line */ static tree c_parser_omp_taskgroup (c_parser *parser, bool *if_p) { location_t loc = c_parser_peek_token (parser)->location; c_parser_skip_to_pragma_eol (parser); return c_finish_omp_taskgroup (loc, c_parser_omp_structured_block (parser, if_p)); } /* OpenMP 4.0: # pragma omp cancel cancel-clause[optseq] new-line LOC is the location of the #pragma. */ #define OMP_CANCEL_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_PARALLEL) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_FOR) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_SECTIONS) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_TASKGROUP) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_IF)) static void c_parser_omp_cancel (c_parser *parser) { location_t loc = c_parser_peek_token (parser)->location; c_parser_consume_pragma (parser); tree clauses = c_parser_omp_all_clauses (parser, OMP_CANCEL_CLAUSE_MASK, "#pragma omp cancel"); c_finish_omp_cancel (loc, clauses); } /* OpenMP 4.0: # pragma omp cancellation point cancelpt-clause[optseq] new-line LOC is the location of the #pragma. */ #define OMP_CANCELLATION_POINT_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_PARALLEL) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_FOR) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_SECTIONS) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_TASKGROUP)) static void c_parser_omp_cancellation_point (c_parser *parser, enum pragma_context context) { location_t loc = c_parser_peek_token (parser)->location; tree clauses; bool point_seen = false; c_parser_consume_pragma (parser); if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp (p, "point") == 0) { c_parser_consume_token (parser); point_seen = true; } } if (!point_seen) { c_parser_error (parser, "expected %<point%>"); c_parser_skip_to_pragma_eol (parser); return; } if (context != pragma_compound) { if (context == pragma_stmt) error_at (loc, "%<#pragma %s%> may only be used in compound statements", "omp cancellation point"); else c_parser_error (parser, "expected declaration specifiers"); c_parser_skip_to_pragma_eol (parser, false); return; } clauses = c_parser_omp_all_clauses (parser, OMP_CANCELLATION_POINT_CLAUSE_MASK, "#pragma omp cancellation point"); c_finish_omp_cancellation_point (loc, clauses); } /* OpenMP 4.0: #pragma omp distribute distribute-clause[optseq] new-line for-loop */ #define OMP_DISTRIBUTE_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_PRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_LASTPRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DIST_SCHEDULE)\ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_COLLAPSE)) static tree c_parser_omp_distribute (location_t loc, c_parser *parser, char *p_name, omp_clause_mask mask, tree *cclauses, bool *if_p) { tree clauses, block, ret; strcat (p_name, " distribute"); mask |= OMP_DISTRIBUTE_CLAUSE_MASK; if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); bool simd = false; bool parallel = false; if (strcmp (p, "simd") == 0) simd = true; else parallel = strcmp (p, "parallel") == 0; if (parallel || simd) { tree cclauses_buf[C_OMP_CLAUSE_SPLIT_COUNT]; if (cclauses == NULL) cclauses = cclauses_buf; c_parser_consume_token (parser); if (!flag_openmp) /* flag_openmp_simd */ { if (simd) return c_parser_omp_simd (loc, parser, p_name, mask, cclauses, if_p); else return c_parser_omp_parallel (loc, parser, p_name, mask, cclauses, if_p); } block = c_begin_compound_stmt (true); if (simd) ret = c_parser_omp_simd (loc, parser, p_name, mask, cclauses, if_p); else ret = c_parser_omp_parallel (loc, parser, p_name, mask, cclauses, if_p); block = c_end_compound_stmt (loc, block, true); if (ret == NULL) return ret; ret = make_node (OMP_DISTRIBUTE); TREE_TYPE (ret) = void_type_node; OMP_FOR_BODY (ret) = block; OMP_FOR_CLAUSES (ret) = cclauses[C_OMP_CLAUSE_SPLIT_DISTRIBUTE]; SET_EXPR_LOCATION (ret, loc); add_stmt (ret); return ret; } } if (!flag_openmp) /* flag_openmp_simd */ { c_parser_skip_to_pragma_eol (parser, false); return NULL_TREE; } clauses = c_parser_omp_all_clauses (parser, mask, p_name, cclauses == NULL); if (cclauses) { omp_split_clauses (loc, OMP_DISTRIBUTE, mask, clauses, cclauses); clauses = cclauses[C_OMP_CLAUSE_SPLIT_DISTRIBUTE]; } block = c_begin_compound_stmt (true); ret = c_parser_omp_for_loop (loc, parser, OMP_DISTRIBUTE, clauses, NULL, if_p); block = c_end_compound_stmt (loc, block, true); add_stmt (block); return ret; } /* OpenMP 4.0: # pragma omp teams teams-clause[optseq] new-line structured-block */ #define OMP_TEAMS_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_PRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_SHARED) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_REDUCTION) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NUM_TEAMS) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_THREAD_LIMIT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DEFAULT)) static tree c_parser_omp_teams (location_t loc, c_parser *parser, char *p_name, omp_clause_mask mask, tree *cclauses, bool *if_p) { tree clauses, block, ret; strcat (p_name, " teams"); mask |= OMP_TEAMS_CLAUSE_MASK; if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp (p, "distribute") == 0) { tree cclauses_buf[C_OMP_CLAUSE_SPLIT_COUNT]; if (cclauses == NULL) cclauses = cclauses_buf; c_parser_consume_token (parser); if (!flag_openmp) /* flag_openmp_simd */ return c_parser_omp_distribute (loc, parser, p_name, mask, cclauses, if_p); block = c_begin_compound_stmt (true); ret = c_parser_omp_distribute (loc, parser, p_name, mask, cclauses, if_p); block = c_end_compound_stmt (loc, block, true); if (ret == NULL) return ret; clauses = cclauses[C_OMP_CLAUSE_SPLIT_TEAMS]; ret = make_node (OMP_TEAMS); TREE_TYPE (ret) = void_type_node; OMP_TEAMS_CLAUSES (ret) = clauses; OMP_TEAMS_BODY (ret) = block; OMP_TEAMS_COMBINED (ret) = 1; return add_stmt (ret); } } if (!flag_openmp) /* flag_openmp_simd */ { c_parser_skip_to_pragma_eol (parser, false); return NULL_TREE; } clauses = c_parser_omp_all_clauses (parser, mask, p_name, cclauses == NULL); if (cclauses) { omp_split_clauses (loc, OMP_TEAMS, mask, clauses, cclauses); clauses = cclauses[C_OMP_CLAUSE_SPLIT_TEAMS]; } tree stmt = make_node (OMP_TEAMS); TREE_TYPE (stmt) = void_type_node; OMP_TEAMS_CLAUSES (stmt) = clauses; OMP_TEAMS_BODY (stmt) = c_parser_omp_structured_block (parser, if_p); return add_stmt (stmt); } /* OpenMP 4.0: # pragma omp target data target-data-clause[optseq] new-line structured-block */ #define OMP_TARGET_DATA_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DEVICE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_MAP) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_IF) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_USE_DEVICE_PTR)) static tree c_parser_omp_target_data (location_t loc, c_parser *parser, bool *if_p) { tree clauses = c_parser_omp_all_clauses (parser, OMP_TARGET_DATA_CLAUSE_MASK, "#pragma omp target data"); int map_seen = 0; for (tree *pc = &clauses; *pc;) { if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_MAP) switch (OMP_CLAUSE_MAP_KIND (*pc)) { case GOMP_MAP_TO: case GOMP_MAP_ALWAYS_TO: case GOMP_MAP_FROM: case GOMP_MAP_ALWAYS_FROM: case GOMP_MAP_TOFROM: case GOMP_MAP_ALWAYS_TOFROM: case GOMP_MAP_ALLOC: map_seen = 3; break; case GOMP_MAP_FIRSTPRIVATE_POINTER: case GOMP_MAP_ALWAYS_POINTER: break; default: map_seen |= 1; error_at (OMP_CLAUSE_LOCATION (*pc), "%<#pragma omp target data%> with map-type other " "than %<to%>, %<from%>, %<tofrom%> or %<alloc%> " "on %<map%> clause"); *pc = OMP_CLAUSE_CHAIN (*pc); continue; } pc = &OMP_CLAUSE_CHAIN (*pc); } if (map_seen != 3) { if (map_seen == 0) error_at (loc, "%<#pragma omp target data%> must contain at least " "one %<map%> clause"); return NULL_TREE; } tree stmt = make_node (OMP_TARGET_DATA); TREE_TYPE (stmt) = void_type_node; OMP_TARGET_DATA_CLAUSES (stmt) = clauses; keep_next_level (); tree block = c_begin_compound_stmt (true); add_stmt (c_parser_omp_structured_block (parser, if_p)); OMP_TARGET_DATA_BODY (stmt) = c_end_compound_stmt (loc, block, true); SET_EXPR_LOCATION (stmt, loc); return add_stmt (stmt); } /* OpenMP 4.0: # pragma omp target update target-update-clause[optseq] new-line */ #define OMP_TARGET_UPDATE_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_FROM) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_TO) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DEVICE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_IF) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DEPEND) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NOWAIT)) static bool c_parser_omp_target_update (location_t loc, c_parser *parser, enum pragma_context context) { if (context == pragma_stmt) { error_at (loc, "%<#pragma %s%> may only be used in compound statements", "omp target update"); c_parser_skip_to_pragma_eol (parser, false); return false; } tree clauses = c_parser_omp_all_clauses (parser, OMP_TARGET_UPDATE_CLAUSE_MASK, "#pragma omp target update"); if (omp_find_clause (clauses, OMP_CLAUSE_TO) == NULL_TREE && omp_find_clause (clauses, OMP_CLAUSE_FROM) == NULL_TREE) { error_at (loc, "%<#pragma omp target update%> must contain at least one " "%<from%> or %<to%> clauses"); return false; } tree stmt = make_node (OMP_TARGET_UPDATE); TREE_TYPE (stmt) = void_type_node; OMP_TARGET_UPDATE_CLAUSES (stmt) = clauses; SET_EXPR_LOCATION (stmt, loc); add_stmt (stmt); return false; } /* OpenMP 4.5: # pragma omp target enter data target-data-clause[optseq] new-line */ #define OMP_TARGET_ENTER_DATA_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DEVICE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_MAP) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_IF) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DEPEND) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NOWAIT)) static tree c_parser_omp_target_enter_data (location_t loc, c_parser *parser, enum pragma_context context) { bool data_seen = false; if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp (p, "data") == 0) { c_parser_consume_token (parser); data_seen = true; } } if (!data_seen) { c_parser_error (parser, "expected %<data%>"); c_parser_skip_to_pragma_eol (parser); return NULL_TREE; } if (context == pragma_stmt) { error_at (loc, "%<#pragma %s%> may only be used in compound statements", "omp target enter data"); c_parser_skip_to_pragma_eol (parser, false); return NULL_TREE; } tree clauses = c_parser_omp_all_clauses (parser, OMP_TARGET_ENTER_DATA_CLAUSE_MASK, "#pragma omp target enter data"); int map_seen = 0; for (tree *pc = &clauses; *pc;) { if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_MAP) switch (OMP_CLAUSE_MAP_KIND (*pc)) { case GOMP_MAP_TO: case GOMP_MAP_ALWAYS_TO: case GOMP_MAP_ALLOC: map_seen = 3; break; case GOMP_MAP_FIRSTPRIVATE_POINTER: case GOMP_MAP_ALWAYS_POINTER: break; default: map_seen |= 1; error_at (OMP_CLAUSE_LOCATION (*pc), "%<#pragma omp target enter data%> with map-type other " "than %<to%> or %<alloc%> on %<map%> clause"); *pc = OMP_CLAUSE_CHAIN (*pc); continue; } pc = &OMP_CLAUSE_CHAIN (*pc); } if (map_seen != 3) { if (map_seen == 0) error_at (loc, "%<#pragma omp target enter data%> must contain at least " "one %<map%> clause"); return NULL_TREE; } tree stmt = make_node (OMP_TARGET_ENTER_DATA); TREE_TYPE (stmt) = void_type_node; OMP_TARGET_ENTER_DATA_CLAUSES (stmt) = clauses; SET_EXPR_LOCATION (stmt, loc); add_stmt (stmt); return stmt; } /* OpenMP 4.5: # pragma omp target exit data target-data-clause[optseq] new-line */ #define OMP_TARGET_EXIT_DATA_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DEVICE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_MAP) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_IF) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DEPEND) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NOWAIT)) static tree c_parser_omp_target_exit_data (location_t loc, c_parser *parser, enum pragma_context context) { bool data_seen = false; if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp (p, "data") == 0) { c_parser_consume_token (parser); data_seen = true; } } if (!data_seen) { c_parser_error (parser, "expected %<data%>"); c_parser_skip_to_pragma_eol (parser); return NULL_TREE; } if (context == pragma_stmt) { error_at (loc, "%<#pragma %s%> may only be used in compound statements", "omp target exit data"); c_parser_skip_to_pragma_eol (parser, false); return NULL_TREE; } tree clauses = c_parser_omp_all_clauses (parser, OMP_TARGET_EXIT_DATA_CLAUSE_MASK, "#pragma omp target exit data"); int map_seen = 0; for (tree *pc = &clauses; *pc;) { if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_MAP) switch (OMP_CLAUSE_MAP_KIND (*pc)) { case GOMP_MAP_FROM: case GOMP_MAP_ALWAYS_FROM: case GOMP_MAP_RELEASE: case GOMP_MAP_DELETE: map_seen = 3; break; case GOMP_MAP_FIRSTPRIVATE_POINTER: case GOMP_MAP_ALWAYS_POINTER: break; default: map_seen |= 1; error_at (OMP_CLAUSE_LOCATION (*pc), "%<#pragma omp target exit data%> with map-type other " "than %<from%>, %<release%> or %<delete%> on %<map%>" " clause"); *pc = OMP_CLAUSE_CHAIN (*pc); continue; } pc = &OMP_CLAUSE_CHAIN (*pc); } if (map_seen != 3) { if (map_seen == 0) error_at (loc, "%<#pragma omp target exit data%> must contain at least one " "%<map%> clause"); return NULL_TREE; } tree stmt = make_node (OMP_TARGET_EXIT_DATA); TREE_TYPE (stmt) = void_type_node; OMP_TARGET_EXIT_DATA_CLAUSES (stmt) = clauses; SET_EXPR_LOCATION (stmt, loc); add_stmt (stmt); return stmt; } /* OpenMP 4.0: # pragma omp target target-clause[optseq] new-line structured-block */ #define OMP_TARGET_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DEVICE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_MAP) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_IF) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DEPEND) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NOWAIT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_PRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DEFAULTMAP) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_IS_DEVICE_PTR)) static bool c_parser_omp_target (c_parser *parser, enum pragma_context context, bool *if_p) { location_t loc = c_parser_peek_token (parser)->location; c_parser_consume_pragma (parser); tree *pc = NULL, stmt, block; if (context != pragma_stmt && context != pragma_compound) { c_parser_error (parser, "expected declaration specifiers"); c_parser_skip_to_pragma_eol (parser); return false; } if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); enum tree_code ccode = ERROR_MARK; if (strcmp (p, "teams") == 0) ccode = OMP_TEAMS; else if (strcmp (p, "parallel") == 0) ccode = OMP_PARALLEL; else if (strcmp (p, "simd") == 0) ccode = OMP_SIMD; if (ccode != ERROR_MARK) { tree cclauses[C_OMP_CLAUSE_SPLIT_COUNT]; char p_name[sizeof ("#pragma omp target teams distribute " "parallel for simd")]; c_parser_consume_token (parser); strcpy (p_name, "#pragma omp target"); if (!flag_openmp) /* flag_openmp_simd */ { tree stmt; switch (ccode) { case OMP_TEAMS: stmt = c_parser_omp_teams (loc, parser, p_name, OMP_TARGET_CLAUSE_MASK, cclauses, if_p); break; case OMP_PARALLEL: stmt = c_parser_omp_parallel (loc, parser, p_name, OMP_TARGET_CLAUSE_MASK, cclauses, if_p); break; case OMP_SIMD: stmt = c_parser_omp_simd (loc, parser, p_name, OMP_TARGET_CLAUSE_MASK, cclauses, if_p); break; default: gcc_unreachable (); } return stmt != NULL_TREE; } keep_next_level (); tree block = c_begin_compound_stmt (true), ret; switch (ccode) { case OMP_TEAMS: ret = c_parser_omp_teams (loc, parser, p_name, OMP_TARGET_CLAUSE_MASK, cclauses, if_p); break; case OMP_PARALLEL: ret = c_parser_omp_parallel (loc, parser, p_name, OMP_TARGET_CLAUSE_MASK, cclauses, if_p); break; case OMP_SIMD: ret = c_parser_omp_simd (loc, parser, p_name, OMP_TARGET_CLAUSE_MASK, cclauses, if_p); break; default: gcc_unreachable (); } block = c_end_compound_stmt (loc, block, true); if (ret == NULL_TREE) return false; if (ccode == OMP_TEAMS) { /* For combined target teams, ensure the num_teams and thread_limit clause expressions are evaluated on the host, before entering the target construct. */ tree c; for (c = cclauses[C_OMP_CLAUSE_SPLIT_TEAMS]; c; c = OMP_CLAUSE_CHAIN (c)) if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT) && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST) { tree expr = OMP_CLAUSE_OPERAND (c, 0); tree tmp = create_tmp_var_raw (TREE_TYPE (expr)); expr = build4 (TARGET_EXPR, TREE_TYPE (expr), tmp, expr, NULL_TREE, NULL_TREE); add_stmt (expr); OMP_CLAUSE_OPERAND (c, 0) = expr; tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c), OMP_CLAUSE_FIRSTPRIVATE); OMP_CLAUSE_DECL (tc) = tmp; OMP_CLAUSE_CHAIN (tc) = cclauses[C_OMP_CLAUSE_SPLIT_TARGET]; cclauses[C_OMP_CLAUSE_SPLIT_TARGET] = tc; } } tree stmt = make_node (OMP_TARGET); TREE_TYPE (stmt) = void_type_node; OMP_TARGET_CLAUSES (stmt) = cclauses[C_OMP_CLAUSE_SPLIT_TARGET]; OMP_TARGET_BODY (stmt) = block; OMP_TARGET_COMBINED (stmt) = 1; add_stmt (stmt); pc = &OMP_TARGET_CLAUSES (stmt); goto check_clauses; } else if (!flag_openmp) /* flag_openmp_simd */ { c_parser_skip_to_pragma_eol (parser, false); return false; } else if (strcmp (p, "data") == 0) { c_parser_consume_token (parser); c_parser_omp_target_data (loc, parser, if_p); return true; } else if (strcmp (p, "enter") == 0) { c_parser_consume_token (parser); c_parser_omp_target_enter_data (loc, parser, context); return false; } else if (strcmp (p, "exit") == 0) { c_parser_consume_token (parser); c_parser_omp_target_exit_data (loc, parser, context); return false; } else if (strcmp (p, "update") == 0) { c_parser_consume_token (parser); return c_parser_omp_target_update (loc, parser, context); } } if (!flag_openmp) /* flag_openmp_simd */ { c_parser_skip_to_pragma_eol (parser, false); return false; } stmt = make_node (OMP_TARGET); TREE_TYPE (stmt) = void_type_node; OMP_TARGET_CLAUSES (stmt) = c_parser_omp_all_clauses (parser, OMP_TARGET_CLAUSE_MASK, "#pragma omp target"); pc = &OMP_TARGET_CLAUSES (stmt); keep_next_level (); block = c_begin_compound_stmt (true); add_stmt (c_parser_omp_structured_block (parser, if_p)); OMP_TARGET_BODY (stmt) = c_end_compound_stmt (loc, block, true); SET_EXPR_LOCATION (stmt, loc); add_stmt (stmt); check_clauses: while (*pc) { if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_MAP) switch (OMP_CLAUSE_MAP_KIND (*pc)) { case GOMP_MAP_TO: case GOMP_MAP_ALWAYS_TO: case GOMP_MAP_FROM: case GOMP_MAP_ALWAYS_FROM: case GOMP_MAP_TOFROM: case GOMP_MAP_ALWAYS_TOFROM: case GOMP_MAP_ALLOC: case GOMP_MAP_FIRSTPRIVATE_POINTER: case GOMP_MAP_ALWAYS_POINTER: break; default: error_at (OMP_CLAUSE_LOCATION (*pc), "%<#pragma omp target%> with map-type other " "than %<to%>, %<from%>, %<tofrom%> or %<alloc%> " "on %<map%> clause"); *pc = OMP_CLAUSE_CHAIN (*pc); continue; } pc = &OMP_CLAUSE_CHAIN (*pc); } return true; } /* OpenMP 4.0: # pragma omp declare simd declare-simd-clauses[optseq] new-line */ #define OMP_DECLARE_SIMD_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_SIMDLEN) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_LINEAR) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_ALIGNED) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_UNIFORM) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_INBRANCH) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NOTINBRANCH)) static void c_parser_omp_declare_simd (c_parser *parser, enum pragma_context context) { auto_vec<c_token> clauses; while (c_parser_next_token_is_not (parser, CPP_PRAGMA_EOL)) { c_token *token = c_parser_peek_token (parser); if (token->type == CPP_EOF) { c_parser_skip_to_pragma_eol (parser); return; } clauses.safe_push (*token); c_parser_consume_token (parser); } clauses.safe_push (*c_parser_peek_token (parser)); c_parser_skip_to_pragma_eol (parser); while (c_parser_next_token_is (parser, CPP_PRAGMA)) { if (c_parser_peek_token (parser)->pragma_kind != PRAGMA_OMP_DECLARE || c_parser_peek_2nd_token (parser)->type != CPP_NAME || strcmp (IDENTIFIER_POINTER (c_parser_peek_2nd_token (parser)->value), "simd") != 0) { c_parser_error (parser, "%<#pragma omp declare simd%> must be followed by " "function declaration or definition or another " "%<#pragma omp declare simd%>"); return; } c_parser_consume_pragma (parser); while (c_parser_next_token_is_not (parser, CPP_PRAGMA_EOL)) { c_token *token = c_parser_peek_token (parser); if (token->type == CPP_EOF) { c_parser_skip_to_pragma_eol (parser); return; } clauses.safe_push (*token); c_parser_consume_token (parser); } clauses.safe_push (*c_parser_peek_token (parser)); c_parser_skip_to_pragma_eol (parser); } /* Make sure nothing tries to read past the end of the tokens. */ c_token eof_token; memset (&eof_token, 0, sizeof (eof_token)); eof_token.type = CPP_EOF; clauses.safe_push (eof_token); clauses.safe_push (eof_token); switch (context) { case pragma_external: if (c_parser_next_token_is (parser, CPP_KEYWORD) && c_parser_peek_token (parser)->keyword == RID_EXTENSION) { int ext = disable_extension_diagnostics (); do c_parser_consume_token (parser); while (c_parser_next_token_is (parser, CPP_KEYWORD) && c_parser_peek_token (parser)->keyword == RID_EXTENSION); c_parser_declaration_or_fndef (parser, true, true, true, false, true, NULL, clauses); restore_extension_diagnostics (ext); } else c_parser_declaration_or_fndef (parser, true, true, true, false, true, NULL, clauses); break; case pragma_struct: case pragma_param: case pragma_stmt: c_parser_error (parser, "%<#pragma omp declare simd%> must be followed by " "function declaration or definition"); break; case pragma_compound: if (c_parser_next_token_is (parser, CPP_KEYWORD) && c_parser_peek_token (parser)->keyword == RID_EXTENSION) { int ext = disable_extension_diagnostics (); do c_parser_consume_token (parser); while (c_parser_next_token_is (parser, CPP_KEYWORD) && c_parser_peek_token (parser)->keyword == RID_EXTENSION); if (c_parser_next_tokens_start_declaration (parser)) { c_parser_declaration_or_fndef (parser, true, true, true, true, true, NULL, clauses); restore_extension_diagnostics (ext); break; } restore_extension_diagnostics (ext); } else if (c_parser_next_tokens_start_declaration (parser)) { c_parser_declaration_or_fndef (parser, true, true, true, true, true, NULL, clauses); break; } c_parser_error (parser, "%<#pragma omp declare simd%> must be followed by " "function declaration or definition"); break; default: gcc_unreachable (); } } /* Finalize #pragma omp declare simd clauses after FNDECL has been parsed, and put that into "omp declare simd" attribute. */ static void c_finish_omp_declare_simd (c_parser *parser, tree fndecl, tree parms, vec<c_token> clauses) { /* Normally first token is CPP_NAME "simd". CPP_EOF there indicates error has been reported and CPP_PRAGMA that c_finish_omp_declare_simd has already processed the tokens. */ if (clauses.exists () && clauses[0].type == CPP_EOF) return; if (fndecl == NULL_TREE || TREE_CODE (fndecl) != FUNCTION_DECL) { error ("%<#pragma omp declare simd%> not immediately followed by " "a function declaration or definition"); clauses[0].type = CPP_EOF; return; } if (clauses.exists () && clauses[0].type != CPP_NAME) { error_at (DECL_SOURCE_LOCATION (fndecl), "%<#pragma omp declare simd%> not immediately followed by " "a single function declaration or definition"); clauses[0].type = CPP_EOF; return; } if (parms == NULL_TREE) parms = DECL_ARGUMENTS (fndecl); unsigned int tokens_avail = parser->tokens_avail; gcc_assert (parser->tokens == &parser->tokens_buf[0]); parser->tokens = clauses.address (); parser->tokens_avail = clauses.length (); /* c_parser_omp_declare_simd pushed 2 extra CPP_EOF tokens at the end. */ while (parser->tokens_avail > 3) { c_token *token = c_parser_peek_token (parser); gcc_assert (token->type == CPP_NAME && strcmp (IDENTIFIER_POINTER (token->value), "simd") == 0); c_parser_consume_token (parser); parser->in_pragma = true; tree c = NULL_TREE; c = c_parser_omp_all_clauses (parser, OMP_DECLARE_SIMD_CLAUSE_MASK, "#pragma omp declare simd"); c = c_omp_declare_simd_clauses_to_numbers (parms, c); if (c != NULL_TREE) c = tree_cons (NULL_TREE, c, NULL_TREE); c = build_tree_list (get_identifier ("omp declare simd"), c); TREE_CHAIN (c) = DECL_ATTRIBUTES (fndecl); DECL_ATTRIBUTES (fndecl) = c; } parser->tokens = &parser->tokens_buf[0]; parser->tokens_avail = tokens_avail; if (clauses.exists ()) clauses[0].type = CPP_PRAGMA; } /* OpenMP 4.0: # pragma omp declare target new-line declarations and definitions # pragma omp end declare target new-line OpenMP 4.5: # pragma omp declare target ( extended-list ) new-line # pragma omp declare target declare-target-clauses[seq] new-line */ #define OMP_DECLARE_TARGET_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_TO) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_LINK)) static void c_parser_omp_declare_target (c_parser *parser) { location_t loc = c_parser_peek_token (parser)->location; tree clauses = NULL_TREE; if (c_parser_next_token_is (parser, CPP_NAME)) clauses = c_parser_omp_all_clauses (parser, OMP_DECLARE_TARGET_CLAUSE_MASK, "#pragma omp declare target"); else if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { clauses = c_parser_omp_var_list_parens (parser, OMP_CLAUSE_TO_DECLARE, clauses); clauses = c_finish_omp_clauses (clauses, C_ORT_OMP); c_parser_skip_to_pragma_eol (parser); } else { c_parser_skip_to_pragma_eol (parser); current_omp_declare_target_attribute++; return; } if (current_omp_declare_target_attribute) error_at (loc, "%<#pragma omp declare target%> with clauses in between " "%<#pragma omp declare target%> without clauses and " "%<#pragma omp end declare target%>"); for (tree c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) { tree t = OMP_CLAUSE_DECL (c), id; tree at1 = lookup_attribute ("omp declare target", DECL_ATTRIBUTES (t)); tree at2 = lookup_attribute ("omp declare target link", DECL_ATTRIBUTES (t)); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LINK) { id = get_identifier ("omp declare target link"); std::swap (at1, at2); } else id = get_identifier ("omp declare target"); if (at2) { error_at (OMP_CLAUSE_LOCATION (c), "%qD specified both in declare target %<link%> and %<to%>" " clauses", t); continue; } if (!at1) { DECL_ATTRIBUTES (t) = tree_cons (id, NULL_TREE, DECL_ATTRIBUTES (t)); if (TREE_CODE (t) != FUNCTION_DECL && !is_global_var (t)) continue; symtab_node *node = symtab_node::get (t); if (node != NULL) { node->offloadable = 1; if (ENABLE_OFFLOADING) { g->have_offload = true; if (is_a <varpool_node *> (node)) vec_safe_push (offload_vars, t); } } } } } static void c_parser_omp_end_declare_target (c_parser *parser) { location_t loc = c_parser_peek_token (parser)->location; c_parser_consume_pragma (parser); if (c_parser_next_token_is (parser, CPP_NAME) && strcmp (IDENTIFIER_POINTER (c_parser_peek_token (parser)->value), "declare") == 0) { c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_NAME) && strcmp (IDENTIFIER_POINTER (c_parser_peek_token (parser)->value), "target") == 0) c_parser_consume_token (parser); else { c_parser_error (parser, "expected %<target%>"); c_parser_skip_to_pragma_eol (parser); return; } } else { c_parser_error (parser, "expected %<declare%>"); c_parser_skip_to_pragma_eol (parser); return; } c_parser_skip_to_pragma_eol (parser); if (!current_omp_declare_target_attribute) error_at (loc, "%<#pragma omp end declare target%> without corresponding " "%<#pragma omp declare target%>"); else current_omp_declare_target_attribute--; } /* OpenMP 4.0 #pragma omp declare reduction (reduction-id : typename-list : expression) \ initializer-clause[opt] new-line initializer-clause: initializer (omp_priv = initializer) initializer (function-name (argument-list)) */ static void c_parser_omp_declare_reduction (c_parser *parser, enum pragma_context context) { unsigned int tokens_avail = 0, i; vec<tree> types = vNULL; vec<c_token> clauses = vNULL; enum tree_code reduc_code = ERROR_MARK; tree reduc_id = NULL_TREE; tree type; location_t rloc = c_parser_peek_token (parser)->location; if (context == pragma_struct || context == pragma_param) { error ("%<#pragma omp declare reduction%> not at file or block scope"); goto fail; } if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) goto fail; switch (c_parser_peek_token (parser)->type) { case CPP_PLUS: reduc_code = PLUS_EXPR; break; case CPP_MULT: reduc_code = MULT_EXPR; break; case CPP_MINUS: reduc_code = MINUS_EXPR; break; case CPP_AND: reduc_code = BIT_AND_EXPR; break; case CPP_XOR: reduc_code = BIT_XOR_EXPR; break; case CPP_OR: reduc_code = BIT_IOR_EXPR; break; case CPP_AND_AND: reduc_code = TRUTH_ANDIF_EXPR; break; case CPP_OR_OR: reduc_code = TRUTH_ORIF_EXPR; break; case CPP_NAME: const char *p; p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp (p, "min") == 0) { reduc_code = MIN_EXPR; break; } if (strcmp (p, "max") == 0) { reduc_code = MAX_EXPR; break; } reduc_id = c_parser_peek_token (parser)->value; break; default: c_parser_error (parser, "expected %<+%>, %<*%>, %<-%>, %<&%>, " "%<^%>, %<|%>, %<&&%>, %<||%> or identifier"); goto fail; } tree orig_reduc_id, reduc_decl; orig_reduc_id = reduc_id; reduc_id = c_omp_reduction_id (reduc_code, reduc_id); reduc_decl = c_omp_reduction_decl (reduc_id); c_parser_consume_token (parser); if (!c_parser_require (parser, CPP_COLON, "expected %<:%>")) goto fail; while (true) { location_t loc = c_parser_peek_token (parser)->location; struct c_type_name *ctype = c_parser_type_name (parser); if (ctype != NULL) { type = groktypename (ctype, NULL, NULL); if (type == error_mark_node) ; else if ((INTEGRAL_TYPE_P (type) || TREE_CODE (type) == REAL_TYPE || TREE_CODE (type) == COMPLEX_TYPE) && orig_reduc_id == NULL_TREE) error_at (loc, "predeclared arithmetic type in " "%<#pragma omp declare reduction%>"); else if (TREE_CODE (type) == FUNCTION_TYPE || TREE_CODE (type) == ARRAY_TYPE) error_at (loc, "function or array type in " "%<#pragma omp declare reduction%>"); else if (TYPE_ATOMIC (type)) error_at (loc, "%<_Atomic%> qualified type in " "%<#pragma omp declare reduction%>"); else if (TYPE_QUALS_NO_ADDR_SPACE (type)) error_at (loc, "const, volatile or restrict qualified type in " "%<#pragma omp declare reduction%>"); else { tree t; for (t = DECL_INITIAL (reduc_decl); t; t = TREE_CHAIN (t)) if (comptypes (TREE_PURPOSE (t), type)) { error_at (loc, "redeclaration of %qs " "%<#pragma omp declare reduction%> for " "type %qT", IDENTIFIER_POINTER (reduc_id) + sizeof ("omp declare reduction ") - 1, type); location_t ploc = DECL_SOURCE_LOCATION (TREE_VEC_ELT (TREE_VALUE (t), 0)); error_at (ploc, "previous %<#pragma omp declare " "reduction%>"); break; } if (t == NULL_TREE) types.safe_push (type); } if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; } else break; } if (!c_parser_require (parser, CPP_COLON, "expected %<:%>") || types.is_empty ()) { fail: clauses.release (); types.release (); while (true) { c_token *token = c_parser_peek_token (parser); if (token->type == CPP_EOF || token->type == CPP_PRAGMA_EOL) break; c_parser_consume_token (parser); } c_parser_skip_to_pragma_eol (parser); return; } if (types.length () > 1) { while (c_parser_next_token_is_not (parser, CPP_PRAGMA_EOL)) { c_token *token = c_parser_peek_token (parser); if (token->type == CPP_EOF) goto fail; clauses.safe_push (*token); c_parser_consume_token (parser); } clauses.safe_push (*c_parser_peek_token (parser)); c_parser_skip_to_pragma_eol (parser); /* Make sure nothing tries to read past the end of the tokens. */ c_token eof_token; memset (&eof_token, 0, sizeof (eof_token)); eof_token.type = CPP_EOF; clauses.safe_push (eof_token); clauses.safe_push (eof_token); } int errs = errorcount; FOR_EACH_VEC_ELT (types, i, type) { tokens_avail = parser->tokens_avail; gcc_assert (parser->tokens == &parser->tokens_buf[0]); if (!clauses.is_empty ()) { parser->tokens = clauses.address (); parser->tokens_avail = clauses.length (); parser->in_pragma = true; } bool nested = current_function_decl != NULL_TREE; if (nested) c_push_function_context (); tree fndecl = build_decl (BUILTINS_LOCATION, FUNCTION_DECL, reduc_id, default_function_type); current_function_decl = fndecl; allocate_struct_function (fndecl, true); push_scope (); tree stmt = push_stmt_list (); /* Intentionally BUILTINS_LOCATION, so that -Wshadow doesn't warn about these. */ tree omp_out = build_decl (BUILTINS_LOCATION, VAR_DECL, get_identifier ("omp_out"), type); DECL_ARTIFICIAL (omp_out) = 1; DECL_CONTEXT (omp_out) = fndecl; pushdecl (omp_out); tree omp_in = build_decl (BUILTINS_LOCATION, VAR_DECL, get_identifier ("omp_in"), type); DECL_ARTIFICIAL (omp_in) = 1; DECL_CONTEXT (omp_in) = fndecl; pushdecl (omp_in); struct c_expr combiner = c_parser_expression (parser); struct c_expr initializer; tree omp_priv = NULL_TREE, omp_orig = NULL_TREE; bool bad = false; initializer.set_error (); if (!c_parser_require (parser, CPP_CLOSE_PAREN, "expected %<)%>")) bad = true; else if (c_parser_next_token_is (parser, CPP_NAME) && strcmp (IDENTIFIER_POINTER (c_parser_peek_token (parser)->value), "initializer") == 0) { c_parser_consume_token (parser); pop_scope (); push_scope (); omp_priv = build_decl (BUILTINS_LOCATION, VAR_DECL, get_identifier ("omp_priv"), type); DECL_ARTIFICIAL (omp_priv) = 1; DECL_INITIAL (omp_priv) = error_mark_node; DECL_CONTEXT (omp_priv) = fndecl; pushdecl (omp_priv); omp_orig = build_decl (BUILTINS_LOCATION, VAR_DECL, get_identifier ("omp_orig"), type); DECL_ARTIFICIAL (omp_orig) = 1; DECL_CONTEXT (omp_orig) = fndecl; pushdecl (omp_orig); if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) bad = true; else if (!c_parser_next_token_is (parser, CPP_NAME)) { c_parser_error (parser, "expected %<omp_priv%> or " "function-name"); bad = true; } else if (strcmp (IDENTIFIER_POINTER (c_parser_peek_token (parser)->value), "omp_priv") != 0) { if (c_parser_peek_2nd_token (parser)->type != CPP_OPEN_PAREN || c_parser_peek_token (parser)->id_kind != C_ID_ID) { c_parser_error (parser, "expected function-name %<(%>"); bad = true; } else initializer = c_parser_postfix_expression (parser); if (initializer.value && TREE_CODE (initializer.value) == CALL_EXPR) { int j; tree c = initializer.value; for (j = 0; j < call_expr_nargs (c); j++) { tree a = CALL_EXPR_ARG (c, j); STRIP_NOPS (a); if (TREE_CODE (a) == ADDR_EXPR && TREE_OPERAND (a, 0) == omp_priv) break; } if (j == call_expr_nargs (c)) error ("one of the initializer call arguments should be " "%<&omp_priv%>"); } } else { c_parser_consume_token (parser); if (!c_parser_require (parser, CPP_EQ, "expected %<=%>")) bad = true; else { tree st = push_stmt_list (); location_t loc = c_parser_peek_token (parser)->location; rich_location richloc (line_table, loc); start_init (omp_priv, NULL_TREE, 0, &richloc); struct c_expr init = c_parser_initializer (parser); finish_init (); finish_decl (omp_priv, loc, init.value, init.original_type, NULL_TREE); pop_stmt_list (st); } } if (!bad && !c_parser_require (parser, CPP_CLOSE_PAREN, "expected %<)%>")) bad = true; } if (!bad) { c_parser_skip_to_pragma_eol (parser); tree t = tree_cons (type, make_tree_vec (omp_priv ? 6 : 3), DECL_INITIAL (reduc_decl)); DECL_INITIAL (reduc_decl) = t; DECL_SOURCE_LOCATION (omp_out) = rloc; TREE_VEC_ELT (TREE_VALUE (t), 0) = omp_out; TREE_VEC_ELT (TREE_VALUE (t), 1) = omp_in; TREE_VEC_ELT (TREE_VALUE (t), 2) = combiner.value; walk_tree (&combiner.value, c_check_omp_declare_reduction_r, &TREE_VEC_ELT (TREE_VALUE (t), 0), NULL); if (omp_priv) { DECL_SOURCE_LOCATION (omp_priv) = rloc; TREE_VEC_ELT (TREE_VALUE (t), 3) = omp_priv; TREE_VEC_ELT (TREE_VALUE (t), 4) = omp_orig; TREE_VEC_ELT (TREE_VALUE (t), 5) = initializer.value; walk_tree (&initializer.value, c_check_omp_declare_reduction_r, &TREE_VEC_ELT (TREE_VALUE (t), 3), NULL); walk_tree (&DECL_INITIAL (omp_priv), c_check_omp_declare_reduction_r, &TREE_VEC_ELT (TREE_VALUE (t), 3), NULL); } } pop_stmt_list (stmt); pop_scope (); if (cfun->language != NULL) { ggc_free (cfun->language); cfun->language = NULL; } set_cfun (NULL); current_function_decl = NULL_TREE; if (nested) c_pop_function_context (); if (!clauses.is_empty ()) { parser->tokens = &parser->tokens_buf[0]; parser->tokens_avail = tokens_avail; } if (bad) goto fail; if (errs != errorcount) break; } clauses.release (); types.release (); } /* OpenMP 4.0 #pragma omp declare simd declare-simd-clauses[optseq] new-line #pragma omp declare reduction (reduction-id : typename-list : expression) \ initializer-clause[opt] new-line #pragma omp declare target new-line */ static void c_parser_omp_declare (c_parser *parser, enum pragma_context context) { c_parser_consume_pragma (parser); if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp (p, "simd") == 0) { /* c_parser_consume_token (parser); done in c_parser_omp_declare_simd. */ c_parser_omp_declare_simd (parser, context); return; } if (strcmp (p, "reduction") == 0) { c_parser_consume_token (parser); c_parser_omp_declare_reduction (parser, context); return; } if (!flag_openmp) /* flag_openmp_simd */ { c_parser_skip_to_pragma_eol (parser, false); return; } if (strcmp (p, "target") == 0) { c_parser_consume_token (parser); c_parser_omp_declare_target (parser); return; } } c_parser_error (parser, "expected %<simd%> or %<reduction%> " "or %<target%>"); c_parser_skip_to_pragma_eol (parser); } /* OpenMP 4.5: #pragma omp taskloop taskloop-clause[optseq] new-line for-loop #pragma omp taskloop simd taskloop-simd-clause[optseq] new-line for-loop */ #define OMP_TASKLOOP_CLAUSE_MASK \ ( (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_SHARED) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_PRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_LASTPRIVATE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_DEFAULT) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_GRAINSIZE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NUM_TASKS) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_COLLAPSE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_UNTIED) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_IF) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_FINAL) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_MERGEABLE) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_NOGROUP) \ | (OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_PRIORITY)) static tree c_parser_omp_taskloop (location_t loc, c_parser *parser, char *p_name, omp_clause_mask mask, tree *cclauses, bool *if_p) { tree clauses, block, ret; strcat (p_name, " taskloop"); mask |= OMP_TASKLOOP_CLAUSE_MASK; if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp (p, "simd") == 0) { tree cclauses_buf[C_OMP_CLAUSE_SPLIT_COUNT]; if (cclauses == NULL) cclauses = cclauses_buf; mask &= ~(OMP_CLAUSE_MASK_1 << PRAGMA_OMP_CLAUSE_REDUCTION); c_parser_consume_token (parser); if (!flag_openmp) /* flag_openmp_simd */ return c_parser_omp_simd (loc, parser, p_name, mask, cclauses, if_p); block = c_begin_compound_stmt (true); ret = c_parser_omp_simd (loc, parser, p_name, mask, cclauses, if_p); block = c_end_compound_stmt (loc, block, true); if (ret == NULL) return ret; ret = make_node (OMP_TASKLOOP); TREE_TYPE (ret) = void_type_node; OMP_FOR_BODY (ret) = block; OMP_FOR_CLAUSES (ret) = cclauses[C_OMP_CLAUSE_SPLIT_TASKLOOP]; SET_EXPR_LOCATION (ret, loc); add_stmt (ret); return ret; } } if (!flag_openmp) /* flag_openmp_simd */ { c_parser_skip_to_pragma_eol (parser, false); return NULL_TREE; } clauses = c_parser_omp_all_clauses (parser, mask, p_name, cclauses == NULL); if (cclauses) { omp_split_clauses (loc, OMP_TASKLOOP, mask, clauses, cclauses); clauses = cclauses[C_OMP_CLAUSE_SPLIT_TASKLOOP]; } block = c_begin_compound_stmt (true); ret = c_parser_omp_for_loop (loc, parser, OMP_TASKLOOP, clauses, NULL, if_p); block = c_end_compound_stmt (loc, block, true); add_stmt (block); return ret; } /* Main entry point to parsing most OpenMP pragmas. */ static void c_parser_omp_construct (c_parser *parser, bool *if_p) { enum pragma_kind p_kind; location_t loc; tree stmt; char p_name[sizeof "#pragma omp teams distribute parallel for simd"]; omp_clause_mask mask (0); loc = c_parser_peek_token (parser)->location; p_kind = c_parser_peek_token (parser)->pragma_kind; c_parser_consume_pragma (parser); switch (p_kind) { case PRAGMA_OACC_ATOMIC: c_parser_omp_atomic (loc, parser); return; case PRAGMA_OACC_CACHE: strcpy (p_name, "#pragma acc"); stmt = c_parser_oacc_cache (loc, parser); break; case PRAGMA_OACC_DATA: stmt = c_parser_oacc_data (loc, parser, if_p); break; case PRAGMA_OACC_HOST_DATA: stmt = c_parser_oacc_host_data (loc, parser, if_p); break; case PRAGMA_OACC_KERNELS: case PRAGMA_OACC_PARALLEL: strcpy (p_name, "#pragma acc"); stmt = c_parser_oacc_kernels_parallel (loc, parser, p_kind, p_name, if_p); break; case PRAGMA_OACC_LOOP: strcpy (p_name, "#pragma acc"); stmt = c_parser_oacc_loop (loc, parser, p_name, mask, NULL, if_p); break; case PRAGMA_OACC_WAIT: strcpy (p_name, "#pragma wait"); stmt = c_parser_oacc_wait (loc, parser, p_name); break; case PRAGMA_OMP_ATOMIC: c_parser_omp_atomic (loc, parser); return; case PRAGMA_OMP_CRITICAL: stmt = c_parser_omp_critical (loc, parser, if_p); break; case PRAGMA_OMP_DISTRIBUTE: strcpy (p_name, "#pragma omp"); stmt = c_parser_omp_distribute (loc, parser, p_name, mask, NULL, if_p); break; case PRAGMA_OMP_FOR: strcpy (p_name, "#pragma omp"); stmt = c_parser_omp_for (loc, parser, p_name, mask, NULL, if_p); break; case PRAGMA_OMP_MASTER: stmt = c_parser_omp_master (loc, parser, if_p); break; case PRAGMA_OMP_PARALLEL: strcpy (p_name, "#pragma omp"); stmt = c_parser_omp_parallel (loc, parser, p_name, mask, NULL, if_p); break; case PRAGMA_OMP_SECTIONS: strcpy (p_name, "#pragma omp"); stmt = c_parser_omp_sections (loc, parser, p_name, mask, NULL); break; case PRAGMA_OMP_SIMD: strcpy (p_name, "#pragma omp"); stmt = c_parser_omp_simd (loc, parser, p_name, mask, NULL, if_p); break; case PRAGMA_OMP_SINGLE: stmt = c_parser_omp_single (loc, parser, if_p); break; case PRAGMA_OMP_TASK: stmt = c_parser_omp_task (loc, parser, if_p); break; case PRAGMA_OMP_TASKGROUP: stmt = c_parser_omp_taskgroup (parser, if_p); break; case PRAGMA_OMP_TASKLOOP: strcpy (p_name, "#pragma omp"); stmt = c_parser_omp_taskloop (loc, parser, p_name, mask, NULL, if_p); break; case PRAGMA_OMP_TEAMS: strcpy (p_name, "#pragma omp"); stmt = c_parser_omp_teams (loc, parser, p_name, mask, NULL, if_p); break; default: gcc_unreachable (); } if (stmt) gcc_assert (EXPR_LOCATION (stmt) != UNKNOWN_LOCATION); } /* OpenMP 2.5: # pragma omp threadprivate (variable-list) */ static void c_parser_omp_threadprivate (c_parser *parser) { tree vars, t; location_t loc; c_parser_consume_pragma (parser); loc = c_parser_peek_token (parser)->location; vars = c_parser_omp_var_list_parens (parser, OMP_CLAUSE_ERROR, NULL); /* Mark every variable in VARS to be assigned thread local storage. */ for (t = vars; t; t = TREE_CHAIN (t)) { tree v = TREE_PURPOSE (t); /* FIXME diagnostics: Ideally we should keep individual locations for all the variables in the var list to make the following errors more precise. Perhaps c_parser_omp_var_list_parens() should construct a list of locations to go along with the var list. */ /* If V had already been marked threadprivate, it doesn't matter whether it had been used prior to this point. */ if (!VAR_P (v)) error_at (loc, "%qD is not a variable", v); else if (TREE_USED (v) && !C_DECL_THREADPRIVATE_P (v)) error_at (loc, "%qE declared %<threadprivate%> after first use", v); else if (! is_global_var (v)) error_at (loc, "automatic variable %qE cannot be %<threadprivate%>", v); else if (TREE_TYPE (v) == error_mark_node) ; else if (! COMPLETE_TYPE_P (TREE_TYPE (v))) error_at (loc, "%<threadprivate%> %qE has incomplete type", v); else { if (! DECL_THREAD_LOCAL_P (v)) { set_decl_tls_model (v, decl_default_tls_model (v)); /* If rtl has been already set for this var, call make_decl_rtl once again, so that encode_section_info has a chance to look at the new decl flags. */ if (DECL_RTL_SET_P (v)) make_decl_rtl (v); } C_DECL_THREADPRIVATE_P (v) = 1; } } c_parser_skip_to_pragma_eol (parser); } /* Parse a transaction attribute (GCC Extension). transaction-attribute: attributes [ [ any-word ] ] The transactional memory language description is written for C++, and uses the C++0x attribute syntax. For compatibility, allow the bracket style for transactions in C as well. */ static tree c_parser_transaction_attributes (c_parser *parser) { tree attr_name, attr = NULL; if (c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) return c_parser_attributes (parser); if (!c_parser_next_token_is (parser, CPP_OPEN_SQUARE)) return NULL_TREE; c_parser_consume_token (parser); if (!c_parser_require (parser, CPP_OPEN_SQUARE, "expected %<[%>")) goto error1; attr_name = c_parser_attribute_any_word (parser); if (attr_name) { c_parser_consume_token (parser); attr = build_tree_list (attr_name, NULL_TREE); } else c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, "expected %<]%>"); error1: c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, "expected %<]%>"); return attr; } /* Parse a __transaction_atomic or __transaction_relaxed statement (GCC Extension). transaction-statement: __transaction_atomic transaction-attribute[opt] compound-statement __transaction_relaxed compound-statement Note that the only valid attribute is: "outer". */ static tree c_parser_transaction (c_parser *parser, enum rid keyword) { unsigned int old_in = parser->in_transaction; unsigned int this_in = 1, new_in; location_t loc = c_parser_peek_token (parser)->location; tree stmt, attrs; gcc_assert ((keyword == RID_TRANSACTION_ATOMIC || keyword == RID_TRANSACTION_RELAXED) && c_parser_next_token_is_keyword (parser, keyword)); c_parser_consume_token (parser); if (keyword == RID_TRANSACTION_RELAXED) this_in |= TM_STMT_ATTR_RELAXED; else { attrs = c_parser_transaction_attributes (parser); if (attrs) this_in |= parse_tm_stmt_attr (attrs, TM_STMT_ATTR_OUTER); } /* Keep track if we're in the lexical scope of an outer transaction. */ new_in = this_in | (old_in & TM_STMT_ATTR_OUTER); parser->in_transaction = new_in; stmt = c_parser_compound_statement (parser); parser->in_transaction = old_in; if (flag_tm) stmt = c_finish_transaction (loc, stmt, this_in); else error_at (loc, (keyword == RID_TRANSACTION_ATOMIC ? "%<__transaction_atomic%> without transactional memory support enabled" : "%<__transaction_relaxed %> " "without transactional memory support enabled")); return stmt; } /* Parse a __transaction_atomic or __transaction_relaxed expression (GCC Extension). transaction-expression: __transaction_atomic ( expression ) __transaction_relaxed ( expression ) */ static struct c_expr c_parser_transaction_expression (c_parser *parser, enum rid keyword) { struct c_expr ret; unsigned int old_in = parser->in_transaction; unsigned int this_in = 1; location_t loc = c_parser_peek_token (parser)->location; tree attrs; gcc_assert ((keyword == RID_TRANSACTION_ATOMIC || keyword == RID_TRANSACTION_RELAXED) && c_parser_next_token_is_keyword (parser, keyword)); c_parser_consume_token (parser); if (keyword == RID_TRANSACTION_RELAXED) this_in |= TM_STMT_ATTR_RELAXED; else { attrs = c_parser_transaction_attributes (parser); if (attrs) this_in |= parse_tm_stmt_attr (attrs, 0); } parser->in_transaction = this_in; matching_parens parens; if (parens.require_open (parser)) { tree expr = c_parser_expression (parser).value; ret.original_type = TREE_TYPE (expr); ret.value = build1 (TRANSACTION_EXPR, ret.original_type, expr); if (this_in & TM_STMT_ATTR_RELAXED) TRANSACTION_EXPR_RELAXED (ret.value) = 1; SET_EXPR_LOCATION (ret.value, loc); ret.original_code = TRANSACTION_EXPR; if (!parens.require_close (parser)) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); goto error; } } else { error: ret.set_error (); ret.original_code = ERROR_MARK; ret.original_type = NULL; } parser->in_transaction = old_in; if (!flag_tm) error_at (loc, (keyword == RID_TRANSACTION_ATOMIC ? "%<__transaction_atomic%> without transactional memory support enabled" : "%<__transaction_relaxed %> " "without transactional memory support enabled")); set_c_expr_source_range (&ret, loc, loc); return ret; } /* Parse a __transaction_cancel statement (GCC Extension). transaction-cancel-statement: __transaction_cancel transaction-attribute[opt] ; Note that the only valid attribute is "outer". */ static tree c_parser_transaction_cancel (c_parser *parser) { location_t loc = c_parser_peek_token (parser)->location; tree attrs; bool is_outer = false; gcc_assert (c_parser_next_token_is_keyword (parser, RID_TRANSACTION_CANCEL)); c_parser_consume_token (parser); attrs = c_parser_transaction_attributes (parser); if (attrs) is_outer = (parse_tm_stmt_attr (attrs, TM_STMT_ATTR_OUTER) != 0); if (!flag_tm) { error_at (loc, "%<__transaction_cancel%> without " "transactional memory support enabled"); goto ret_error; } else if (parser->in_transaction & TM_STMT_ATTR_RELAXED) { error_at (loc, "%<__transaction_cancel%> within a " "%<__transaction_relaxed%>"); goto ret_error; } else if (is_outer) { if ((parser->in_transaction & TM_STMT_ATTR_OUTER) == 0 && !is_tm_may_cancel_outer (current_function_decl)) { error_at (loc, "outer %<__transaction_cancel%> not " "within outer %<__transaction_atomic%>"); error_at (loc, " or a %<transaction_may_cancel_outer%> function"); goto ret_error; } } else if (parser->in_transaction == 0) { error_at (loc, "%<__transaction_cancel%> not within " "%<__transaction_atomic%>"); goto ret_error; } return add_stmt (build_tm_abort_call (loc, is_outer)); ret_error: return build1 (NOP_EXPR, void_type_node, error_mark_node); } /* Parse a single source file. */ void c_parse_file (void) { /* Use local storage to begin. If the first token is a pragma, parse it. If it is #pragma GCC pch_preprocess, then this will load a PCH file which will cause garbage collection. */ c_parser tparser; memset (&tparser, 0, sizeof tparser); tparser.tokens = &tparser.tokens_buf[0]; the_parser = &tparser; if (c_parser_peek_token (&tparser)->pragma_kind == PRAGMA_GCC_PCH_PREPROCESS) c_parser_pragma_pch_preprocess (&tparser); the_parser = ggc_alloc<c_parser> (); *the_parser = tparser; if (tparser.tokens == &tparser.tokens_buf[0]) the_parser->tokens = &the_parser->tokens_buf[0]; /* Initialize EH, if we've been told to do so. */ if (flag_exceptions) using_eh_for_cleanups (); c_parser_translation_unit (the_parser); the_parser = NULL; } /* Parse the body of a function declaration marked with "__RTL". The RTL parser works on the level of characters read from a FILE *, whereas c_parser works at the level of tokens. Square this circle by consuming all of the tokens up to and including the closing brace, recording the start/end of the RTL fragment, and reopening the file and re-reading the relevant lines within the RTL parser. This requires the opening and closing braces of the C function to be on separate lines from the RTL they wrap. Take ownership of START_WITH_PASS, if non-NULL. */ void c_parser_parse_rtl_body (c_parser *parser, char *start_with_pass) { if (!c_parser_require (parser, CPP_OPEN_BRACE, "expected %<{%>")) { free (start_with_pass); return; } location_t start_loc = c_parser_peek_token (parser)->location; /* Consume all tokens, up to the closing brace, handling matching pairs of braces in the rtl dump. */ int num_open_braces = 1; while (1) { switch (c_parser_peek_token (parser)->type) { case CPP_OPEN_BRACE: num_open_braces++; break; case CPP_CLOSE_BRACE: if (--num_open_braces == 0) goto found_closing_brace; break; case CPP_EOF: error_at (start_loc, "no closing brace"); free (start_with_pass); return; default: break; } c_parser_consume_token (parser); } found_closing_brace: /* At the closing brace; record its location. */ location_t end_loc = c_parser_peek_token (parser)->location; /* Consume the closing brace. */ c_parser_consume_token (parser); /* Invoke the RTL parser. */ if (!read_rtl_function_body_from_file_range (start_loc, end_loc)) { free (start_with_pass); return; } /* If a pass name was provided for START_WITH_PASS, run the backend accordingly now, on the cfun created above, transferring ownership of START_WITH_PASS. */ if (start_with_pass) run_rtl_passes (start_with_pass); } #include "gt-c-c-parser.h"
ddm_matrix_assembly.c
// // Created by bergolho on 25/07/19. // #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include <time.h> #include "../alg/grid/grid.h" #include "../config/assembly_matrix_config.h" #include "../monodomain/constants.h" #include "../utils/utils.h" #include "../single_file_libraries/stb_ds.h" #include "../config_helpers/config_helpers.h" INIT_ASSEMBLY_MATRIX(set_initial_conditions_fvm) { real_cpu alpha; struct cell_node **ac = the_grid->active_cells; uint32_t active_cells = the_grid->num_active_cells; real_cpu beta = the_solver->beta; real_cpu cm = the_solver->cm; real_cpu dt = the_solver->dt; int i; #pragma omp parallel for private(alpha) for(i = 0; i < active_cells; i++) { alpha = ALPHA(beta, cm, dt, ac[i]->discretization.x, ac[i]->discretization.y, ac[i]->discretization.z); ac[i]->v = initial_v; ac[i]->b = initial_v * alpha; } } static struct element fill_element_ddm (uint32_t position, char direction, real_cpu dx, real_cpu dy, real_cpu dz,\ const real_cpu sigma_x, const real_cpu sigma_y, const real_cpu sigma_z,\ const real_cpu kappa_x, const real_cpu kappa_y, const real_cpu kappa_z,\ const real_cpu dt,\ struct element *cell_elements); void create_sigma_low_block(struct cell_node* ac,real_cpu x_left, real_cpu x_right, real_cpu y_down, real_cpu y_up,double b_sigma_x, double b_sigma_y, double b_sigma_z,double sigma_factor) { real_cpu x = ac->center.x; real_cpu y = ac->center.y; if( (x<=x_right) && (x>= x_left) && (y>= y_down) && (y<= y_up)) { ac->sigma.x = b_sigma_x*sigma_factor; ac->sigma.y = b_sigma_y*sigma_factor; ac->sigma.z = b_sigma_z*sigma_factor; } } void calculate_kappa_elements(struct monodomain_solver *the_solver, struct grid *the_grid,\ const real_cpu cell_length_x, const real_cpu cell_length_y, const real_cpu cell_length_z) { uint32_t num_active_cells = the_grid->num_active_cells; struct cell_node **ac = the_grid->active_cells; real_cpu beta = the_solver->beta; real_cpu cm = the_solver->cm; #pragma omp parallel for for (uint32_t i = 0; i < num_active_cells; i++) { ac[i]->kappa.x = KAPPA(beta,cm,cell_length_x,ac[i]->discretization.x); ac[i]->kappa.y = KAPPA(beta,cm,cell_length_y,ac[i]->discretization.y); ac[i]->kappa.z = KAPPA(beta,cm,cell_length_z,ac[i]->discretization.z); } } struct element fill_element_ddm (uint32_t position, char direction, real_cpu dx, real_cpu dy, real_cpu dz,\ const real_cpu sigma_x, const real_cpu sigma_y, const real_cpu sigma_z,\ const real_cpu kappa_x, const real_cpu kappa_y, const real_cpu kappa_z,\ const real_cpu dt,\ struct element *cell_elements) { real_cpu multiplier; struct element new_element; new_element.column = position; new_element.direction = direction; // Z direction if(direction == 'n') { multiplier = ((dx * dy) / dz); new_element.value = ( multiplier * (-sigma_z - (kappa_z / dt)) ); cell_elements[0].value += ( multiplier * (sigma_z + (kappa_z / dt)) ); } // Z direction else if(direction == 's') { multiplier = ((dx * dy) / dz); new_element.value = ( multiplier * (-sigma_z - (kappa_z / dt)) ); cell_elements[0].value += ( multiplier * (sigma_z + (kappa_z / dt)) ); } // Y direction else if(direction == 'e') { multiplier = ((dx * dz) / dy); new_element.value = ( multiplier * (-sigma_y - (kappa_y / dt)) ); cell_elements[0].value += ( multiplier * (sigma_y + (kappa_y / dt)) ); } // Y direction else if(direction == 'w') { multiplier = ((dx * dz) / dy); new_element.value = ( multiplier * (-sigma_y - (kappa_y / dt)) ); cell_elements[0].value += ( multiplier * (sigma_y + (kappa_y / dt)) ); } // X direction else if(direction == 'f') { multiplier = ((dy * dz) / dx); new_element.value = ( multiplier * (-sigma_x - (kappa_x / dt)) ); cell_elements[0].value += ( multiplier * (sigma_x + (kappa_x / dt)) ); } // X direction else if(direction == 'b') { multiplier = ((dy * dz) / dx); new_element.value = ( multiplier * (-sigma_x - (kappa_x / dt)) ); cell_elements[0].value += ( multiplier * (sigma_x + (kappa_x / dt)) ); } return new_element; } static void fill_discretization_matrix_elements_ddm (struct cell_node *grid_cell, void *neighbour_grid_cell, real_cpu dt ,char direction) { uint32_t position; bool has_found; real_cpu dx, dy, dz; struct transition_node *white_neighbor_cell; struct cell_node *black_neighbor_cell; /* When neighbour_grid_cell is a transition node, looks for the next neighbor * cell which is a cell node. */ uint16_t neighbour_grid_cell_level = ((struct basic_cell_data *)(neighbour_grid_cell))->level; char neighbour_grid_cell_type = ((struct basic_cell_data *)(neighbour_grid_cell))->type; if(neighbour_grid_cell_level > grid_cell->cell_data.level) { if(neighbour_grid_cell_type == TRANSITION_NODE_TYPE) { has_found = false; while(!has_found) { if(neighbour_grid_cell_type == TRANSITION_NODE_TYPE) { white_neighbor_cell = (struct transition_node *)neighbour_grid_cell; if(white_neighbor_cell->single_connector == NULL) { has_found = true; } else { neighbour_grid_cell = white_neighbor_cell->quadruple_connector1; neighbour_grid_cell_type = ((struct basic_cell_data *)(neighbour_grid_cell))->type; } } else { break; } } } } else { if(neighbour_grid_cell_level <= grid_cell->cell_data.level && (neighbour_grid_cell_type == TRANSITION_NODE_TYPE)) { has_found = false; while(!has_found) { if(neighbour_grid_cell_type == TRANSITION_NODE_TYPE) { white_neighbor_cell = (struct transition_node *)(neighbour_grid_cell); if(white_neighbor_cell->single_connector == 0) { has_found = true; } else { neighbour_grid_cell = white_neighbor_cell->single_connector; neighbour_grid_cell_type = ((struct basic_cell_data *)(neighbour_grid_cell))->type; } } else { break; } } } } // We care only with the interior points if(neighbour_grid_cell_type == CELL_NODE_TYPE) { black_neighbor_cell = (struct cell_node *)(neighbour_grid_cell); if(black_neighbor_cell->active) { real_cpu sigma_x1 = grid_cell->sigma.x; real_cpu sigma_x2 = black_neighbor_cell->sigma.x; real_cpu sigma_x = 0.0; if(sigma_x1 != 0.0 && sigma_x2 != 0.0) { sigma_x = (2.0f * sigma_x1 * sigma_x2) / (sigma_x1 + sigma_x2); } real_cpu sigma_y1 = grid_cell->sigma.y; real_cpu sigma_y2 = black_neighbor_cell->sigma.y; real_cpu sigma_y = 0.0; if(sigma_y1 != 0.0 && sigma_y2 != 0.0) { sigma_y = (2.0f * sigma_y1 * sigma_y2) / (sigma_y1 + sigma_y2); } real_cpu sigma_z1 = grid_cell->sigma.z; real_cpu sigma_z2 = black_neighbor_cell->sigma.z; real_cpu sigma_z = 0.0; if(sigma_z1 != 0.0 && sigma_z2 != 0.0) { sigma_z = (2.0f * sigma_z1 * sigma_z2) / (sigma_z1 + sigma_z2); } if(black_neighbor_cell->cell_data.level > grid_cell->cell_data.level) { dx = black_neighbor_cell->discretization.x; dy = black_neighbor_cell->discretization.y; dz = black_neighbor_cell->discretization.z; } else { dx = grid_cell->discretization.x; dy = grid_cell->discretization.y; dz = grid_cell->discretization.z; } lock_cell_node(grid_cell); struct element *cell_elements = grid_cell->elements; position = black_neighbor_cell->grid_position; size_t max_elements = arrlen(cell_elements); bool insert = true; for(size_t i = 1; i < max_elements; i++) { if(cell_elements[i].column == position) { insert = false; break; } } if(insert) { struct element new_element = fill_element_ddm(position, direction,\ dx, dy, dz,\ sigma_x, sigma_y, sigma_z,\ grid_cell->kappa.x,grid_cell->kappa.y,grid_cell->kappa.z,\ dt, cell_elements); new_element.cell = black_neighbor_cell; arrput(grid_cell->elements, new_element); } unlock_cell_node(grid_cell); lock_cell_node(black_neighbor_cell); cell_elements = black_neighbor_cell->elements; position = grid_cell->grid_position; max_elements = arrlen(cell_elements); insert = true; for(size_t i = 1; i < max_elements; i++) { if(cell_elements[i].column == position) { insert = false; break; } } if(insert) { struct element new_element = fill_element_ddm(position, direction,\ dx, dy, dz,\ sigma_x, sigma_y, sigma_z,\ grid_cell->kappa.x,grid_cell->kappa.y,grid_cell->kappa.z,\ dt, cell_elements); new_element.cell = grid_cell; arrput(black_neighbor_cell->elements, new_element); } unlock_cell_node(black_neighbor_cell); } } } void initialize_diagonal_elements(struct monodomain_solver *the_solver, struct grid *the_grid) { real_cpu alpha, dx, dy, dz; uint32_t num_active_cells = the_grid->num_active_cells; struct cell_node **ac = the_grid->active_cells; real_cpu beta = the_solver->beta; real_cpu cm = the_solver->cm; real_cpu dt = the_solver->dt; int i; #pragma omp parallel for private(alpha, dx, dy, dz) for(i = 0; i < num_active_cells; i++) { dx = ac[i]->discretization.x; dy = ac[i]->discretization.y; dz = ac[i]->discretization.z; alpha = ALPHA(beta, cm, dt, dx, dy, dz); struct element element; element.column = ac[i]->grid_position; element.cell = ac[i]; element.value = alpha; if(ac[i]->elements) arrfree(ac[i]->elements); ac[i]->elements = NULL; arrsetcap(ac[i]->elements, 7); arrput(ac[i]->elements, element); } } int randRange(int n) { int limit; int r; limit = RAND_MAX - (RAND_MAX % n); while((r = rand()) >= limit) ; return r % n; } // This function will read the fibrotic regions and for each cell that is inside the region and we will // reduce its conductivity value based on the 'sigma_factor'. ASSEMBLY_MATRIX (heterogenous_fibrotic_sigma_with_factor_ddm_assembly_matrix) { static bool sigma_initialized = false; uint32_t num_active_cells = the_grid->num_active_cells; struct cell_node **ac = the_grid->active_cells; initialize_diagonal_elements(the_solver, the_grid); char *fib_file = NULL; GET_PARAMETER_VALUE_CHAR_OR_REPORT_ERROR(fib_file, config->config_data, "fibrosis_file"); int fib_size = 0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(int,fib_size, config->config_data, "size"); real sigma_x = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_x, config->config_data, "sigma_x"); real sigma_y = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_y, config->config_data, "sigma_y"); real sigma_z = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_z, config->config_data, "sigma_z"); real cell_length_x = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_x, config->config_data, "cell_length_x"); real cell_length_y = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_y, config->config_data, "cell_length_y"); real cell_length_z = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_z, config->config_data, "cell_length_z"); real sigma_factor = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_factor, config->config_data, "sigma_factor"); // Calculate the kappa values on each cell of th grid calculate_kappa_elements(the_solver,the_grid,cell_length_x,cell_length_y,cell_length_z); if(!sigma_initialized) { #pragma omp parallel for for (uint32_t i = 0; i < num_active_cells; i++) { ac[i]->sigma.x = sigma_x; ac[i]->sigma.y = sigma_y; ac[i]->sigma.z = sigma_z; } sigma_initialized = true; } // Read and store the fibrosis locations FILE *file = fopen(fib_file, "r"); if(!file) { printf("Error opening file %s!!\n", fib_file); exit(0); } real_cpu **scar_mesh = (real_cpu **)malloc(sizeof(real_cpu *) * fib_size); for(int i = 0; i < fib_size; i++) { scar_mesh[i] = (real_cpu *)malloc(sizeof(real_cpu) * 7); if(scar_mesh[i] == NULL) { printf("Failed to allocate memory\n"); exit(0); } } uint32_t i = 0; while (fscanf(file, "%lf,%lf,%lf,%lf,%lf,%lf,%lf\n", &scar_mesh[i][0], &scar_mesh[i][1], &scar_mesh[i][2], &scar_mesh[i][3], &scar_mesh[i][4], &scar_mesh[i][5], &scar_mesh[i][6]) != EOF) { i++; } fclose(file); uint32_t num_fibrotic_regions = i; // Pass through all the cells of the grid and check if its center is inside the current // fibrotic region #pragma omp parallel for for(int j = 0; j < num_fibrotic_regions; j++) { struct cell_node *grid_cell = the_grid->first_cell; real_cpu b_center_x = scar_mesh[j][0]; real_cpu b_center_y = scar_mesh[j][1]; real_cpu b_h_dx = scar_mesh[j][3]; real_cpu b_h_dy = scar_mesh[j][4]; bool active = (bool) (scar_mesh[j][6]); while(grid_cell != 0) { if (grid_cell->active) { real_cpu center_x = grid_cell->center.x; real_cpu center_y = grid_cell->center.y; real_cpu half_dx = grid_cell->discretization.x/2.0; real_cpu half_dy = grid_cell->discretization.y/2.0; struct point_3d p; struct point_3d q; p.x = b_center_y + b_h_dy; p.y = b_center_y - b_h_dy; q.x = b_center_x + b_h_dx; q.y = b_center_x - b_h_dx; // Check if the current cell is inside the fibrotic region if (center_x > q.y && center_x < q.x && center_y > p.y && center_y < p.x) { if(active == 0) { grid_cell->sigma.x = sigma_x * sigma_factor; grid_cell->sigma.y = sigma_y * sigma_factor; grid_cell->sigma.z = sigma_z * sigma_factor; } } } grid_cell = grid_cell->next; } } printf("[!] Using DDM formulation\n"); printf("[X] Cell length = %.10lf || sigma_x = %.10lf || dx = %.10lf || kappa_x = %.10lf\n",\ cell_length_x,ac[0]->sigma.x,ac[0]->discretization.x,ac[0]->kappa.x); printf("[Y] Cell length = %.10lf || sigma_y = %.10lf || dy = %.10lf || kappa_y = %.10lf\n",\ cell_length_y,ac[0]->sigma.y,ac[0]->discretization.y,ac[0]->kappa.y); printf("[Z] Cell length = %.10lf || sigma_z = %.10lf || dz = %.10lf || kappa_z = %.10lf\n",\ cell_length_z,ac[0]->sigma.z,ac[0]->discretization.z,ac[0]->kappa.z); #pragma omp parallel for for(int i = 0; i < num_active_cells; i++) { // Computes and designates the flux due to south cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->south, the_solver->dt,'s'); // Computes and designates the flux due to north cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->north, the_solver->dt,'n'); // Computes and designates the flux due to east cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->east, the_solver->dt,'e'); // Computes and designates the flux due to west cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->west, the_solver->dt,'w'); // Computes and designates the flux due to front cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->front, the_solver->dt,'f'); // Computes and designates the flux due to back cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->back, the_solver->dt,'b'); } for(int k = 0; k < fib_size; k++) { free(scar_mesh[k]); } free(scar_mesh); } ASSEMBLY_MATRIX(homogenous_ddm_assembly_matrix) { static bool sigma_initialized = false; struct cell_node *grid_cell; uint32_t num_active_cells = the_grid->num_active_cells; struct cell_node **ac = the_grid->active_cells; initialize_diagonal_elements(the_solver, the_grid); real sigma_x = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_x, config->config_data, "sigma_x"); real sigma_y = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_y, config->config_data, "sigma_y"); real sigma_z = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_z, config->config_data, "sigma_z"); real cell_length_x = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_x, config->config_data, "cell_length_x"); real cell_length_y = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_y, config->config_data, "cell_length_y"); real cell_length_z = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_z, config->config_data, "cell_length_z"); // Calculate the kappa values on each cell of th grid calculate_kappa_elements(the_solver,the_grid,cell_length_x,cell_length_y,cell_length_z); printf("[!] Using DDM formulation\n"); printf("[X] Cell length = %.10lf || sigma_x = %.10lf || dx = %.10lf || kappa_x = %.10lf\n",\ cell_length_x,ac[0]->sigma.x,ac[0]->discretization.x,ac[0]->kappa.x); printf("[Y] Cell length = %.10lf || sigma_y = %.10lf || dy = %.10lf || kappa_y = %.10lf\n",\ cell_length_y,ac[0]->sigma.y,ac[0]->discretization.y,ac[0]->kappa.y); printf("[Z] Cell length = %.10lf || sigma_z = %.10lf || dz = %.10lf || kappa_z = %.10lf\n",\ cell_length_z,ac[0]->sigma.z,ac[0]->discretization.z,ac[0]->kappa.z); // Initialize the conductivities of each cell if (!sigma_initialized) { grid_cell = the_grid->first_cell; while(grid_cell != 0) { if(grid_cell->active) { grid_cell->sigma.x = sigma_x; grid_cell->sigma.y = sigma_y; grid_cell->sigma.z = sigma_z; } grid_cell = grid_cell->next; } sigma_initialized = true; } #pragma omp parallel for for(int i = 0; i < num_active_cells; i++) { // Computes and designates the flux due to south cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->south, the_solver->dt,'s'); // Computes and designates the flux due to north cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->north, the_solver->dt,'n'); // Computes and designates the flux due to east cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->east, the_solver->dt,'e'); // Computes and designates the flux due to west cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->west, the_solver->dt,'w'); // Computes and designates the flux due to front cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->front, the_solver->dt,'f'); // Computes and designates the flux due to back cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->back, the_solver->dt,'b'); } } ASSEMBLY_MATRIX(sigma_low_region_triangle_ddm_tiny) { uint32_t num_active_cells = the_grid->num_active_cells; struct cell_node **ac = the_grid->active_cells; initialize_diagonal_elements(the_solver, the_grid); int i; real sigma_x = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_x, config->config_data, "sigma_x"); real sigma_y = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_y, config->config_data, "sigma_y"); real sigma_z = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_z, config->config_data, "sigma_z"); real cell_length_x = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_x, config->config_data, "cell_length_x"); real cell_length_y = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_y, config->config_data, "cell_length_y"); real cell_length_z = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_z, config->config_data, "cell_length_z"); real sigma_factor = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_factor, config->config_data, "sigma_factor"); real sigma_factor_2 = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_factor_2, config->config_data, "sigma_factor_2"); real side_length = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,side_length, config->config_data, "side_length"); // Calculate the kappas for the DDM calculate_kappa_elements(the_solver,the_grid,cell_length_x,cell_length_y,cell_length_z); //~ bool inside; // Initialize the conductivities #pragma omp parallel for for (i = 0; i < num_active_cells; i++) { ac[i]->sigma.x = sigma_x; ac[i]->sigma.y = sigma_y; ac[i]->sigma.z = sigma_z; } printf("[!] Using DDM formulation\n"); printf("[X] Cell length = %.10lf || sigma_x = %.10lf || dx = %.10lf || kappa_x = %.10lf\n",\ cell_length_x,ac[0]->sigma.x,ac[0]->discretization.x,ac[0]->kappa.x); printf("[Y] Cell length = %.10lf || sigma_y = %.10lf || dy = %.10lf || kappa_y = %.10lf\n",\ cell_length_y,ac[0]->sigma.y,ac[0]->discretization.y,ac[0]->kappa.y); printf("[Z] Cell length = %.10lf || sigma_z = %.10lf || dz = %.10lf || kappa_z = %.10lf\n",\ cell_length_z,ac[0]->sigma.z,ac[0]->discretization.z,ac[0]->kappa.z); //regiao ao redor do meio com sigma menor// /*Aqui comeca a brincadeira de criar os triangulos * * Pensei em dividir em 3 partes a primeira uma barra * * 1 2 3 * ******* * ****** * ***** * **** * ** * * * 1 fazendo o canal * * ** * ** * ** * ** * ** * * 2 considerar a abertura de maneira que pegue 5 celulas * * * * * * * * * * * 3 pegar o triangulo * * **** * *** * ** * * * * Dai (1)+(2)+(3) eh a area que desejamos * * */ // set the square scar mesh... //~ real X_left = side_length/3.0; //~ real X_right = (side_length/3.0+side_length/3.0); //~ real Y_down = side_length/3.0; //~ real Y_up = (side_length/3.0+side_length/3.0); //esquerda //~ real X_left = side_length/6.0; //~ real X_right = (side_length/3.0+side_length/3.0); real X_left = side_length/12.0; real X_right = (side_length/6.0+side_length/6.0); //~ real Y_down = side_length/6.0; real Y_down = 0.0; //~ real Y_up = (side_length/6.0+side_length/6.0+side_length/12.0); real Y_up = (side_length/6.0+side_length/6.0+side_length/6.0); //General square slow sigma *aquela divisao por 3 pode mudar*... #pragma omp parallel for for (i = 0; i < num_active_cells; i++) { double x_prev = ac[i]->center.x; double y_prev = ac[i]->center.y; if ((x_prev>= X_left ) && (x_prev <= X_right) && (y_prev>= Y_down) && (y_prev<= Y_up)) { ac[i]->sigma.x = sigma_x * sigma_factor; ac[i]->sigma.y = sigma_y * sigma_factor; ac[i]->sigma.z = sigma_z * sigma_factor; } } //Vou recuparando os triangulos do square #pragma omp parallel for for (i = 0; i < num_active_cells; i++) { double x = ac[i]->center.x; double y = ac[i]->center.y; //Part 1 int mid_scar_Y = (Y_down + Y_up)/12.0; int Part1_x_right = X_left + 10.*(cell_length_x); int Part2_x_left = Part1_x_right + cell_length_x; if( (y<=(mid_scar_Y+(cell_length_y/2.))) && (y> (mid_scar_Y- (cell_length_y/2.))) && (x>= X_left) && (x<= X_right)) { ac[i]->sigma.x = sigma_x; ac[i]->sigma.y = sigma_y; ac[i]->sigma.z = sigma_z; } //Part 1.5 if( (y<=(mid_scar_Y+(cell_length_y))) && (y> (mid_scar_Y- 2.0*(cell_length_y))) && (x>= X_left) && (x<= X_left+5.0*cell_length_x)) //isto mudei { ac[i]->sigma.x = sigma_x; ac[i]->sigma.y = sigma_y; ac[i]->sigma.z = sigma_z; } //Part 2 int Part2_y_up = mid_scar_Y + (3.*cell_length_y); //original int Part2_y_down = mid_scar_Y - (2.*cell_length_y); //original //~ int Part2_y_up = mid_scar_Y + (20.*cell_length_y);//modifiquei //~ int Part2_y_down = mid_scar_Y - (20.*cell_length_y);//modifiquei //talvez colocar o de cima if( (x>= Part2_x_left) && (x<= X_right) && (y<= Part2_y_up ) &&(y> Part2_y_down)) { ac[i]->sigma.x = sigma_x; ac[i]->sigma.y = sigma_y; ac[i]->sigma.z = sigma_z; } //Part 3 up, m coeficiente angular int Part3_x_left = Part2_x_left + cell_length_x; int Part3_y_up = Part2_y_up; real m_up = (Y_up-Part3_y_up)/(X_right-Part3_x_left); int Part3_x_left_2 = (Part3_x_left + X_right)/2.0; if((x>=Part3_x_left) && (x <= X_right) && (y <= (m_up*(x-Part3_x_left)+Part3_y_up)) && (y>= Part3_y_up) ) { if(x>=Part3_x_left_2) { ac[i]->sigma.x = sigma_x*sigma_factor_2; ac[i]->sigma.y = sigma_y*sigma_factor_2; ac[i]->sigma.z = sigma_z*sigma_factor_2; } else { ac[i]->sigma.x = sigma_x; ac[i]->sigma.y = sigma_y; ac[i]->sigma.z = sigma_z; } } //Part 3 down, m coeficiente angular int Part3_y_down = Part2_y_down; real m_down = (Y_down - Part3_y_down)/(X_right-Part3_x_left); if((x>=Part3_x_left) && (x <= X_right) && (y >= (m_down*(x-Part3_x_left)+ Part3_y_down)) && (y<= Part3_y_down) && (y>=Y_down)) { if(x>=Part3_x_left_2) { ac[i]->sigma.x = sigma_x*sigma_factor_2; ac[i]->sigma.y = sigma_y*sigma_factor_2; ac[i]->sigma.z = sigma_z*sigma_factor_2; } else { ac[i]->sigma.x = sigma_x; ac[i]->sigma.y = sigma_y; ac[i]->sigma.z = sigma_z; } } //middle canal if ((y<=Part3_y_up) && (y>=Part3_y_down) && (x>=Part3_x_left_2) && (x<=X_right)) { ac[i]->sigma.x = sigma_x*sigma_factor_2; ac[i]->sigma.y = sigma_y*sigma_factor_2; ac[i]->sigma.z = sigma_z*sigma_factor_2; } } // Aqui termina a construcao dos triangulos #pragma omp parallel for for (i = 0; i < num_active_cells; i++) { // Computes and designates the flux due to south cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->south, the_solver->dt,'s'); // Computes and designates the flux due to north cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->north, the_solver->dt,'n'); // Computes and designates the flux due to east cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->east, the_solver->dt,'e'); // Computes and designates the flux due to west cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->west, the_solver->dt,'w'); // Computes and designates the flux due to front cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->front, the_solver->dt,'f'); // Computes and designates the flux due to back cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->back, the_solver->dt,'b'); } } ASSEMBLY_MATRIX(write_sigma_low_region_triangle_ddm_tiny) { uint32_t num_active_cells = the_grid->num_active_cells; struct cell_node **ac = the_grid->active_cells; struct cell_node *grid_cell; initialize_diagonal_elements(the_solver, the_grid); int i; real sigma_x = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_x, config->config_data, "sigma_x"); real sigma_y = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_y, config->config_data, "sigma_y"); real sigma_z = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_z, config->config_data, "sigma_z"); real cell_length_x = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_x, config->config_data, "cell_length_x"); real cell_length_y = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_y, config->config_data, "cell_length_y"); real cell_length_z = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_z, config->config_data, "cell_length_z"); real sigma_factor = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_factor, config->config_data, "sigma_factor"); real sigma_factor_2 = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_factor_2, config->config_data, "sigma_factor_2"); real side_length = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,side_length, config->config_data, "side_length"); char *new_fib_file = NULL; GET_PARAMETER_VALUE_CHAR_OR_REPORT_ERROR(new_fib_file, config->config_data, "rescaled_fibrosis_file"); //~ real scar_length = 0.0; //~ GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(scar_length, config->config_data, "scar_length"); //~ calculate_kappa_elements(the_grid,cell_length_x,cell_length_y,cell_length_z); //~ calculate_kappa_elements(the_solver,the_grid,cell_length_x,cell_length_y,cell_length_z); //~ bool inside; #pragma omp parallel for for (i = 0; i < num_active_cells; i++) { ac[i]->sigma.x = sigma_x; ac[i]->sigma.y = sigma_y; ac[i]->sigma.z = sigma_z; } printf("[!] Using DDM formulation\n"); printf("[X] Cell length = %.10lf || sigma_x = %.10lf || dx = %.10lf || kappa_x = %.10lf\n",\ cell_length_x,ac[0]->sigma.x,ac[0]->discretization.x,ac[0]->kappa.x); printf("[Y] Cell length = %.10lf || sigma_y = %.10lf || dy = %.10lf || kappa_y = %.10lf\n",\ cell_length_y,ac[0]->sigma.y,ac[0]->discretization.y,ac[0]->kappa.y); printf("[Z] Cell length = %.10lf || sigma_z = %.10lf || dz = %.10lf || kappa_z = %.10lf\n",\ cell_length_z,ac[0]->sigma.z,ac[0]->discretization.z,ac[0]->kappa.z); //regiao ao redor do meio com sigma menor// /*Aqui comeca a brincadeira de criar os triangulos * * Pensei em dividir em 3 partes a primeira uma barra * * 1 2 3 * ******* * ****** * ***** * **** * ** * * * 1 fazendo o canal * * ** * ** * ** * ** * ** * * 2 considerar a abertura de maneira que pegue 5 celulas * * * * * * * * * * * 3 pegar o triangulo * * **** * *** * ** * * * * Dai (1)+(2)+(3) eh a ahrea que desejamos * * */ // set the square scar mesh... //~ real X_left = side_length/3.0; //~ real X_right = (side_length/3.0+side_length/3.0); //~ real Y_down = side_length/3.0; //~ real Y_up = (side_length/3.0+side_length/3.0); //esquerda //~ real X_left = side_length/6.0; //~ real X_right = (side_length/3.0+side_length/3.0); real X_left = side_length/12.0; real X_right = (side_length/6.0+side_length/6.0); //~ real Y_down = side_length/6.0; real Y_down = 0.0; //~ real Y_up = (side_length/6.0+side_length/6.0+side_length/12.0); real Y_up = (side_length/6.0+side_length/6.0+side_length/6.0); //General square slow sigma *aquela divisao por 3 pode mudar*... #pragma omp parallel for for (i = 0; i < num_active_cells; i++) { double x_prev = ac[i]->center.x; double y_prev = ac[i]->center.y; if ((x_prev>= X_left ) && (x_prev <= X_right) && (y_prev>= Y_down) && (y_prev<= Y_up)) { ac[i]->sigma.x = sigma_x * sigma_factor; ac[i]->sigma.y = sigma_y * sigma_factor; ac[i]->sigma.z = sigma_z * sigma_factor; } } //Vou recuparando os triangulos do square #pragma omp parallel for for (i = 0; i < num_active_cells; i++) { double x = ac[i]->center.x; double y = ac[i]->center.y; //Part 1 int mid_scar_Y = (Y_down + Y_up)/12.0; int Part1_x_right = X_left + 10.*(cell_length_x); int Part2_x_left = Part1_x_right + cell_length_x; if( (y<=(mid_scar_Y+(cell_length_y/2.))) && (y> (mid_scar_Y- (cell_length_y/2.))) && (x>= X_left) && (x<= X_right)) { ac[i]->sigma.x = sigma_x; ac[i]->sigma.y = sigma_y; ac[i]->sigma.z = sigma_z; } //Part 1.5 if( (y<=(mid_scar_Y+(cell_length_y))) && (y> (mid_scar_Y- 2.0*(cell_length_y))) && (x>= X_left) && (x<= X_left+5.0*cell_length_x)) //isto mudei { ac[i]->sigma.x = sigma_x; ac[i]->sigma.y = sigma_y; ac[i]->sigma.z = sigma_z; } //~ //Part 2 int Part2_y_up = mid_scar_Y + (3.*cell_length_y); //original int Part2_y_down = mid_scar_Y - (2.*cell_length_y); //original //~ int Part2_y_up = mid_scar_Y + (20.*cell_length_y);//modifiquei //~ int Part2_y_down = mid_scar_Y - (20.*cell_length_y);//modifiquei //talvez colocar o de cima if( (x>= Part2_x_left) && (x<= X_right) && (y<= Part2_y_up ) &&(y> Part2_y_down)) { ac[i]->sigma.x = sigma_x; ac[i]->sigma.y = sigma_y; ac[i]->sigma.z = sigma_z; } //~ //Part 3 up, m coeficiente angular int Part3_x_left = Part2_x_left + cell_length_x; int Part3_y_up = Part2_y_up; real m_up = (Y_up-Part3_y_up)/(X_right-Part3_x_left); int Part3_x_left_2 = (Part3_x_left + X_right)/2.0; if((x>=Part3_x_left) && (x <= X_right) && (y <= (m_up*(x-Part3_x_left)+Part3_y_up)) && (y>= Part3_y_up) ) { if(x>=Part3_x_left_2) { ac[i]->sigma.x = sigma_x*sigma_factor_2; ac[i]->sigma.y = sigma_y*sigma_factor_2; ac[i]->sigma.z = sigma_z*sigma_factor_2; } else { ac[i]->sigma.x = sigma_x; ac[i]->sigma.y = sigma_y; ac[i]->sigma.z = sigma_z; } } //~ //Part 3 down, m coeficiente angular int Part3_y_down = Part2_y_down; real m_down = (Y_down - Part3_y_down)/(X_right-Part3_x_left); if((x>=Part3_x_left) && (x <= X_right) && (y >= (m_down*(x-Part3_x_left)+ Part3_y_down)) && (y<= Part3_y_down) && (y>=Y_down)) { if(x>=Part3_x_left_2) { ac[i]->sigma.x = sigma_x*sigma_factor_2; ac[i]->sigma.y = sigma_y*sigma_factor_2; ac[i]->sigma.z = sigma_z*sigma_factor_2; } else { ac[i]->sigma.x = sigma_x; ac[i]->sigma.y = sigma_y; ac[i]->sigma.z = sigma_z; } } //middle canal if ((y<=Part3_y_up) && (y>=Part3_y_down) && (x>=Part3_x_left_2) && (x<=X_right)) { ac[i]->sigma.x = sigma_x*sigma_factor_2; ac[i]->sigma.y = sigma_y*sigma_factor_2; ac[i]->sigma.z = sigma_z*sigma_factor_2; } } // Write the new grid configuration on the rescaled_fibrosis file FILE *fileW = fopen(new_fib_file, "w+"); grid_cell = the_grid->first_cell; while(grid_cell != 0) { if(grid_cell->active) { // We reescale the cell position using the 'rescale_factor' double center_x = grid_cell->center.x ; double center_y = grid_cell->center.y ; double center_z = grid_cell->center.z ; double dx = grid_cell->discretization.x; double dy = grid_cell->discretization.y; double dz = grid_cell->discretization.z; double w_sigma_x = grid_cell->sigma.x; double w_sigma_y = grid_cell->sigma.y; double w_sigma_z = grid_cell->sigma.z; // Then, we write only the fibrotic regions to the output file fprintf(fileW,"%g,%g,%g,%g,%g,%g,%g,%g,%g\n",center_x,center_y,center_z,dx/2.0,dy/2.0,dz/2.0,w_sigma_x,w_sigma_y,w_sigma_z); } grid_cell = grid_cell->next; } fclose(fileW); // We just leave the program after this ... print_to_stdout_and_file("[!] Finish writing fibrotic region file '%s'!\n",new_fib_file); exit(EXIT_SUCCESS); } ASSEMBLY_MATRIX (heterogenous_fibrotic_sigma_with_factor_ddm_assembly_matrix_add_sigma_reverse) { static bool sigma_initialized = false; uint32_t num_active_cells = the_grid->num_active_cells; struct cell_node **ac = the_grid->active_cells; initialize_diagonal_elements(the_solver, the_grid); char *fib_file = NULL; GET_PARAMETER_VALUE_CHAR_OR_REPORT_ERROR(fib_file, config->config_data, "fibrosis_file"); int fib_size = 0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(int,fib_size, config->config_data, "size"); real sigma_x = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_x, config->config_data, "sigma_x"); real sigma_y = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_y, config->config_data, "sigma_y"); real sigma_z = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_z, config->config_data, "sigma_z"); real cell_length_x = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_x, config->config_data, "cell_length_x"); real cell_length_y = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_y, config->config_data, "cell_length_y"); real cell_length_z = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_z, config->config_data, "cell_length_z"); real sigma_factor = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_factor, config->config_data, "sigma_factor"); // Calculate the kappa values on each cell of th grid calculate_kappa_elements(the_solver,the_grid,cell_length_x,cell_length_y,cell_length_z); if(!sigma_initialized) { #pragma omp parallel for for (uint32_t i = 0; i < num_active_cells; i++) { ac[i]->sigma.x = sigma_x; ac[i]->sigma.y = sigma_y; ac[i]->sigma.z = sigma_z; } sigma_initialized = true; } // Read and store the fibrosis locations FILE *file = fopen(fib_file, "r"); if(!file) { printf("Error opening file %s!!\n", fib_file); exit(0); } real_cpu **scar_mesh = (real_cpu **)malloc(sizeof(real_cpu *) * fib_size); for(int i = 0; i < fib_size; i++) { scar_mesh[i] = (real_cpu *)malloc(sizeof(real_cpu) * 9); if(scar_mesh[i] == NULL) { printf("Failed to allocate memory\n"); exit(0); } } uint32_t i = 0; while (fscanf(file, "%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf\n", &scar_mesh[i][0], &scar_mesh[i][1], &scar_mesh[i][2], &scar_mesh[i][3],\ &scar_mesh[i][4], &scar_mesh[i][5], &scar_mesh[i][6], &scar_mesh[i][7],\ &scar_mesh[i][8]) != EOF) { i++; } fclose(file); uint32_t num_fibrotic_regions = i; // Pass through all the cells of the grid and check if its center is inside the current // fibrotic region struct cell_node *grid_cell = the_grid->first_cell; real aux_sigma_load_x; real aux_sigma_load_y; real aux_sigma_load_z; while(grid_cell != 0) { if (grid_cell->active) { real_cpu center_x = grid_cell->center.x; real_cpu center_y = grid_cell->center.y; real_cpu half_dx = grid_cell->discretization.x/2.0; real_cpu half_dy = grid_cell->discretization.y/2.0; aux_sigma_load_x = grid_cell->sigma.x; aux_sigma_load_y = grid_cell->sigma.y; aux_sigma_load_z = grid_cell->sigma.z; struct point_3d p; struct point_3d q; p.x = center_y + half_dy; p.y = center_y - half_dy; q.x = center_x + half_dx; q.y = center_x - half_dx; for (int j = 0; j < num_fibrotic_regions; j++) { real_cpu b_center_x = scar_mesh[j][0]; real_cpu b_center_y = scar_mesh[j][1]; real_cpu b_sigma_x = scar_mesh[j][6]; real_cpu b_sigma_y = scar_mesh[j][7]; real_cpu b_sigma_z = scar_mesh[j][8]; if (b_center_x > q.y && b_center_x < q.x && b_center_y > p.y && b_center_y < p.x) { aux_sigma_load_x = b_sigma_x; aux_sigma_load_y = b_sigma_y; aux_sigma_load_z = b_sigma_z; //armazenar os valores dos sigmas ao redor e utilizar a meia harmonica para resolvers } } //~ grid_cell->sigma.x = 2.0*((sigma_x * aux_sigma_load_x)/(sigma_x + aux_sigma_load_x)); //~ grid_cell->sigma.y = 2.0*((sigma_y * aux_sigma_load_y)/(sigma_y + aux_sigma_load_y)); //~ grid_cell->sigma.z = 2.0*((sigma_z * aux_sigma_load_z)/(sigma_z + aux_sigma_load_z)); grid_cell->sigma.x = aux_sigma_load_x; grid_cell->sigma.y = aux_sigma_load_y; grid_cell->sigma.z = aux_sigma_load_z; } grid_cell = grid_cell->next; } printf("[!] Using DDM formulation\n"); printf("[X] Cell length = %.10lf || sigma_x = %.10lf || dx = %.10lf || kappa_x = %.10lf\n",\ cell_length_x,ac[0]->sigma.x,ac[0]->discretization.x,ac[0]->kappa.x); printf("[Y] Cell length = %.10lf || sigma_y = %.10lf || dy = %.10lf || kappa_y = %.10lf\n",\ cell_length_y,ac[0]->sigma.y,ac[0]->discretization.y,ac[0]->kappa.y); printf("[Z] Cell length = %.10lf || sigma_z = %.10lf || dz = %.10lf || kappa_z = %.10lf\n",\ cell_length_z,ac[0]->sigma.z,ac[0]->discretization.z,ac[0]->kappa.z); #pragma omp parallel for for(int i = 0; i < num_active_cells; i++) { // Computes and designates the flux due to south cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->south, the_solver->dt,'s'); // Computes and designates the flux due to north cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->north, the_solver->dt,'n'); // Computes and designates the flux due to east cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->east, the_solver->dt,'e'); // Computes and designates the flux due to west cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->west, the_solver->dt,'w'); // Computes and designates the flux due to front cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->front, the_solver->dt,'f'); // Computes and designates the flux due to back cells. fill_discretization_matrix_elements_ddm(ac[i], ac[i]->back, the_solver->dt,'b'); } for(int k = 0; k < fib_size; k++) { free(scar_mesh[k]); } free(scar_mesh); } ASSEMBLY_MATRIX(heterogenous_fibrotic_region_file_write_using_seed) { static bool sigma_initialized = false; int num; uint32_t num_active_cells = the_grid->num_active_cells; struct cell_node **ac = the_grid->active_cells; struct cell_node *grid_cell; initialize_diagonal_elements(the_solver, the_grid); real sigma_x = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_x, config->config_data, "sigma_x"); real sigma_y = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_y, config->config_data, "sigma_y"); real sigma_z = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_z, config->config_data, "sigma_z"); real sigma_factor = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_factor, config->config_data, "sigma_factor"); real sigma_factor_2 = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_factor_2, config->config_data, "sigma_factor_2"); real_cpu phi = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,phi, config->config_data, "phi"); real_cpu phi_2 = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,phi_2, config->config_data, "phi_2"); unsigned seed = 0; GET_PARAMETER_NUMERIC_VALUE_OR_USE_DEFAULT(unsigned,seed, config->config_data, "seed"); char *new_fib_file = NULL; GET_PARAMETER_VALUE_CHAR_OR_REPORT_ERROR(new_fib_file, config->config_data, "rescaled_fibrosis_file"); real rescale_factor = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,rescale_factor, config->config_data, "rescale_factor"); real x_shift = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,x_shift, config->config_data, "x_shift"); real y_shift = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,y_shift, config->config_data, "y_shift"); // Write the new fibrotic region file FILE *fileW = fopen(new_fib_file, "w+"); grid_cell = the_grid->first_cell; // Initialize the random the generator with the same seed used by the original model srand(seed); while(grid_cell != 0) { if(grid_cell->active) { real_cpu p = (real_cpu)(rand()) / (RAND_MAX); if(p < phi) { // We reescale the cell position using the 'rescale_factor' grid_cell->sigma.x = sigma_x * sigma_factor_2; grid_cell->sigma.y = sigma_y * sigma_factor_2; grid_cell->sigma.z = sigma_z * sigma_factor_2; // Then, we write only the fibrotic regions to the output file } else { if((p>=phi)&&(p<=phi_2)) { grid_cell->sigma.x = sigma_x * sigma_factor; grid_cell->sigma.y = sigma_y * sigma_factor; grid_cell->sigma.z = sigma_z * sigma_factor; } else { grid_cell->sigma.x = sigma_x; grid_cell->sigma.y = sigma_y; grid_cell->sigma.z = sigma_z; } } double center_x = grid_cell->center.x; double center_y = grid_cell->center.y; double center_z = grid_cell->center.z; double dx = grid_cell->discretization.x ; double dy = grid_cell->discretization.y ; double dz = grid_cell->discretization.z ; center_x = center_x + x_shift; center_y = center_y + y_shift; fprintf(fileW,"%g,%g,%g,%g,%g,%g,%g,%g,%g\n",center_x,center_y,center_z,dx/2.0,dy/2.0,dz/2.0,grid_cell->sigma.x,grid_cell->sigma.y,grid_cell->sigma.z); } grid_cell = grid_cell->next; } fclose(fileW); // We just leave the program after this ... print_to_stdout_and_file("[!] Finish writing fibrotic region file '%s'!\n",new_fib_file); exit(EXIT_SUCCESS); } ASSEMBLY_MATRIX(sigma_low_region_triangle_ddm_tiny_random_write) { uint32_t num_active_cells = the_grid->num_active_cells; struct cell_node **ac = the_grid->active_cells; initialize_diagonal_elements(the_solver, the_grid); int i; char *fib_file_1 = NULL; GET_PARAMETER_VALUE_CHAR_OR_REPORT_ERROR(fib_file_1, config->config_data, "fibrosis_file_1"); char *fib_file_2 = NULL; GET_PARAMETER_VALUE_CHAR_OR_REPORT_ERROR(fib_file_2, config->config_data, "fibrosis_file_2"); char *fib_file_3 = NULL; GET_PARAMETER_VALUE_CHAR_OR_REPORT_ERROR(fib_file_3, config->config_data, "fibrosis_file_3"); char *new_fib_file = NULL; GET_PARAMETER_VALUE_CHAR_OR_REPORT_ERROR(new_fib_file, config->config_data, "new_fib_file"); int fib_size = 0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(int,fib_size, config->config_data, "size"); real sigma_x = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_x, config->config_data, "sigma_x"); real sigma_y = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_y, config->config_data, "sigma_y"); real sigma_z = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_z, config->config_data, "sigma_z"); real cell_length_x = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_x, config->config_data, "cell_length_x"); real cell_length_y = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_y, config->config_data, "cell_length_y"); real cell_length_z = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,cell_length_z, config->config_data, "cell_length_z"); real sigma_factor = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_factor, config->config_data, "sigma_factor"); real sigma_factor_2 = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,sigma_factor_2, config->config_data, "sigma_factor_2"); real side_length = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real,side_length, config->config_data, "side_length"); calculate_kappa_elements(the_solver,the_grid,cell_length_x,cell_length_y,cell_length_z); #pragma omp parallel for for (i = 0; i < num_active_cells; i++) { ac[i]->sigma.x = sigma_x; ac[i]->sigma.y = sigma_y; ac[i]->sigma.z = sigma_z; } printf("[!] Using DDM formulation\n"); printf("[X] Cell length = %.10lf || sigma_x = %.10lf || dx = %.10lf || kappa_x = %.10lf\n",\ cell_length_x,ac[0]->sigma.x,ac[0]->discretization.x,ac[0]->kappa.x); printf("[Y] Cell length = %.10lf || sigma_y = %.10lf || dy = %.10lf || kappa_y = %.10lf\n",\ cell_length_y,ac[0]->sigma.y,ac[0]->discretization.y,ac[0]->kappa.y); printf("[Z] Cell length = %.10lf || sigma_z = %.10lf || dz = %.10lf || kappa_z = %.10lf\n",\ cell_length_z,ac[0]->sigma.z,ac[0]->discretization.z,ac[0]->kappa.z); // Allocate memory to store the grid configuration real_cpu **scar_mesh = (real_cpu **)malloc(sizeof(real_cpu *) * fib_size); for(int i = 0; i < fib_size; i++) { scar_mesh[i] = (real_cpu *)malloc(sizeof(real_cpu) * 9); if(scar_mesh[i] == NULL) { printf("Failed to allocate memory\n"); exit(0); } } FILE *file; i = 0; // Read the FIRST fibrosis file file = fopen(fib_file_1, "r"); if(!file) { printf("Error opening file %s!!\n", fib_file_1); exit(0); } while (fscanf(file, "%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf\n", &scar_mesh[i][0], &scar_mesh[i][1], &scar_mesh[i][2], &scar_mesh[i][3],\ &scar_mesh[i][4], &scar_mesh[i][5], &scar_mesh[i][6], &scar_mesh[i][7],\ &scar_mesh[i][8]) != EOF) { i++; } fclose(file); // Read the SECOND fibrosis file file = fopen(fib_file_2, "r"); if(!file) { printf("Error opening file %s!!\n", fib_file_2); exit(0); } while (fscanf(file, "%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf\n", &scar_mesh[i][0], &scar_mesh[i][1], &scar_mesh[i][2], &scar_mesh[i][3],\ &scar_mesh[i][4], &scar_mesh[i][5], &scar_mesh[i][6], &scar_mesh[i][7],\ &scar_mesh[i][8]) != EOF) { i++; } fclose(file); // Read the THIRD fibrosis file file = fopen(fib_file_3, "r"); if(!file) { printf("Error opening file %s!!\n", fib_file_3); exit(0); } while (fscanf(file, "%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf\n", &scar_mesh[i][0], &scar_mesh[i][1], &scar_mesh[i][2], &scar_mesh[i][3],\ &scar_mesh[i][4], &scar_mesh[i][5], &scar_mesh[i][6], &scar_mesh[i][7],\ &scar_mesh[i][8]) != EOF) { i++; } fclose(file); uint32_t num_fibrotic_regions = i; // Update the cells that are inside of the scar regions #pragma omp parallel for for(int j = 0; j < num_fibrotic_regions; j++) { struct cell_node *grid_cell = the_grid->first_cell; real_cpu b_center_x = scar_mesh[j][0]; real_cpu b_center_y = scar_mesh[j][1]; real_cpu b_h_dx = scar_mesh[j][3]; real_cpu b_h_dy = scar_mesh[j][4]; real aux_sigma_load_x = scar_mesh[j][6]; real aux_sigma_load_y = scar_mesh[j][7]; while(grid_cell != 0) { if (grid_cell->active) { real_cpu center_x = grid_cell->center.x; real_cpu center_y = grid_cell->center.y; real_cpu half_dy = grid_cell->discretization.y/2.0; real_cpu half_dx = grid_cell->discretization.x/2.0; struct point_3d p; struct point_3d q; p.x = b_center_y + b_h_dy; p.y = b_center_y - b_h_dy; q.x = b_center_x + b_h_dx; q.y = b_center_x - b_h_dx; // Check if the current cell is inside the fibrotic region if (center_x > q.y && center_x < q.x && center_y > p.y && center_y < p.x) { grid_cell->sigma.x = aux_sigma_load_x; grid_cell->sigma.y = aux_sigma_load_y; } } grid_cell = grid_cell->next; } } // Until here, we have a grid with both the column and horizontal regions ... // Start building the channel block real X_left = side_length/12.0; real X_left_1 = X_left + side_length/12.0; real X_right = 3000; real Y_down = 0.0; real Y_up = 1200; #pragma omp parallel for for (i = 0; i < num_active_cells; i++) { double x = ac[i]->center.x; double y = ac[i]->center.y; // Region 1 starts here ... //Part 1 - (Channel construction) int mid_scar_Y = (Y_down + 7500)/12.0; int X_right_1 = X_left + cell_length_x; int Part1_x_right = X_left + 10.*(cell_length_x); int Part2_x_left = Part1_x_right + cell_length_x; // Decrease the conductivity of every cell inside the region create_sigma_low_block(ac[i],X_left,Part1_x_right,Y_down,Y_up,sigma_x,sigma_y,sigma_z,sigma_factor); // Create the little channel create_sigma_low_block(ac[i],X_left,Part1_x_right,mid_scar_Y - cell_length_y/2.,mid_scar_Y+(cell_length_y/4.), sigma_x,sigma_y,sigma_z,1.0 ); create_sigma_low_block(ac[i],X_left,X_left+2.0*cell_length_x,mid_scar_Y- 3.0*(cell_length_y),mid_scar_Y, sigma_x,sigma_y,sigma_z,1.0); //Part 2 - (Channel opening) int Part2_y_up = mid_scar_Y + (3.*cell_length_y); //original int Part2_y_down = mid_scar_Y - (4.*cell_length_y); //original int X_left_2 = X_left+5.0*cell_length_x; int X_right_2 = X_left+10.0*cell_length_x; create_sigma_low_block(ac[i], X_left_2,X_right_2,Part2_y_down,Part2_y_up, sigma_x,sigma_y,sigma_z,1.0); //Part 3 - triangle opening // First step int X_left_3 = X_left_2 + cell_length_x; int X_right_3 = X_right_2; int Y_up_3 = Part2_y_up + 5*cell_length_y; int Y_down_3 = Part2_y_down - 5*cell_length_y; real_cpu m_up = (Y_up_3-Part2_y_up)/(X_right_3-X_left_3); create_sigma_low_block(ac[i], X_left_3,X_right_3,Y_down_3,Y_up_3,sigma_x,sigma_y,sigma_z,1.0); // Second step int X_left_4 = X_left_3 + cell_length_x; int X_right_4 = X_right_3; int Y_up_4 = Y_up_3 + 5*cell_length_y; int Y_down_4 = Y_down_3 - 5*cell_length_y; create_sigma_low_block(ac[i], X_left_4,X_right_4,Y_down_4,Y_up_4,sigma_x,sigma_y,sigma_z,1.0); // Third step int X_left_5 = X_left_4 + cell_length_x; int X_right_5 = X_right_4; int Y_up_5 = Y_up_4 + 5*cell_length_y; int Y_down_5 = Y_down_4 - 5*cell_length_y; create_sigma_low_block(ac[i], X_left_5,X_right_5,Y_down_5,Y_up_5,sigma_x,sigma_y,sigma_z,1.0); // Fourth step int X_left_6 = X_left_5 + cell_length_x; int X_right_6 = X_right_5; int Y_up_6 = Y_up_5 + 5*cell_length_y; int Y_down_6 = Y_down_5 - 5*cell_length_y; create_sigma_low_block(ac[i], X_left_6,X_right_6,Y_down_6,Y_up_6,sigma_x,sigma_y,sigma_z,1.0); // Region 2 starts here ... // The horizontal barrier int X_left_7 = 1900; int X_right_7 = 3900; int Y_down_7 = 1500; int Y_up_7 = 1900; create_sigma_low_block(ac[i], X_left_7,X_right_7,Y_down_7,Y_up_7,sigma_x,sigma_y,sigma_z,sigma_factor_2); // The vertical barrier int X_left_8 = 3500; int X_right_8 = 3900; int Y_down_8 = 0; int Y_up_8 = 1700; create_sigma_low_block(ac[i], X_left_8,X_right_8,Y_down_8,Y_up_8,sigma_x,sigma_y,sigma_z,sigma_factor_2); // Region 3 starts here ... // First upper block int X_left_9 = 1900; int X_right_9 = 2300; int Y_down_9 = 7900; int Y_up_9 = 8300; create_sigma_low_block(ac[i], X_left_9,X_right_9,Y_down_9,Y_up_9,sigma_x,sigma_y,sigma_z,sigma_factor_2); // Second upper block int X_left_9_1 = 2600; int X_right_9_1 = 3000; int Y_down_9_1 = 7900; int Y_up_9_1 = 8300; create_sigma_low_block(ac[i], X_left_9_1,X_right_9_1,Y_down_9_1,Y_up_9_1,sigma_x,sigma_y,sigma_z,sigma_factor_2); // Third upper block (reset) int X_left_10 = 2600; int X_right_10 = 3000; int Y_down_10 = 8600; int Y_up_10 = 9000; create_sigma_low_block(ac[i], X_left_10,X_right_10,Y_down_10,Y_up_10,sigma_x,sigma_y,sigma_z,1.0); // Fourth upper block int X_left_11 = 3800; int X_right_11 = 4200; int Y_down_11 = 8200; int Y_up_11 = 8600; create_sigma_low_block(ac[i], X_left_11,X_right_11,Y_down_11,Y_up_11,sigma_x,sigma_y,sigma_z,sigma_factor_2); } // Write the grid configuration to an output file FILE *fileW = fopen(new_fib_file, "w+"); struct cell_node *grid_cell = the_grid->first_cell; // Initialize the random the generator with the same seed used by the original model while(grid_cell != 0) { if(grid_cell->active) { double center_x = grid_cell->center.x ; double center_y = grid_cell->center.y ; double center_z = grid_cell->center.z ; double dx = grid_cell->discretization.x; double dy = grid_cell->discretization.y; double dz = grid_cell->discretization.z; double w_sigma_x = grid_cell->sigma.x; double w_sigma_y = grid_cell->sigma.y; double w_sigma_z = grid_cell->sigma.z; fprintf(fileW,"%g,%g,%g,%g,%g,%g,%g,%g,%g\n",center_x,center_y,center_z,dx/2.0,dy/2.0,dz/2.0,w_sigma_x,w_sigma_y,w_sigma_z); } grid_cell = grid_cell->next; } fclose(fileW); // We just leave the program after this ... print_to_stdout_and_file("[!] Finish writing fibrotic region file '%s'!\n",new_fib_file); exit(EXIT_SUCCESS); }
PoW.c
/* Copyright 2016-2018 The Ulord Core Foundation */ #include "PoW.h" #include <stdio.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include <assert.h> // #include <omp.h> #include "my_time.h" #include "common.h" #include "my_rand48_r.h" #include "oneWayFunction.h" // #define SSE_VERSION /* * Step 1: Initialize working memory. */ void initWorkMemory(uint8_t *input, uint32_t inputLen, uint8_t *Maddr, const uint32_t K) { uint32_t i, j; uint8_t a[OUTPUT_LEN], b[OUTPUT_LEN]; funcInfor[0].func(input, inputLen, a); uint64_t randSeed[4] = {0, 0, 0, 0}; #ifndef SSE_VERSION struct my_rand48_data randBuffer[4]; #else struct vrand48_data randBuffer[2]; #endif const uint32_t iterNum = WORK_MEMORY_SIZE >> 5; for (i = 0; i < iterNum; ++i) { if (i % K) { #ifndef SSE_VERSION uint64_t num = 0; for (j = 0; j < 4; ++j) { my_rand64_r(&randBuffer[j], &num); memcpy(b + (j << 3), (uint8_t *)&num, 8*sizeof(uint8_t)); } #else vrand64(b, randBuffer); #endif uint8_t shift_num; uint8_t result[OUTPUT_LEN]; reduce_bit((uint8_t *)&i, 4, (uint8_t *)&shift_num, 8); rrs(b, OUTPUT_LEN, result, shift_num); memcpy(Maddr + (i << 5), result, OUTPUT_LEN*sizeof(uint8_t)); for (j = 0; j < 32; ++j) { a[j] ^= result[j]; } } else { uint8_t t = 0, shift_num = 0; reduce_bit(a, 32, (uint8_t *)&t, 8); t = (t & 0x0f) ^ (t >> 4); reduce_bit((uint8_t *)&i, 4, (uint8_t *)&shift_num, 8); uint8_t a_rrs[INPUT_LEN]; rrs(a, OUTPUT_LEN, a_rrs, shift_num); funcInfor[t].func(a_rrs, 32, a); reduce_bit(a, 8, (uint8_t *)&randSeed[0], 48); reduce_bit(a + 8, 8, (uint8_t *)&randSeed[1], 48); reduce_bit(a + 16, 8, (uint8_t *)&randSeed[2], 48); reduce_bit(a + 24, 8, (uint8_t *)&randSeed[3], 48); #ifndef SSE_VERSION my_seed48_r(randSeed[0], &randBuffer[0]); my_seed48_r(randSeed[1], &randBuffer[1]); my_seed48_r(randSeed[2], &randBuffer[2]); my_seed48_r(randSeed[3], &randBuffer[3]); #else vseed48(randSeed , &randBuffer[0]); vseed48(randSeed + 2, &randBuffer[1]); #endif memcpy(Maddr + (i << 5), a, 32*sizeof(uint8_t)); } } } /* * Step 2: Modify the working memory contents. */ void modifyWorkMemory(uint8_t *Maddr, const uint32_t L, const uint32_t C, uint8_t *result) { uint32_t i, j; uint8_t a[OUTPUT_LEN], b[64]; funcInfor[0].func(Maddr + WORK_MEMORY_SIZE - 32, 32, a); memcpy(result, a, OUTPUT_LEN*sizeof(uint8_t)); uint64_t r = 0; reduce_bit(a, 32, (uint8_t *)&r, 64); const uint32_t iterNum = L << 6; for (i = 0; i < C; ++i) { uint64_t randSeed = 0; reduce_bit(a, 32, (uint8_t *)&randSeed, 48); struct my_rand48_data randBuffer; my_seed48_r(randSeed, &randBuffer); uint8_t t1, t2, s; uint64_t randNum = 0, base = 0; for (j = 0; j < iterNum; ++j) { my_rand48_r(&randBuffer, &randNum); base = randNum + r; uint64_t offset = 0; reduce_bit((uint8_t *)&r, 8, (uint8_t *)&offset, 8); offset = (offset << 8) + 1; uint64_t addr1 = (base + WORK_MEMORY_SIZE - offset) % WORK_MEMORY_SIZE; uint64_t addr2 = (base + offset) % WORK_MEMORY_SIZE; t1 = Maddr[addr1]; t2 = Maddr[addr2]; s = a[j & 0x1f]; Maddr[addr1] = t2 ^ s; Maddr[addr2] = t1 ^ s; b[j & 0x3f] = t1 ^ t2; r = r + s + t1 + t2; } uint8_t t = 0; reduce_bit((uint8_t *)&r, 8, (uint8_t *)&t, 8); t = (t & 0x0f) ^ (t >> 4); reduce_bit(b, 64, a, 256); uint8_t shift_num = 0; uint64_t ir = r + i; reduce_bit((uint8_t *)&ir, 8, (uint8_t *)&shift_num, 8); uint8_t a_rrs[INPUT_LEN]; rrs(a, OUTPUT_LEN, a_rrs, shift_num); funcInfor[t].func(a_rrs, 32, a); for (j = 0; j < OUTPUT_LEN; ++j) { result[j] ^= a[j]; } } } /* * Step 3: Calculate the final result. */ void calculateFinalResult(uint8_t *Maddr, uint8_t *c, const uint32_t D, uint8_t *result) { uint32_t i = 0, j = 0, k = 0; memcpy(result, c, OUTPUT_LEN*sizeof(uint8_t)); const uint32_t num = (WORK_MEMORY_SIZE >> 5) - 1; uint32_t it = 0; uint8_t result_rrs[OUTPUT_LEN]; while(1) { uint8_t t = 0, shift_num = 0; uint32_t d = 0; reduce_bit(result, 32, (uint8_t *)&t, 8); t = (t & 0x0f) ^ (t >> 4); reduce_bit(result, 32, (uint8_t *)&d, D); ++d; for (j = 0; j < d; ++j) { uint32_t index = i << 5; for (k = 0; k < 32; ++k) { result[k] ^= Maddr[index + k]; } ++i; if (i == num) { it = i + t; reduce_bit((uint8_t *)&it, 4, (uint8_t *)&shift_num, 8); rrs(result, OUTPUT_LEN, result_rrs, shift_num); funcInfor[0].func(result_rrs, 32, result); return; } } it = t + i; reduce_bit((uint8_t *)&it, 4, (uint8_t *)&shift_num, 8); rrs(result, OUTPUT_LEN, result_rrs, shift_num); funcInfor[t].func(result_rrs, 32, result); } } /* * Correctness & Performance test for Proof of work */ /* void testPowFunction(uint8_t *mess, uint32_t messLen, const int64_t iterNum) { int64_t j; uint32_t inputLen = messLen; uint8_t input[INPUT_LEN], output[OUTPUT_LEN]; memset(input, 0, INPUT_LEN*sizeof(uint8_t)); memcpy(input, mess, messLen*sizeof(char)); // Init all one-way function initOneWayFunction(); uint8_t *Maddr = (uint8_t *)malloc(64 * WORK_MEMORY_SIZE*sizeof(uint8_t)); assert(NULL != Maddr); memset(Maddr, 0, 64 * WORK_MEMORY_SIZE*sizeof(uint8_t)); printf("****************************** Correctness test (PoW function) ******************************\n"); printf("Test message: %s\n", mess); powFunction(input, inputLen, Maddr, output); view_data_u8("PoW", output, OUTPUT_LEN); printf("*********************************************************************************************\n"); printf("*************************************************** Performance test (PoW function) ***************************************************\n"); uint8_t *result = (uint8_t *)malloc(iterNum * OUTPUT_LEN * sizeof(uint8_t)); assert(NULL != result); memset(result, 0, iterNum * OUTPUT_LEN * sizeof(uint8_t)); uint32_t threadNumArr[] = {1, 4, 8, 12, 16, 20, 24, 32, 48, 64}; uint32_t threadNumTypes = sizeof(threadNumArr) / sizeof(uint32_t); printf(" %-18s", "Algorithm"); for (uint32_t ix = 0; ix < threadNumTypes; ++ix) printf("%12d", threadNumArr[ix]); printf("\n"); printf("00 %-18s\t", "PoW"); for (uint32_t ix = 0; ix < threadNumTypes; ++ix) { omp_set_num_threads(threadNumArr[ix]); double startTime = get_wall_time(); if (threadNumArr[ix] == 1) { for (j = 0; j < iterNum; ++j) { powFunction(input, inputLen, Maddr, result + j * OUTPUT_LEN); } } else { #pragma omp parallel for firstprivate(input), private(j) shared(result) for (j = 0; j < iterNum; ++j) { powFunction(input, inputLen, Maddr + omp_get_thread_num() * WORK_MEMORY_SIZE, result + j * OUTPUT_LEN); } } double endTime = get_wall_time(); double costTime = endTime - startTime; printf("%5.0f bps ", iterNum / costTime); fflush(stdout); // Check result for (j = 0; j < iterNum; j += 1) { if (memcmp(output, result + j * OUTPUT_LEN, OUTPUT_LEN)) { printf("Thread num: %d, j: %ld\n", threadNumArr[ix], j); view_data_u8("output", output, OUTPUT_LEN); view_data_u8("result", result + j * OUTPUT_LEN, OUTPUT_LEN); abort(); } } } printf("\n"); printf("***************************************************************************************************************************************\n"); if (NULL != result) { free(result); result = NULL; } if (NULL != Maddr) { free(Maddr); Maddr = NULL; } } */ #define OUTPUT_BUFFER_SIZE (32 * 1024UL * 1024UL) #define MAX_TEST_INPUT_LEN 140 #define MAX_OUT_FILE_NAME_LEN 25 const char testInputCase[][MAX_TEST_INPUT_LEN] = { "", "HelloWorld", "0123456789" }; void powNistTest(const char *outFileName) { const uint64_t iterNum = 1024UL * 1024UL; // const uint64_t iterNum = 1024UL; uint8_t *outputBuffer = (uint8_t *)malloc(OUTPUT_BUFFER_SIZE * sizeof(uint8_t)); assert(NULL != outputBuffer); memset(outputBuffer, 0, OUTPUT_BUFFER_SIZE * sizeof(uint8_t)); uint8_t *Maddr = (uint8_t *)malloc(WORK_MEMORY_SIZE*sizeof(uint8_t)); assert(NULL != Maddr); memset(Maddr, 0, WORK_MEMORY_SIZE*sizeof(uint8_t)); initOneWayFunction(); uint32_t testInputCaseNum = sizeof(testInputCase) / sizeof(const char [MAX_TEST_INPUT_LEN]); for (uint32_t testCaseIx = 0; testCaseIx < testInputCaseNum; ++testCaseIx) { char curOutFileName[MAX_OUT_FILE_NAME_LEN] = ""; sprintf(curOutFileName, "%s-%u.txt", outFileName, testCaseIx); FILE *fp = NULL; if (NULL != (fp = fopen(curOutFileName, "wb"))) { const uint32_t testInputCaseLen = strlen((char *)testInputCase[testCaseIx]); uint8_t input[MAX_TEST_INPUT_LEN]; memset(input, 0, MAX_TEST_INPUT_LEN*sizeof(uint8_t)); memcpy(input, testInputCase[testCaseIx], testInputCaseLen*sizeof(uint8_t)); double startTime = get_wall_time(); powFunction(input, testInputCaseLen, Maddr, outputBuffer); for (uint64_t i = 1, j = 0; i < iterNum; ++i) { memcpy(input, outputBuffer + j, OUTPUT_LEN * sizeof(uint32_t)); j += OUTPUT_LEN; powFunction(input, OUTPUT_LEN, Maddr, outputBuffer + j); /* if (j == OUTPUT_BUFFER_SIZE) { fwrite(outputBuffer, sizeof(uint8_t), OUTPUT_BUFFER_SIZE / sizeof(uint8_t), fp); j = 0; } */ } double endTime = get_wall_time(); double costTime = endTime - startTime; fprintf(stdout, "TestCaseIx: %d, Input: %s, IterNum: %lu, Time: %4.2f, Performance: %5.2f bps\n", testCaseIx, \ testInputCase[testCaseIx], iterNum, costTime, ((double)(iterNum * OUTPUT_LEN)) / costTime); fflush(stdout); fwrite(outputBuffer, sizeof(uint8_t), OUTPUT_BUFFER_SIZE / sizeof(uint8_t), fp); fclose(fp); } else { fprintf(stderr, "Error: Open %s failed!\n", curOutFileName); abort(); } } if (NULL != outputBuffer) { free(outputBuffer); outputBuffer = NULL; } if (NULL != Maddr) { free(Maddr); Maddr = NULL; } }
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-2018 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 128 #define MaxBezierCoordinates 4194304 #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 Image *,const DrawInfo *,const PrimitiveInfo *); static size_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->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) { register ssize_t x; for (x=0; fabs(draw_info->dash_pattern[x]) >= MagickEpsilon; x++) ; clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) (x+4), sizeof(*clone_info->dash_pattern)); if (clone_info->dash_pattern == (double *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) memcpy(clone_info->dash_pattern,draw_info->dash_pattern,(size_t) (x+4)*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) % % A description of each parameter follows: % % o Method 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. % % */ #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); \ } register 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) { register EdgeInfo *p; register 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; register 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) { long direction, next_direction; PointInfo point, *points; PolygonInfo *polygon_info; SegmentInfo bounds; register 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) return((PolygonInfo *) NULL); number_edges=16; polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory(number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); (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) return((PolygonInfo *) NULL); } 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++; } if (points == (PointInfo *) NULL) { number_points=16; points=(PointInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) return((PolygonInfo *) NULL); } 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) return((PolygonInfo *) NULL); } 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; number_points=16; points=(PointInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) return((PolygonInfo *) NULL); 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) return((PolygonInfo *) NULL); } 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) return((PolygonInfo *) NULL); } 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; ghostline=MagickFalse; edge++; } } polygon_info->number_edges=edge; 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) % % A description of each parameter follows: % % o Method 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) { register 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) { MagickBooleanType closed_subpath; PathInfo *path_info; PathInfoCode code; PointInfo p, q; register 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) 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->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 e s t r o y E d g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyEdge() destroys the specified polygon edge. % % The format of the DestroyEdge method is: % % ssize_t DestroyEdge(PolygonInfo *polygon_info,const int edge) % % A description of each parameter follows: % % o polygon_info: Specifies a pointer to an PolygonInfo structure. % % o edge: the polygon edge number to destroy. % */ static size_t DestroyEdge(PolygonInfo *polygon_info, const size_t edge) { assert(edge < polygon_info->number_edges); polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory( polygon_info->edges[edge].points); polygon_info->number_edges--; if (edge < 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); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P o l y g o n I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPolygonInfo() destroys the PolygonInfo data structure. % % The format of the DestroyPolygonInfo method is: % % PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info) % % A description of each parameter follows: % % o polygon_info: Specifies a pointer to an PolygonInfo structure. % */ static PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info) { register ssize_t i; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) 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)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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; register 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; register 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=(ssize_t) ceil(edge.y1-0.5); stop=(ssize_t) 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; register ssize_t x; register Quantum *magick_restrict q; SegmentInfo inverse_edge; ssize_t x_offset; inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge); if (inverse_edge.x2 < inverse_edge.x1) continue; q=GetCacheViewAuthenticPixels(image_view,(ssize_t) ceil(inverse_edge.x1- 0.5),y,(size_t) (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=(ssize_t) ceil(inverse_edge.x1-0.5); x <= (ssize_t) 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 inline double SaneStrokeWidth(const Image *image, const DrawInfo *draw_info) { return(MagickMin((double) draw_info->stroke_width, (2.0*sqrt(2.0)+MagickEpsilon)*MagickMax(image->columns,image->rows))); } static MagickBooleanType DrawBoundingRectangles(Image *image, const DrawInfo *draw_info,const PolygonInfo *polygon_info, ExceptionInfo *exception) { double mid; DrawInfo *clone_info; MagickBooleanType status; PointInfo end, resolution, start; PrimitiveInfo primitive_info[6]; register 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(status); } 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)* SaneStrokeWidth(image,clone_info)/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); } } status=QueryColorCompliance("#00f",AllCompliance,&clone_info->stroke, exception); if (status == MagickFalse) { clone_info=DestroyDrawInfo(clone_info); return(status); } 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); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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,1,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 (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,1,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 (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; register double dx, dy; register 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) 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 > MaxBezierCoordinates) break; if (fabs(length) < 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); } 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 ((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++) { PixelInfo composite, pixel; double alpha, offset; register Quantum *magick_restrict q; register 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 != (ssize_t) ceil(gradient_vector->x1-0.5)) || (y != (ssize_t) 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 != (ssize_t) ceil(gradient_vector->x1-0.5)) || (y != (ssize_t) 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: { MagickBooleanType antialias; double repeat; antialias=MagickFalse; repeat=0.0; if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) || (y != (ssize_t) 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 size_t pad) { double extent; size_t quantum; /* Check if there is enough storage for drawing pimitives. */ extent=(double) mvg_info->offset+pad+PrimitiveExtentPad; quantum=sizeof(**mvg_info->primitive_info); if (((extent*quantum) < (double) SSIZE_MAX) && ((extent*quantum) < (double) GetMaxMemoryRequest())) { if (extent <= (double) *mvg_info->extent) return(MagickTrue); *mvg_info->primitive_info=ResizeQuantumMemory(*mvg_info->primitive_info, (size_t) extent,quantum); if (*mvg_info->primitive_info != (PrimitiveInfo *) NULL) { *mvg_info->extent=(size_t) extent; 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=AcquireCriticalMemory(PrimitiveExtentPad*quantum); (void) memset(*mvg_info->primitive_info,0,PrimitiveExtentPad*quantum); *mvg_info->extent=1; return(MagickFalse); } static SplayTreeInfo *GetMVGMacros(const char *primitive) { char *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(CompareSplayTreeString,RelinquishMagickMemory, RelinquishMagickMemory); token=AcquireString(primitive); extent=strlen(token)+MagickPathExtent; for (q=primitive; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (*token == '\0') break; if (LocaleCompare("push",token) == 0) { register const char *end, *start; GetNextToken(q,&q,extent,token); if (*q == '"') { char name[MagickPathExtent]; const char *p; ssize_t n; /* Named macro (e.g. push graphic-context "wheel"). */ GetNextToken(q,&q,extent,token); start=q; end=q; (void) CopyMagickString(name,token,MagickPathExtent); n=1; for (p=q; *p != '\0'; ) { GetNextToken(p,&p,extent,token); 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)) { char *macro; /* Extract macro. */ GetNextToken(p,&p,extent,token); macro=AcquireString(start); macro[end-start]='\0'; (void) AddValueToSplayTree(macros,ConstantString(name), ConstantString(macro)); macro=DestroyString(macro); break; } } } } } token=DestroyString(token); return(macros); } static inline MagickBooleanType IsPoint(const char *point) { char *p; double value; value=StringToDouble(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; register const char *p; register 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(status); } primitive=(char *) NULL; if (*draw_info->primitive != '@') primitive=AcquireString(draw_info->primitive); else if ((strlen(draw_info->primitive) > 1) && (*(draw_info->primitive+1) != '-')) primitive=FileToString(draw_info->primitive+1,~0UL,exception); if (primitive == (char *) NULL) return(MagickFalse); primitive_extent=(double) strlen(primitive); (void) SetImageArtifact(image,"MVG",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=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)); mvg_info.primitive_info=(&primitive_info); mvg_info.extent=(&number_points); mvg_info.offset=0; 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. */ GetNextToken(q,&q,MagickPathExtent,keyword); 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); switch (*keyword) { case ';': break; case 'a': case 'A': { if (LocaleCompare("affine",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.sx=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.rx=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ry=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.sy=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.tx=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ty=StringToDouble(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) { 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; GetNextToken(q,&q,extent,token); if (*token == '\0') { status=MagickFalse; break; } mvg_class=(const char *) GetValueFromSplayTree(macros,token); if (mvg_class != (const char *) NULL) { 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. */ 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 (draw_info->compliance != SVGCompliance) status&=DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); } break; } if (LocaleCompare("clip-rule",keyword) == 0) { ssize_t fill_rule; 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; 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. */ GetNextToken(q,&q,extent,token); graphic_context[n]->compliance=(ComplianceType) ParseCommandOption( MagickComplianceOptions,MagickFalse,token); break; } status=MagickFalse; break; } case 'd': case 'D': { if (LocaleCompare("decorate",keyword) == 0) { ssize_t decorate; 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) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->density,token); break; } if (LocaleCompare("direction",keyword) == 0) { ssize_t direction; 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) { 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) { 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; 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* StringToDouble(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(token,exception); graphic_context[n]->fill_alpha*=opacity; if (graphic_context[n]->fill.alpha != TransparentAlpha) graphic_context[n]->fill.alpha=graphic_context[n]->fill_alpha; else graphic_context[n]->fill.alpha=ClampToQuantum(QuantumRange* opacity); break; } if (LocaleCompare("fill-rule",keyword) == 0) { ssize_t fill_rule; 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) { 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) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->family,token); break; } if (LocaleCompare("font-size",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->pointsize=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("font-stretch",keyword) == 0) { ssize_t stretch; 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; 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; 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) { GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("gravity",keyword) == 0) { ssize_t gravity; 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; 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) { GetNextToken(q,&q,extent,token); graphic_context[n]->interline_spacing=StringToDouble(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("interword-spacing",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->interword_spacing=StringToDouble(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 'k': case 'K': { if (LocaleCompare("kerning",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->kerning=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } status=MagickFalse; break; } case 'l': case 'L': { if (LocaleCompare("letter-spacing",keyword) == 0) { GetNextToken(q,&q,extent,token); 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* StringToDouble(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. */ 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 (draw_info->compliance != SVGCompliance) status=SetImageMask(image,CompositePixelMask, graphic_context[n]->composite_mask,exception); } break; } break; } case 'o': case 'O': { if (LocaleCompare("offset",keyword) == 0) { GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("opacity",keyword) == 0) { double opacity; 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* StringToDouble(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(token,exception); graphic_context[n]->fill_alpha*=opacity; if (graphic_context[n]->fill_alpha != OpaqueAlpha) graphic_context[n]->fill.alpha=graphic_context[n]->fill_alpha; graphic_context[n]->stroke_alpha*=opacity; if (graphic_context[n]->stroke_alpha != OpaqueAlpha) graphic_context[n]->stroke.alpha=graphic_context[n]->stroke_alpha; 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) { GetNextToken(q,&q,extent,token); 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) && (draw_info->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) { GetNextToken(q,&q,extent,token); if (LocaleCompare("class",token) == 0) { /* Class context. */ for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"class") != 0) continue; break; } GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("clip-path",token) == 0) { char name[MaxTextExtent]; const char *clip_path; GetNextToken(q,&q,extent,token); (void) FormatLocaleString(name,MaxTextExtent,"%s",token); clip_path=(const char *) GetValueFromSplayTree(macros,name); if (clip_path != (const char *) NULL) (void) SetImageArtifact(image,name,clip_path); 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; GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); GetNextToken(q,&q,extent,token); (void) CopyMagickString(type,token,MagickPathExtent); GetNextToken(q,&q,extent,token); segment.x1=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.y1=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.x2=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.y2=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); if (LocaleCompare(type,"radial") == 0) { GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); } for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; 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); 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 == '"') GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("mask",token) == 0) { GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("pattern",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent]; RectangleInfo bounds; GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); GetNextToken(q,&q,extent,token); bounds.x=(ssize_t) ceil(StringToDouble(token,&next_token)-0.5); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); bounds.y=(ssize_t) ceil(StringToDouble(token,&next_token)-0.5); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); bounds.width=(size_t) floor(StringToDouble(token,&next_token)+ 0.5); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); bounds.height=(size_t) floor(StringToDouble(token,&next_token)+ 0.5); if (token == next_token) ThrowPointExpectedException(token,exception); for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; 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); 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) { GetNextToken(q,&q,extent,token); angle=StringToDouble(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) { GetNextToken(q,&q,extent,token); affine.sx=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.sy=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("skewX",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); affine.ry=sin(DegreesToRadians(angle)); break; } if (LocaleCompare("skewY",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(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; } GetNextToken(q,&q,extent,token); status&=QueryColorCompliance(token,AllCompliance,&stop_color, exception); stops[number_stops-1].color=stop_color; GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; stops[number_stops-1].offset=factor*StringToDouble(token, &next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("stroke",keyword) == 0) { 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) { 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; GetNextToken(r,&r,extent,token); if (*token == ',') GetNextToken(r,&r,extent,token); for (x=0; IsPoint(token) != MagickFalse; x++) { GetNextToken(r,&r,extent,token); if (*token == ',') GetNextToken(r,&r,extent,token); } graphic_context[n]->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2*x+4), 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+4)*sizeof(*graphic_context[n]->dash_pattern)); for (j=0; j < x; j++) { GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->dash_pattern[j]=StringToDouble(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; } GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("stroke-dashoffset",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->dash_offset=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); break; } if (LocaleCompare("stroke-linecap",keyword) == 0) { ssize_t linecap; 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; 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) { GetNextToken(q,&q,extent,token); graphic_context[n]->miterlimit=StringToUnsignedLong(token); break; } if (LocaleCompare("stroke-opacity",keyword) == 0) { double opacity; 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* StringToDouble(token,&next_token),0.0),1.0); if (token == next_token) ThrowPointExpectedException(token,exception); graphic_context[n]->stroke_alpha*=opacity; if (graphic_context[n]->stroke.alpha != TransparentAlpha) graphic_context[n]->stroke.alpha=graphic_context[n]->stroke_alpha; else graphic_context[n]->stroke.alpha=ClampToQuantum(QuantumRange* opacity); break; } if (LocaleCompare("stroke-width",keyword) == 0) { GetNextToken(q,&q,extent,token); if (graphic_context[n]->clip_path != MagickFalse) break; graphic_context[n]->stroke_width=StringToDouble(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; 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; 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) { GetNextToken(q,&q,extent,token); graphic_context[n]->text_antialias=StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("text-undercolor",keyword) == 0) { GetNextToken(q,&q,extent,token); status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->undercolor,exception); break; } if (LocaleCompare("translate",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.tx=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ty=StringToDouble(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. */ 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; } break; } case 'v': case 'V': { if (LocaleCompare("viewbox",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token, &next_token)-0.5); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token, &next_token)-0.5); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble( token,&next_token)+0.5); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble( 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) { GetNextToken(q,&q,extent,token); graphic_context[n]->interword_spacing=StringToDouble(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. */ 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; GetNextToken(q,&q,extent,token); point.x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); point.y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(q,(const char **) NULL,extent,token); if (*token == ',') 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,number_points); } if (status == MagickFalse) break; primitive_info[j].primitive=primitive_type; primitive_info[j].coordinates=(size_t) x; primitive_info[j].method=FloodfillMethod; primitive_info[j].closed_subpath=MagickFalse; primitive_info[j].text=(char *) NULL; /* 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((double) alpha,(double) beta); coordinates*=5.0; coordinates+=2.0*((size_t) ceil((double) MagickPI*radius))+6.0* BezierQuantum+360.0; break; } case BezierPrimitive: { coordinates=(double) (BezierQuantum*primitive_info[j].coordinates); if (primitive_info[j].coordinates > (107*BezierQuantum)) { (void) ThrowMagickException(exception,GetMagickModule(),DrawError, "TooManyBezierCoordinates","`%s'",token); status=MagickFalse; break; } break; } case PathPrimitive: { char *s, *t; GetNextToken(q,&q,extent,token); coordinates=1.0; t=token; for (s=token; *s != '\0'; s=t) { double value; value=StringToDouble(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; } case CirclePrimitive: case ArcPrimitive: case EllipsePrimitive: { double alpha, beta, radius; alpha=bounds.x2-bounds.x1; beta=bounds.y2-bounds.y1; radius=hypot(alpha,beta); coordinates=2.0*(ceil(MagickPI*radius))+6.0*BezierQuantum+360.0; if (coordinates > (MaxBezierCoordinates/4)) { (void) ThrowMagickException(exception,GetMagickModule(),DrawError, "TooManyBezierCoordinates","`%s'",token); status=MagickFalse; } break; } default: break; } if (coordinates > MaxBezierCoordinates) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",token); status=MagickFalse; } 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,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: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } 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) { primitive_type=UndefinedPrimitive; 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; } 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 != ',') 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; break; } case ImagePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } GetNextToken(q,&q,extent,token); (void) CloneString(&primitive_info[j].text,token); break; } } mvg_info.offset=i; if ((image->debug != MagickFalse) && (q > p)) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p-1), p); if (status == MagickFalse) break; primitive_info[i].primitive=UndefinedPrimitive; 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) && (draw_info->compliance != SVGCompliance) && (graphic_context[n]->clip_mask != (char *) NULL) && (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0)) 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,1,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("#000000ff",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); clone_info->fill_pattern=NewImageList(); clone_info->stroke_pattern=NewImageList(); (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,1,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) { register 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) { PathInfo *magick_restrict path_info; PolygonInfo **polygon_info; register 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) return((PolygonInfo **) NULL); (void) memset(polygon_info,0,number_threads*sizeof(*polygon_info)); path_info=ConvertPrimitiveToPath(primitive_info); if (path_info == (PathInfo *) NULL) return(DestroyPolygonThreadSet(polygon_info)); for (i=0; i < (ssize_t) number_threads; i++) { polygon_info[i]=ConvertPathToPolygon(path_info); if (polygon_info[i] == (PolygonInfo *) NULL) return(DestroyPolygonThreadSet(polygon_info)); } path_info=(PathInfo *) RelinquishMagickMemory(path_info); return(polygon_info); } 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; register const PointInfo *q; register EdgeInfo *p; register 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,(size_t) 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); 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; MagickBooleanType fill, status; double mid; PolygonInfo **magick_restrict polygon_info; register EdgeInfo *p; register 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); if (polygon_info == (PolygonInfo **) NULL) return(MagickFalse); DisableMSCWarning(4127) if (0) { status=DrawBoundingRectangles(image,draw_info,polygon_info[0],exception); if (status == MagickFalse) { polygon_info=DestroyPolygonThreadSet(polygon_info); return(status); } } RestoreMSCWarning 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)*SaneStrokeWidth(image,draw_info)/2.0; bounds=polygon_info[0]->edges[0].bounds; 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=(ssize_t) ceil(bounds.y1-0.5); stop_y=(ssize_t) 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; register ssize_t x; register Quantum *magick_restrict q; ssize_t start_x, stop_x; if (status == MagickFalse) continue; start_x=(ssize_t) ceil(bounds.x1-0.5); stop_x=(ssize_t) 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 == (ssize_t) ceil(primitive_info->point.x-0.5)) && (y == (ssize_t) 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=(ssize_t) ceil(bounds.y1-0.5); stop_y=(ssize_t) 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(); register Quantum *magick_restrict q; register ssize_t x; ssize_t start_x, stop_x; if (status == MagickFalse) continue; start_x=(ssize_t) ceil(bounds.x1-0.5); stop_x=(ssize_t) 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.25 ? 1.0 : 0.0; stroke_alpha=stroke_alpha > 0.25 ? 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, q, point; register ssize_t i, x; ssize_t coordinates, y; x=(ssize_t) ceil(primitive_info->point.x-0.5); y=(ssize_t) 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; register 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=(ssize_t) ceil(primitive_info->point.x-0.5); y=(ssize_t) ceil(primitive_info->point.y-0.5); image_view=AcquireAuthenticCacheView(image,exception); switch (primitive_info->primitive) { case AlphaPrimitive: { if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); switch (primitive_info->method) { case PointMethod: default: { PixelInfo pixel; register 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); (void) SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { MagickBooleanType sync; PixelInfo pixel, target; (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, exception); GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register 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); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { ChannelType channel_mask; PixelInfo target; (void) 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: { MagickBooleanType sync; PixelInfo pixel; for (y=0; y < (ssize_t) image->rows; y++) { register 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); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } } break; } case ColorPrimitive: { switch (primitive_info->method) { case PointMethod: default: { PixelInfo pixel; register 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); (void) SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { MagickBooleanType sync; PixelInfo pixel, target; (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, exception); for (y=0; y < (ssize_t) image->rows; y++) { register 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); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { PixelInfo target; (void) 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: { MagickBooleanType sync; PixelInfo pixel; GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register 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); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == 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(); if (LocaleNCompare(primitive_info->text,"data:",5) == 0) composite_images=ReadInlineImage(clone_info,primitive_info->text, exception); else { (void) CopyMagickString(clone_info->filename,primitive_info->text, MagickPathExtent); composite_images=ReadImage(clone_info,exception); } clone_info=DestroyImageInfo(clone_info); if (composite_images == (Image *) NULL) { status=0; break; } composite_image=RemoveFirstImageFromList(&composite_images); composite_images=DestroyImageList(composite_images); (void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor) NULL,(void *) NULL); x1=(ssize_t) ceil(primitive_info[1].point.x-0.5); y1=(ssize_t) 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; (void) TransformImage(&composite_image,(char *) NULL, composite_geometry,exception); } if (composite_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel, exception); if (draw_info->alpha != OpaqueAlpha) (void) 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; status&=DrawAffineImage(image,composite_image,&affine,exception); composite_image=DestroyImage(composite_image); break; } case PointPrimitive: { PixelInfo fill_color; register 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); (void) 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); status=DrawDashPolygon(draw_info,primitive_info,image,exception); break; } mid=ExpandAffine(&draw_info->affine)*SaneStrokeWidth(image,draw_info)/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); 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]; register 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; register 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(image,draw_info,p); if (stroke_polygon == (PrimitiveInfo *) NULL) { status=0; stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon); 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=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"interword-spacing"); if (option != (const char *) NULL) draw_info->interword_spacing=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"kerning"); if (option != (const char *) NULL) draw_info->kerning=StringToDouble(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=StringToDouble(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; register 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; MagickBooleanType status; PointInfo center, points[3], radii; register double cosine, sine; PrimitiveInfo *primitive_info; register PrimitiveInfo *p; register 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 ((fabs(radii.x) < MagickEpsilon) || (fabs(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; 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) 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); p=(*mvg_info->primitive_info)+mvg_info->offset; mvg_info->offset+=p->coordinates; p+=p->coordinates; } 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(status); } static MagickBooleanType TraceBezier(MVGInfo *mvg_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; PrimitiveInfo *primitive_info; register PrimitiveInfo *p; register 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) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) quantum) quantum=(size_t) alpha; } } quantum=(size_t) MagickMin((double) quantum/number_coordinates, (double) BezierQuantum); control_points=quantum*number_coordinates; if (CheckPrimitiveExtent(mvg_info,control_points+1) == MagickFalse) return(MagickFalse); primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; coefficients=(double *) AcquireQuantumMemory((size_t) number_coordinates,sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory((size_t) control_points, sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); /* 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) return(MagickFalse); p+=p->coordinates; } if (TracePoint(p,end) == MagickFalse) 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; register PrimitiveInfo *p; register 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 ((coordinates > (double) SSIZE_MAX) || (coordinates > (double) GetMaxMemoryRequest())) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (CheckPrimitiveExtent(mvg_info,(size_t) 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 size_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; register PrimitiveInfo *q; register 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 { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arc.x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arc.y=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); angle=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse; GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse; if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(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(0); 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++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(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(0); 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 { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(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(0); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(0); 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 { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(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(0); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(0); 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 { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(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(0); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(0); 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++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(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(0); 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++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(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(0); 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++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); if (token == next_token) ThrowPointExpectedException(token,exception); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(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(0); 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 { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(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(0); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(0); 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(0); q=(*mvg_info->primitive_info)+mvg_info->offset; if (TracePoint(q,point) == MagickFalse) return(0); 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(0); 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(number_coordinates); } static MagickBooleanType TraceRectangle(PrimitiveInfo *primitive_info, const PointInfo start,const PointInfo end) { PointInfo point; register PrimitiveInfo *p; register ssize_t i; if ((fabs(start.x-end.x) < MagickEpsilon) || (fabs(start.y-end.y) < MagickEpsilon)) { primitive_info->coordinates=0; return(MagickTrue); } 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; register PrimitiveInfo *p; register 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; register double dx, dy; register 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 Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info) { #define CheckPathExtent(pad) \ if ((q+(pad)) >= (ssize_t) max_strokes) \ { \ if (~max_strokes < (pad)) \ { \ path_p=(PointInfo *) RelinquishMagickMemory(path_p); \ path_q=(PointInfo *) RelinquishMagickMemory(path_q); \ } \ else \ { \ max_strokes+=(pad); \ path_p=(PointInfo *) ResizeQuantumMemory(path_p,max_strokes, \ sizeof(*path_p)); \ path_q=(PointInfo *) ResizeQuantumMemory(path_q,max_strokes, \ sizeof(*path_q)); \ } \ if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL)) \ { \ if (path_p != (PointInfo *) NULL) \ path_p=(PointInfo *) RelinquishMagickMemory(path_p); \ if (path_q != (PointInfo *) NULL) \ path_q=(PointInfo *) RelinquishMagickMemory(path_q); \ polygon_primitive=(PrimitiveInfo *) \ RelinquishMagickMemory(polygon_primitive); \ return((PrimitiveInfo *) NULL); \ } \ } typedef struct _LineSegment { double p, q; } LineSegment; double delta_theta, dot_product, mid, miterlimit; LineSegment dx = {0,0}, dy = {0,0}, inverse_slope = {0,0}, slope = {0,0}, theta = {0,0}; MagickBooleanType closed_path; PointInfo box_p[5], box_q[5], center, offset, *path_p, *path_q; PrimitiveInfo *polygon_primitive, *stroke_polygon; register ssize_t i; size_t arc_segments, max_strokes, number_vertices; ssize_t j, n, p, q; /* Allocate paths. */ number_vertices=primitive_info->coordinates; max_strokes=2*number_vertices+6*BezierQuantum+360; polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_vertices+2UL,sizeof(*polygon_primitive)); if (polygon_primitive == (PrimitiveInfo *) NULL) return((PrimitiveInfo *) NULL); (void) memcpy(polygon_primitive,primitive_info,(size_t) number_vertices* sizeof(*polygon_primitive)); closed_path=primitive_info[0].closed_subpath; 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; } path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes, sizeof(*path_p)); if (path_p == (PointInfo *) NULL) { polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory( polygon_primitive); return((PrimitiveInfo *) NULL); } path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes, sizeof(*path_q)); if (path_q == (PointInfo *) NULL) { path_p=(PointInfo *) RelinquishMagickMemory(path_p); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory( polygon_primitive); 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)*SaneStrokeWidth(image,draw_info)/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; path_q[p++]=box_q[0]; path_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(6*BezierQuantum+360); dot_product=dx.q*dy.p-dx.p*dy.q; if (dot_product <= 0.0) switch (draw_info->linejoin) { case BevelJoin: { path_q[q++]=box_q[1]; path_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) path_p[p++]=box_p[4]; else { path_p[p++]=box_p[1]; path_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) { path_q[q++]=box_q[4]; path_p[p++]=box_p[4]; } else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; path_p[p++]=box_p[1]; path_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) path_p[p++]=box_p[4]; else { path_p[p++]=box_p[1]; path_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) ceil((double) ((theta.q-theta.p)/ (2.0*sqrt((double) (1.0/mid))))); CheckPathExtent(arc_segments+6*BezierQuantum+360); path_q[q].x=box_q[1].x; path_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); path_q[q].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); path_q[q].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); q++; } path_q[q++]=box_q[2]; break; } default: break; } else switch (draw_info->linejoin) { case BevelJoin: { path_p[p++]=box_p[1]; path_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) path_q[q++]=box_q[4]; else { path_q[q++]=box_q[1]; path_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) { path_q[q++]=box_q[4]; path_p[p++]=box_p[4]; } else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; path_p[p++]=box_p[1]; path_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) path_q[q++]=box_q[4]; else { path_q[q++]=box_q[1]; path_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) ceil((double) ((theta.p-theta.q)/ (2.0*sqrt((double) (1.0/mid))))); CheckPathExtent(arc_segments+6*BezierQuantum+360); path_p[p++]=box_p[1]; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); path_p[p].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); path_p[p].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); p++; } path_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; } path_p[p++]=box_p[1]; path_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) { for (i=0; i < (ssize_t) p; i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=path_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=path_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); } path_p=(PointInfo *) RelinquishMagickMemory(path_p); path_q=(PointInfo *) RelinquishMagickMemory(path_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); return(stroke_polygon); }
vect-outer-simd-3.c
/* { dg-require-effective-target vect_simd_clones } */ /* { dg-additional-options "-O3 -fopenmp-simd -ffast-math" } */ #include <stdlib.h> #include "tree-vect.h" #define N 64 float *px, *py; float *tx, *ty; float *x1, *z1, *t1, *t2; int bound[N]; static void inline bar(const float cx, float cy, float *vx, float *vy, int n) { int j; for (j = 0; j < n; ++j) { const float dx = cx - px[j]; const float dy = cy - py[j]; *vx -= dx * tx[j]; *vy -= dy * ty[j]; } } __attribute__((noinline, noclone)) void foo1 () { int i; int n = bound[63]; #pragma omp simd for (i=0; i<N; i++) bar(px[i], py[i], x1+i, z1+i, n); } __attribute__((noinline, noclone)) void foo2 () { volatile int i; int n = bound[63]; for (i=0; i<N; i++) bar(px[i], py[i], x1+i, z1+i, n); } int main() { float *X = (float*)malloc(N * 8 * sizeof (float)); int i; /* check_vect (); */ px = &X[0]; py = &X[N * 1]; tx = &X[N * 2]; ty = &X[N * 3]; x1 = &X[N * 4]; z1 = &X[N * 5]; t1 = &X[N * 6]; t2 = &X[N * 7]; for (i=0; i<N; i++) { px[i] = (float) (i+2); tx[i] = (float) (i+1); py[i] = (float) (i+4); ty[i] = (float) (i+3); x1[i] = z1[i] = 1.0f; bound[i] = i + 1; } foo1 (); /* vector variant. */ for (i=0; i<N;i++) { t1[i] = x1[i]; x1[i] = 1.0f; t2[i] = z1[i]; z1[i] = 1.0f; } foo2 (); /* scalar variant. */ for (i=0; i<N; i++) if (x1[i] != t1[i] || z1[i] != t2[i]) abort (); return 0; } /* { dg-final { scan-tree-dump "OUTER LOOP VECTORIZED" "vect" } } */
GB_binop__second_int64.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__second_int64) // A.*B function (eWiseMult): GB (_AemultB_08__second_int64) // A.*B function (eWiseMult): GB (_AemultB_02__second_int64) // A.*B function (eWiseMult): GB (_AemultB_04__second_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__second_int64) // A*D function (colscale): GB (_AxD__second_int64) // D*A function (rowscale): GB (_DxB__second_int64) // C+=B function (dense accum): GB (_Cdense_accumB__second_int64) // C+=b function (dense accum): GB (_Cdense_accumb__second_int64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__second_int64) // C=scalar+B GB ((none)) // C=scalar+B' GB ((none)) // C=A+scalar GB ((none)) // C=A'+scalar GB ((none)) // C type: int64_t // A type: int64_t // A pattern? 1 // B type: int64_t // B pattern? 0 // BinaryOp: cij = bij #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ int64_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) \ ; // true if values of A are not used #define GB_A_IS_PATTERN \ 1 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int64_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) \ int64_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 = y ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 1 // 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_SECOND || GxB_NO_INT64 || GxB_NO_SECOND_INT64) //------------------------------------------------------------------------------ // 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__second_int64) ( 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__second_int64) ( 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__second_int64) ( 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 int64_t int64_t bwork = (*((int64_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__second_int64) ( 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 int64_t *restrict Cx = (int64_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__second_int64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *restrict Cx = (int64_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__second_int64) ( 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) ; int64_t alpha_scalar ; int64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int64_t *) alpha_scalar_in)) ; beta_scalar = (*((int64_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__second_int64) ( 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__second_int64) ( 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__second_int64) ( 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__second_int64) ( 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 //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 int64_t *Cx = (int64_t *) Cx_output ; int64_t x = (*((int64_t *) x_input)) ; int64_t *Bx = (int64_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 ; int64_t bij = GBX (Bx, p, false) ; Cx [p] = bij ; } return (GrB_SUCCESS) ; #endif } #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 ; int64_t *Cx = (int64_t *) Cx_output ; int64_t *Ax = (int64_t *) Ax_input ; int64_t y = (*((int64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; ; ; Cx [p] = y ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = aij ; \ } GrB_Info GB ((none)) ( 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 \ int64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t x = (*((const int64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int64_t } #endif //------------------------------------------------------------------------------ // 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) \ { \ ; ; \ Cx [pC] = y ; \ } 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 int64_t y = (*((const int64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
GB_split_sparse.c
//------------------------------------------------------------------------------ // GB_split_sparse: split a sparse/hypersparse matrix into tiles //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ #define GB_FREE_WORKSPACE \ GB_WERK_POP (C_ek_slicing, int64_t) ; \ GB_FREE_WORK (&Wp, Wp_size) ; #define GB_FREE_ALL \ GB_FREE_WORKSPACE ; \ GB_Matrix_free (&C) ; #include "GB_split.h" GrB_Info GB_split_sparse // split a sparse matrix ( GrB_Matrix *Tiles, // 2D row-major array of size m-by-n const GrB_Index m, const GrB_Index n, const int64_t *restrict Tile_rows, // size m+1 const int64_t *restrict Tile_cols, // size n+1 const GrB_Matrix A, // input matrix GB_Context Context ) { //-------------------------------------------------------------------------- // get inputs //-------------------------------------------------------------------------- GrB_Info info ; int A_sparsity = GB_sparsity (A) ; bool A_is_hyper = (A_sparsity == GxB_HYPERSPARSE) ; ASSERT (A_is_hyper || A_sparsity == GxB_SPARSE) ; GrB_Matrix C = NULL ; GB_WERK_DECLARE (C_ek_slicing, int64_t) ; ASSERT_MATRIX_OK (A, "A sparse for split", GB0) ; int sparsity_control = A->sparsity_control ; float hyper_switch = A->hyper_switch ; bool csc = A->is_csc ; GrB_Type atype = A->type ; int64_t avlen = A->vlen ; int64_t avdim = A->vdim ; size_t asize = atype->size ; GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int64_t nouter = csc ? n : m ; int64_t ninner = csc ? m : n ; const int64_t *Tile_vdim = csc ? Tile_cols : Tile_rows ; const int64_t *Tile_vlen = csc ? Tile_rows : Tile_cols ; int64_t anvec = A->nvec ; const int64_t *restrict Ap = A->p ; const int64_t *restrict Ah = A->h ; const int64_t *restrict Ai = A->i ; const bool A_iso = A->iso ; //-------------------------------------------------------------------------- // allocate workspace //-------------------------------------------------------------------------- size_t Wp_size = 0 ; int64_t *restrict Wp = NULL ; Wp = GB_MALLOC_WORK (anvec, int64_t, &Wp_size) ; if (Wp == NULL) { // out of memory GB_FREE_ALL ; return (GrB_OUT_OF_MEMORY) ; } GB_memcpy (Wp, Ap, anvec * sizeof (int64_t), nthreads_max) ; //-------------------------------------------------------------------------- // split A into tiles //-------------------------------------------------------------------------- int64_t akend = 0 ; for (int64_t outer = 0 ; outer < nouter ; outer++) { //---------------------------------------------------------------------- // find the starting and ending vector of these tiles //---------------------------------------------------------------------- // The tile appears in vectors avstart:avend-1 of A, and indices // aistart:aiend-1. const int64_t avstart = Tile_vdim [outer] ; const int64_t avend = Tile_vdim [outer+1] ; int64_t akstart = akend ; if (A_is_hyper) { // A is hypersparse: look for vector avend in the A->h hyper list. // The vectors to handle for this outer loop are in // Ah [akstart:akend-1]. akend = akstart ; int64_t pright = anvec - 1 ; bool found ; GB_SPLIT_BINARY_SEARCH (avend, Ah, akend, pright, found) ; ASSERT (GB_IMPLIES (akstart <= akend-1, Ah [akend-1] < avend)) ; } else { // A is sparse; the vectors to handle are akstart:akend-1 akend = avend ; } // # of vectors in all tiles in this outer loop int64_t cnvec = akend - akstart ; int nth = GB_nthreads (cnvec, chunk, nthreads_max) ; //---------------------------------------------------------------------- // create all tiles for vectors akstart:akend-1 in A //---------------------------------------------------------------------- for (int64_t inner = 0 ; inner < ninner ; inner++) { //------------------------------------------------------------------ // allocate C, C->p, and C->h for this tile //------------------------------------------------------------------ const int64_t aistart = Tile_vlen [inner] ; const int64_t aiend = Tile_vlen [inner+1] ; const int64_t cvdim = avend - avstart ; const int64_t cvlen = aiend - aistart ; C = NULL ; GB_OK (GB_new (&C, // new header atype, cvlen, cvdim, GB_Ap_malloc, csc, A_sparsity, hyper_switch, cnvec, Context)) ; C->sparsity_control = sparsity_control ; C->hyper_switch = hyper_switch ; C->nvec = cnvec ; int64_t *restrict Cp = C->p ; int64_t *restrict Ch = C->h ; //------------------------------------------------------------------ // determine the boundaries of this tile //------------------------------------------------------------------ int64_t k ; #pragma omp parallel for num_threads(nth) schedule(static) for (k = akstart ; k < akend ; k++) { int64_t pA = Wp [k] ; const int64_t pA_end = Ap [k+1] ; const int64_t aknz = pA_end - pA ; if (aknz == 0 || Ai [pA] >= aiend) { // this vector of C is empty } else if (aknz > 256) { // use binary search to find aiend bool found ; int64_t pright = pA_end - 1 ; GB_SPLIT_BINARY_SEARCH (aiend, Ai, pA, pright, found) ; #ifdef GB_DEBUG // check the results with a linear search int64_t p2 = Wp [k] ; for ( ; p2 < Ap [k+1] ; p2++) { if (Ai [p2] >= aiend) break ; } ASSERT (pA == p2) ; #endif } else { // use a linear-time search to find aiend for ( ; pA < pA_end ; pA++) { if (Ai [pA] >= aiend) break ; } #ifdef GB_DEBUG // check the results with a binary search bool found ; int64_t p2 = Wp [k] ; int64_t p2_end = Ap [k+1] - 1 ; GB_SPLIT_BINARY_SEARCH (aiend, Ai, p2, p2_end, found) ; ASSERT (pA == p2) ; #endif } Cp [k-akstart] = (pA - Wp [k]) ; // # of entries in this vector if (A_is_hyper) { Ch [k-akstart] = Ah [k] - avstart ; } } GB_cumsum (Cp, cnvec, &(C->nvec_nonempty), nth, Context) ; int64_t cnz = Cp [cnvec] ; //------------------------------------------------------------------ // allocate C->i and C->x for this tile //------------------------------------------------------------------ // set C->iso = A_iso OK GB_OK (GB_bix_alloc (C, cnz, GxB_SPARSE, false, true, A_iso, Context)) ; int64_t *restrict Ci = C->i ; C->magic = GB_MAGIC ; // for GB_nnz_held(C), to slice C //------------------------------------------------------------------ // copy the tile from A into C //------------------------------------------------------------------ int C_ntasks, C_nthreads ; GB_SLICE_MATRIX (C, 8, chunk) ; bool done = false ; if (A_iso) { //-------------------------------------------------------------- // split an iso matrix A into an iso tile C //-------------------------------------------------------------- // A is iso and so is C; copy the iso entry GBURBLE ("(iso sparse split) ") ; memcpy (C->x, A->x, asize) ; #define GB_ISO_SPLIT #define GB_COPY(pC,pA) ; #include "GB_split_sparse_template.c" } else { //-------------------------------------------------------------- // split a non-iso matrix A into an non-iso tile C //-------------------------------------------------------------- #ifndef GBCOMPACT // no typecasting needed switch (asize) { #undef GB_COPY #define GB_COPY(pC,pA) Cx [pC] = Ax [pA] ; case GB_1BYTE : // uint8, int8, bool, or 1-byte user-defined #define GB_CTYPE uint8_t #include "GB_split_sparse_template.c" break ; case GB_2BYTE : // uint16, int16, or 2-byte user-defined #define GB_CTYPE uint16_t #include "GB_split_sparse_template.c" break ; case GB_4BYTE : // uint32, int32, float, or 4-byte user #define GB_CTYPE uint32_t #include "GB_split_sparse_template.c" break ; case GB_8BYTE : // uint64, int64, double, float complex, // or 8-byte user defined #define GB_CTYPE uint64_t #include "GB_split_sparse_template.c" break ; case GB_16BYTE : // double complex or 16-byte user-defined #define GB_CTYPE GB_blob16 // #define GB_CTYPE uint64_t // #undef GB_COPY // #define GB_COPY(pC,pA) \ // Cx [2*pC ] = Ax [2*pA ] ; \ // Cx [2*pC+1] = Ax [2*pA+1] ; #include "GB_split_sparse_template.c" break ; default:; } #endif } if (!done) { // user-defined types #define GB_CTYPE GB_void #undef GB_COPY #define GB_COPY(pC,pA) \ memcpy (Cx + (pC)*asize, Ax +(pA)*asize, asize) ; #include "GB_split_sparse_template.c" } //------------------------------------------------------------------ // free workspace //------------------------------------------------------------------ GB_WERK_POP (C_ek_slicing, int64_t) ; //------------------------------------------------------------------ // advance to the next tile //------------------------------------------------------------------ if (inner < ninner - 1) { int64_t k ; #pragma omp parallel for num_threads(nth) schedule(static) for (k = akstart ; k < akend ; k++) { int64_t ck = k - akstart ; int64_t cknz = Cp [ck+1] - Cp [ck] ; Wp [k] += cknz ; } } //------------------------------------------------------------------ // conform the tile and save it in the Tiles array //------------------------------------------------------------------ ASSERT_MATRIX_OK (C, "C for GB_split", GB0) ; GB_OK (GB_hypermatrix_prune (C, Context)) ; GB_OK (GB_conform (C, Context)) ; if (csc) { GB_TILE (Tiles, inner, outer) = C ; } else { GB_TILE (Tiles, outer, inner) = C ; } ASSERT_MATRIX_OK (C, "final tile C for GB_split", GB0) ; C = NULL ; } } GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; }
hello-omp.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> int main (int argc, char *argv[]) { int nthreads, tid; /* Fork a team of threads giving them their own copies of variables */ #pragma omp parallel private(nthreads, tid) { /* Obtain thread number */ tid = omp_get_thread_num(); printf("Hello World from thread = %d\n", tid); /* Only master thread does this */ if (tid == 0) { nthreads = omp_get_num_threads(); printf("Number of threads = %d\n", nthreads); } } /* All threads join master thread and disband */ }
positions.c
#include "globals.h" void Make_Positions() { printf ( "Sampling positions ...\n" ); fflush ( stdout ); //! @todo do 2D properly in here and peanowalk, too #ifdef PEANO_SAMPLING const uint64_t countCoords = peanoCurveLength(); const uint64_t cellSize = peanoCellSize(); const double halfCellSize = 0.5 * cellSize; const double norm = peanoNormFactor(); double cellSides[3]; cellSides[0] = cellSize * Problem.Boxsize[0] * norm; cellSides[1] = cellSize * Problem.Boxsize[1] * norm; cellSides[2] = cellSize * Problem.Boxsize[2] * norm; const double cellVolume = cellSides[0] * cellSides[1] * cellSides[2]; const double probabilityFactor = cellVolume / ( Problem.Mpart ); double probabilitySum = 0.0; printf ( " Have %lu peano cells of volume (%g, %g, %g) for %d particles\n", countCoords, cellSides[0], cellSides[1], cellSides[2], Param.Npart ); Assert ( countCoords > Param.Npart, "Need more peano cells than particles\n" ); int ipart = 0; for ( uint64_t peano = 0; peano < countCoords; ++peano ) { assignPeanoCoordinates ( P[ipart].Pos, peano ); translateAndRenormalizePeanoCoords ( P[ipart].Pos, halfCellSize, norm ); const double probability = probabilityFactor * Density_Func_Ptr ( ipart, Param.BiasCorrection ); probabilitySum += probability; //Accept particle if ( ipart < Param.Npart && probability > erand48 ( Omp.Seed ) ) { //randomize position inside peano cell P[ipart].Pos[0] += ( erand48 ( Omp.Seed ) - 0.5 ) * cellSides[0]; P[ipart].Pos[1] += ( erand48 ( Omp.Seed ) - 0.5 ) * cellSides[1]; P[ipart].Pos[2] += ( erand48 ( Omp.Seed ) - 0.5 ) * cellSides[2]; ++ipart; if ( ipart == Param.Npart ) { printf ( " Aborting at %lu of %lu peano nodes (%g%%)\n", peano, countCoords, peano * 100. / countCoords ); //Let it run further to get correct probabilitySum values } } } if ( ipart != Param.Npart ) { Problem.Mpart = Problem.Mpart * ipart / Param.Npart; Param.Npart = ipart; //If got less particles we can just ignore all memory beyond this point in the structs printf ( " Resetting particle number to %d and particle mass to %g\n", Param.Npart, Problem.Mpart ); } // Normalization: Sum_cells p = 1 * Npart printf ( " Sum of probabilities %g (%g%%)\n", probabilitySum, probabilitySum * 100.0 / Param.Npart ); #else #pragma omp parallel for for ( int ipart = 0; ipart < Param.Npart; ipart++ ) { #ifdef REJECTION_SAMPLING double rho = 0.0, rho_r = 0.0; while ( rho >= rho_r ) { P[ipart].Pos[0] = erand48 ( Omp.Seed ) * Problem.Boxsize[0]; P[ipart].Pos[1] = erand48 ( Omp.Seed ) * Problem.Boxsize[1]; #ifdef TWO_DIM P[ipart].Pos[2] = 0.0; #else P[ipart].Pos[2] = erand48 ( Omp.Seed ) * Problem.Boxsize[2]; #endif //TWO_DIM rho = Problem.Rho_Max * erand48 ( Omp.Seed ); rho_r = Density_Func_Ptr ( ipart , Param.BiasCorrection ); } #else P[ipart].Pos[0] = erand48 ( Omp.Seed ) * Problem.Boxsize[0]; P[ipart].Pos[1] = erand48 ( Omp.Seed ) * Problem.Boxsize[1]; #ifdef TWO_DIM P[ipart].Pos[2] = 0.0; #else P[ipart].Pos[2] = erand48 ( Omp.Seed ) * Problem.Boxsize[2]; #endif //TWO_DIM #endif //REJECTION_SAMPLING P[ipart].Type = 0; } #endif //PEANO_SAMPLING printf ( "done\n" ); return; } void Make_Velocities() { printf ( "Velocities ..." ); fflush ( stdout ); #pragma omp parallel for for ( int ipart = 0; ipart < Param.Npart; ipart++ ) { ( *Velocity_Func_Ptr ) ( ipart, P[ipart].Vel ); #ifdef TWO_DIM P[ipart].Vel[2] = 0.0; #endif //TWO_DIM } printf ( " done\n" ); return ; } void Make_Temperatures() { printf ( "Internal Energy ..." ); fflush ( stdout ); #pragma omp parallel for for ( int ipart = 0; ipart < Param.Npart; ipart++ ) { SphP[ipart].U = ( *U_Func_Ptr ) ( ipart ); } printf ( " done\n" ); return ; } void Make_Magnetic_Fields() { printf ( "Magnetic Field ..." ); fflush ( stdout ); #pragma omp parallel for for ( int ipart = 0; ipart < Param.Npart; ipart++ ) { ( *Magnetic_Field_Func_Ptr ) ( ipart, SphP[ipart].Bfld ); #ifdef TWO_DIM SphP[ipart].Bfld[2] = 0.0; #endif //TWO_DIM } printf ( " done\n" ); return ; } void Make_PostProcessing() { printf ( "Post Processing ..." ); fflush ( stdout ); ( *PostProcessing_Func_Ptr ) (); printf ( " done\n" ); return ; }
p6.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <omp.h> #define ISIZE 1000 #define JSIZE 1000 int main(int argc, char **argv) { double *a = new double[ISIZE*JSIZE]; double *A = new double[ISIZE*JSIZE]; FILE *ff; int nth = 1; if (argc == 2) nth = atoi(argv[1]); omp_set_dynamic(0); omp_set_num_threads(nth); // Initialization for (int i = 0; i < ISIZE; i++) { for (int j = 0; j < JSIZE; j++) { a[i*JSIZE+j] = 10 * i + j; A[i*JSIZE+j] = 10 * i + j; } } double t = omp_get_wtime(); for (int k = 0; k < 1000; ++k){ // Parallelize for (int i = 0; i < ISIZE - 1; i++) { #pragma omp parallel for for (int j = 0; j < JSIZE - 1; j++) { A[i*JSIZE+j] = sin(0.00001 * a[(i+1)*JSIZE+j+1]); } } } t = omp_get_wtime() - t; printf("Time: %f\n", t); ff = fopen("p6.out", "w"); for (int i = 0; i < ISIZE; i++) { for (int j = 0; j < JSIZE; j++) { fprintf(ff, "%f ", A[i*JSIZE+j]); } fprintf(ff, "\n"); } fclose(ff); delete [] a; delete [] A; return 0; }
mclib.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <glob.h> #include <unistd.h> #include <dirent.h> #include "hdf5.h" #include <math.h> #include <time.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_sort_vector.h> #include "mclib_3d.h" #include <omp.h> #include "mpi.h" #define PROP_DIM1 1 #define PROP_DIM2 8 #define PROP_DIM3 8 #define COORD_DIM1 2 #define R_DIM_2D 9120 #define THETA_DIM_2D 2000 //define constants const double A_RAD=7.56e-15, C_LIGHT=2.99792458e10, PL_CONST=6.6260755e-27; const double K_B=1.380658e-16, M_P=1.6726231e-24, THOMP_X_SECT=6.65246e-25, M_EL=9.1093879e-28 ; int getOrigNumProcesses(int *counted_cont_procs, int **proc_array, char dir[200], int angle_rank, int angle_procs, int last_frame, int dim_switch, int riken_switch) { int i=0, j=0, val=0, original_num_procs=-1, rand_num=0; int frame2=0, framestart=0, scatt_framestart=0, ph_num=0; double time=0; char mc_chkpt_files[200]="", restrt=""; //define new variable that wont write over the restrt variable in the main part of the code, when its put into the readCheckpoint function struct photon *phPtr=NULL; //pointer to array of photons //DIR * dirp; //struct dirent * entry; //struct stat st = {0}; glob_t files; //if (angle_rank==0) { //find number of mc_checkpt files there are //loop through them and find out which prior processes didnt finish and keep track of which ones didnt snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), "%s%s", dir,"mc_chkpt_*" ); val=glob(mc_chkpt_files, 0, NULL,&files ); printf("TEST: %s\n", mc_chkpt_files); //look @ a file by choosing rand int between 0 and files.gl_pathc and if the file exists open and read it to get the actual value for the old number of angle_procs srand(angle_rank); //printf("NUM_FILES: %d\n",files.gl_pathc); rand_num=rand() % files.gl_pathc; snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), "%s%s%d%s", dir,"mc_chkpt_", rand_num,".dat" ); printf("TEST: %s\n", mc_chkpt_files); if ( access( mc_chkpt_files, F_OK ) == -1 ) { while(( access( mc_chkpt_files, F_OK ) == -1 ) ) { rand_num=rand() % files.gl_pathc; snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), "%s%s%d%s", dir,"mc_chkpt_", rand_num,".dat" ); //printf("TEST: %s\n", mc_chkpt_files); } } readCheckpoint(dir, &phPtr, &frame2, &framestart, &scatt_framestart, &ph_num, &restrt, &time, rand_num, &original_num_procs, dim_switch, riken_switch); //original_num_procs= 70; } int count_procs[original_num_procs], count=0; int cont_procs[original_num_procs]; //create array of files including any checkpoint file which may not have been created yet b/c old process was still in 1st frame of scattering for (j=0;j<original_num_procs;j++) { count_procs[j]=j; cont_procs[j]=-1; //set to impossible value for previous mpi process rank that needs to be con't } int limit= (angle_rank != angle_procs-1) ? (angle_rank+1)*original_num_procs/angle_procs : original_num_procs; //char mc_chkpt_files[200]=""; printf("Angle ID: %d, start_num: %d, limit: %d\n", angle_rank, (angle_rank*original_num_procs/angle_procs), limit); count=0; for (j=floor(angle_rank*original_num_procs/angle_procs);j<limit;j++) { snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), "%s%s%d%s", dir,"mc_chkpt_", j,".dat" ); //printf("TEST: %s\n", mc_chkpt_files); if ( access( mc_chkpt_files, F_OK ) != -1 ) { readCheckpoint(dir, &phPtr, &frame2, &framestart, &scatt_framestart, &ph_num, &restrt, &time, count_procs[j], &i, dim_switch, riken_switch); free(phPtr); phPtr=NULL; if ((framestart<=frame2) && (scatt_framestart<=last_frame)) //add another condition here { cont_procs[count]=j; printf("ACCEPTED: %s\n", mc_chkpt_files); count++; } } else { cont_procs[count]=j; printf("ACCEPTED: %s\n", mc_chkpt_files); count++; } } (*proc_array)=malloc (count * sizeof (int )); //allocate space to pointer to hold the old process angle_id's count=0; for (i=0;i<original_num_procs;i++) { if (cont_procs[i]!=-1) { (*proc_array)[count]=cont_procs[i]; count++; } } //save number of old processes this process counted need to be restarted *counted_cont_procs=count; globfree(& files); return original_num_procs; } void printPhotons(struct photon *ph, int num_ph, int frame,int frame_inj, char dir[200], int angle_rank ) { //function to save the photons' positions and 4 momentum int i=0; char mc_file_p0[200]="", mc_file_p1[200]="",mc_file_p2[200]="", mc_file_p3[200]=""; char mc_file_r0[200]="", mc_file_r1[200]="", mc_file_r2[200]="", mc_file_ns[200]="", mc_file_pw[200]=""; FILE *fPtr=NULL, *fPtr1=NULL,*fPtr2=NULL,*fPtr3=NULL,*fPtr4=NULL,*fPtr5=NULL,*fPtr6=NULL,*fPtr7=NULL,*fPtr8=NULL; //make strings for proper files snprintf(mc_file_p0,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_P0_", angle_rank, ".dat" ); snprintf(mc_file_p1,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_P1_", angle_rank, ".dat" ); snprintf(mc_file_p2,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_P2_", angle_rank, ".dat" ); snprintf(mc_file_p3,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_P3_", angle_rank, ".dat" ); snprintf(mc_file_r0,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_R0_", angle_rank, ".dat" ); snprintf(mc_file_r1,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_R1_", angle_rank, ".dat" ); snprintf(mc_file_r2,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_R2_", angle_rank, ".dat" ); snprintf(mc_file_ns,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_NS_", angle_rank, ".dat" ); //for number of scatterings each photon went through if (frame==frame_inj) //if the frame is the same one that the photons were injected in, save the photon weights { snprintf(mc_file_pw,sizeof(mc_file_p0),"%s%s%d%s",dir,"mcdata_PW_", angle_rank, ".dat" ); } //save the energy fPtr=fopen(mc_file_p0, "a"); fPtr1=fopen(mc_file_p1, "a"); fPtr2=fopen(mc_file_p2, "a"); fPtr3=fopen(mc_file_p3, "a"); fPtr4=fopen(mc_file_r0, "a"); fPtr5=fopen(mc_file_r1, "a"); fPtr6=fopen(mc_file_r2, "a"); fPtr7=fopen(mc_file_ns, "a"); if (frame==frame_inj) { fPtr8=fopen(mc_file_pw, "a"); } //printf("Writing P0\n"); for (i=0;i<num_ph;i++) { fprintf(fPtr,"%0.13e\t", (ph+i)->p0); //printf("%d: %0.13e \n", i, (ph+i)->p0); fprintf(fPtr1,"%0.13e\t", (ph+i)->p1); //printf("%d: %0.13e \n", i, (ph+i)->p1); fprintf(fPtr2,"%0.13e\t", (ph+i)->p2); //printf("%d: %0.13e \n", i, (ph+i)->p2); fprintf(fPtr3,"%0.13e\t", (ph+i)->p3); //printf("%d: %0.13e \n", i, (ph+i)->p3); fprintf(fPtr4,"%0.13e\t", (ph+i)->r0); //printf("%d: %0.13e \n", i, (ph+i)->r0); fprintf(fPtr5,"%0.13e\t", (ph+i)->r1); //printf("%d: %0.13e \n", i, (ph+i)->r1); fprintf(fPtr6,"%0.13e\t", (ph+i)->r2); //printf("%d: %0.13e \n", i, (ph+i)->r2); //fprintf(fPtr7,"%0.13e\t", *(ph_num_scatt+i)); fprintf(fPtr7,"%e\t", (ph+i)->num_scatt); //printf("%d: %0.13e \n", i, (ph+i)->num_scatt); if (frame==frame_inj) { fprintf(fPtr8,"%e\t", (ph+i)->weight); } } fclose(fPtr); fclose(fPtr1); fclose(fPtr2); fclose(fPtr3); fclose(fPtr4); fclose(fPtr5); fclose(fPtr6); fclose(fPtr7); if (frame==frame_inj) { fclose(fPtr8); } //printf("%s\n%s\n%s\n", mc_file_p0, mc_file_r0, mc_file_ns); } void saveCheckpoint(char dir[200], int frame, int frame2, int scatt_frame, int ph_num,double time_now, struct photon *ph, int last_frame, int angle_rank,int angle_size ) { //function to save data necessary to restart simulation if it ends //need to save all photon data FILE *fPtr=NULL; char checkptfile[200]=""; char command[200]=""; char restart; int i=0; //for openMPI have some type of problem with saving the checkpoint file for the frame in which photons have been injected and scattered in, can try to delete old mc_checkpoint file //and creating a new one in that case? snprintf(checkptfile,sizeof(checkptfile),"%s%s%d%s",dir,"mc_chkpt_", angle_rank,".dat" ); if ((scatt_frame!=last_frame) && (scatt_frame != frame)) { fPtr=fopen(checkptfile, "wb"); //printf("%s\n", checkptfile); if (fPtr==NULL) { printf("Cannot open %s to save checkpoint\n", checkptfile); } fwrite(&angle_size, sizeof(int), 1, fPtr); restart='c'; fwrite(&restart, sizeof(char), 1, fPtr); //printf("Rank: %d wrote restart %c\n", angle_rank, restart); fflush(stdout); fwrite(&frame, sizeof(int), 1, fPtr); //printf("Rank: %d wrote frame\n", angle_rank); fflush(stdout); fwrite(&frame2, sizeof(int), 1, fPtr); //printf("Rank: %d wrote frame2\n", angle_rank); fflush(stdout); fwrite(&scatt_frame, sizeof(int), 1, fPtr); //printf("Rank: %d wrote scatt_frame\n", angle_rank); fflush(stdout); fwrite(&time_now, sizeof(double), 1, fPtr); //printf("Rank: %d wrote time_now\n", angle_rank); fflush(stdout); fwrite(&ph_num, sizeof(int), 1, fPtr); //printf("Rank: %d wrote ph_num\n", angle_rank); fflush(stdout); for(i=0;i<ph_num;i++) { fwrite((ph+i), sizeof(struct photon ), 1, fPtr); //fwrite((ph), sizeof(struct photon )*ph_num, ph_num, fPtr); } //printf("Rank: %d wrote photons\n", angle_rank); fflush(stdout); } else if (scatt_frame == frame) { snprintf(command, sizeof(command), "%s%s","exec rm ",checkptfile); system(command); fPtr=fopen(checkptfile, "wb"); //printf("%s\n", checkptfile); fflush(stdout); if (fPtr==NULL) { printf("Cannot open %s to save checkpoint\n", checkptfile); } fwrite(&angle_size, sizeof(int), 1, fPtr); restart='c'; fwrite(&restart, sizeof(char), 1, fPtr); //printf("Rank: %d wrote restart %c\n", angle_rank, restart); fflush(stdout); fwrite(&frame, sizeof(int), 1, fPtr); //printf("Rank: %d wrote frame\n", angle_rank); fflush(stdout); fwrite(&frame2, sizeof(int), 1, fPtr); //printf("Rank: %d wrote frame2\n", angle_rank); fflush(stdout); fwrite(&scatt_frame, sizeof(int), 1, fPtr); //printf("Rank: %d wrote scatt_frame\n", angle_rank); fflush(stdout); fwrite(&time_now, sizeof(double), 1, fPtr); //printf("Rank: %d wrote time_now\n", angle_rank); fflush(stdout); fwrite(&ph_num, sizeof(int), 1, fPtr); //printf("Rank: %d wrote ph_num\n", angle_rank); fflush(stdout); for(i=0;i<ph_num;i++) { //fwrite((ph), sizeof(struct photon )*ph_num, ph_num, fPtr); fwrite((ph+i), sizeof(struct photon ), 1, fPtr); } //printf("Rank: %d wrote photons\n", angle_rank); fflush(stdout); } else { fPtr=fopen(checkptfile, "wb"); //printf("%s\n", checkptfile); if (fPtr==NULL) { printf("Cannot open %s to save checkpoint\n", checkptfile); } //just finished last iteration of scatt_frame fwrite(&angle_size, sizeof(int), 1, fPtr); restart='r'; fwrite(&restart, sizeof(char), 1, fPtr); fwrite(&frame, sizeof(int), 1, fPtr); fwrite(&frame2, sizeof(int), 1, fPtr); } fclose(fPtr); } void readCheckpoint(char dir[200], struct photon **ph, int *frame2, int *framestart, int *scatt_framestart, int *ph_num, char *restart, double *time, int angle_rank, int *angle_size , int dim_switch, int riken_switch ) { //function to read in data from checkpoint file FILE *fPtr=NULL; char checkptfile[200]=""; int i=0; //int frame, scatt_frame, ph_num, i=0; struct photon *phHolder=NULL; //pointer to struct to hold data read in from checkpoint file snprintf(checkptfile,sizeof(checkptfile),"%s%s%d%s",dir,"mc_chkpt_", angle_rank,".dat" ); printf("Checkpoint file: %s\n", checkptfile); if (access( checkptfile, F_OK ) != -1) //if you can access the file, open and read it { fPtr=fopen(checkptfile, "rb"); { fread(angle_size, sizeof(int), 1, fPtr); //uncomment once I run MCRAT for the sims that didnt save this originally } fread(restart, sizeof(char), 1, fPtr); //printf("%c\n", *restart); fread(framestart, sizeof(int), 1, fPtr); //printf("%d\n", *framestart); fread(frame2, sizeof(int), 1, fPtr); if((*restart)=='c') { fread(scatt_framestart, sizeof(int), 1, fPtr); if ((riken_switch==1) && (dim_switch==1) && ((*scatt_framestart)>=3000)) { *scatt_framestart+=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 } else { *scatt_framestart+=1; //add one to start at the next frame after the simulation was interrrupted } //printf("%d\n", *scatt_framestart); fread(time, sizeof(double), 1, fPtr); //printf("%e\n", *time); fread(ph_num, sizeof(int), 1, fPtr); //printf("%d\n", *ph_num); phHolder=malloc(sizeof(struct photon)); (*ph)=malloc(sizeof(struct photon)*(*ph_num)); //allocate memory to hold photon data for (i=0;i<(*ph_num);i++) { fread(phHolder, sizeof(struct photon), 1, fPtr); //printf("%e,%e,%e, %e,%e,%e, %e, %e\n",(ph)->p0, (ph)->p1, (ph)->p2, ph->p3, (ph)->r0, (ph)->r1, (ph)->r2, ph->num_scatt ); (*ph)[i].p0=phHolder->p0; (*ph)[i].p1=phHolder->p1; (*ph)[i].p2=phHolder->p2; (*ph)[i].p3=phHolder->p3; (*ph)[i].r0= phHolder->r0; (*ph)[i].r1=phHolder->r1 ; (*ph)[i].r2=phHolder->r2; (*ph)[i].num_scatt=phHolder->num_scatt; (*ph)[i].weight=phHolder->weight; (*ph)[i].nearest_block_index= phHolder->nearest_block_index; } free(phHolder); } else { if ((riken_switch==1) && (dim_switch==1) && ((*framestart)>=3000)) { *framestart+=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 } else { *framestart+=1; //if the checkpoint file saved and the program was inturrupted before the frame variable had just increased and before the scatt_frame iteration was saved, add one to the frame start } *scatt_framestart=(*framestart); } fclose(fPtr); } else //if not use default { //*framestart=(*framestart); *scatt_framestart=(*framestart); *restart='r'; } } void readMcPar(char file[200], double *fluid_domain_x, double *fluid_domain_y, double *fps, double *theta_jmin, double *theta_j, double *d_theta_j, double *inj_radius_small, double *inj_radius_large, int *frm0_small, int *frm0_large, int *last_frm, int *frm2_small,int *frm2_large , double *ph_weight_small,double *ph_weight_large,int *min_photons, int *max_photons, char *spect, char *restart, int *num_threads, int *dim_switch) { //function to read mc.par file FILE *fptr=NULL; char buf[100]=""; double theta_deg; //open file fptr=fopen(file,"r"); //read in frames per sec and other variables outlined in main() fscanf(fptr, "%lf",fluid_domain_x); //printf("%lf\n", *fluid_domain_x ); fgets(buf, 100,fptr); fscanf(fptr, "%lf",fluid_domain_y); //printf("%lf\n", *fluid_domain_y ); fgets(buf, 100,fptr); fscanf(fptr, "%lf",fps); //printf("%f\n", *fps ); fgets(buf, 100,fptr); fscanf(fptr, "%d",frm0_small); //printf("%d\n", *frm0_small ); fgets(buf, 100,fptr); fscanf(fptr, "%d",frm0_large); //printf("%d\n", *frm0_large ); fgets(buf, 100,fptr); fscanf(fptr, "%d",last_frm); //printf("%d\n", *last_frm ); fgets(buf, 100,fptr); fscanf(fptr, "%d",frm2_small); *frm2_small+=*frm0_small; //frame to go to is what is given in the file plus the starting frame //printf("%d\n", *frm2_small ); fgets(buf, 100,fptr); //fscanf(fptr, "%d",photon_num); remove photon num because we dont need this //printf("%d\n", *photon_num ); fscanf(fptr, "%d",frm2_large); *frm2_large+=*frm0_large; //frame to go to is what is given in the file plus the starting frame //printf("%d\n", *frm2_large ); fgets(buf, 100,fptr); //fgets(buf, 100,fptr); fscanf(fptr, "%lf",inj_radius_small); //printf("%lf\n", *inj_radius_small ); fgets(buf, 100,fptr); fscanf(fptr, "%lf",inj_radius_large); //printf("%lf\n", *inj_radius_large ); fgets(buf, 100,fptr); //theta jmin fscanf(fptr, "%lf",&theta_deg); *theta_jmin=theta_deg;//*M_PI/180; leave as degrees to manipulate processes //printf("%f\n", *theta_jmin ); fgets(buf, 100,fptr); fscanf(fptr, "%lf",&theta_deg); *theta_j=theta_deg;//*M_PI/180; //printf("%f\n", *theta_j ); fgets(buf, 100,fptr); fscanf(fptr, "%lf",d_theta_j); //*theta_j=theta_deg;//*M_PI/180; //printf("%f\n", *theta_j ); fgets(buf, 100,fptr); fscanf(fptr, "%lf",ph_weight_small); //printf("%f\n", *ph_weight_small ); fgets(buf, 100,fptr); fscanf(fptr, "%lf",ph_weight_large); fgets(buf, 100,fptr); fscanf(fptr, "%d",min_photons); fgets(buf, 100,fptr); fscanf(fptr, "%d",max_photons); fgets(buf, 100,fptr); *spect=getc(fptr); fgets(buf, 100,fptr); //printf("%c\n",*spect); *restart=getc(fptr); fgets(buf, 100,fptr); fscanf(fptr, "%d",num_threads); //printf("%d\n",*num_threads); fgets(buf, 100,fptr); fscanf(fptr, "%d",dim_switch); //printf("%d\n",*dim_switch); //close file fclose(fptr); } void readAndDecimate(char flash_file[200], double r_inj, double fps, double **x, double **y, double **szx, double **szy, double **r,\ double **theta, double **velx, double **vely, double **dens, double **pres, double **gamma, double **dens_lab, double **temp, int *number, int ph_inj_switch, double min_r, double max_r, double min_theta, double max_theta, FILE *fPtr) { //function to read in data from FLASH file hid_t file,dset, space; herr_t status; hsize_t dims[2]={0,0}; //hold dimension size for coordinate data set (mostly interested in dims[0]) double **vel_x_buffer=NULL, **vel_y_buffer=NULL, **dens_buffer=NULL, **pres_buffer=NULL, **coord_buffer=NULL, **block_sz_buffer=NULL; double *velx_unprc=NULL, *vely_unprc=NULL, *dens_unprc=NULL, *pres_unprc=NULL, *x_unprc=NULL, *y_unprc=NULL, *r_unprc=NULL, *szx_unprc=NULL, *szy_unprc=NULL; int i,j,count,x1_count, y1_count, r_count, **node_buffer=NULL, num_nodes=0, elem_factor=0; double x1[8]={-7.0/16,-5.0/16,-3.0/16,-1.0/16,1.0/16,3.0/16,5.0/16,7.0/16}; double ph_rmin=0, ph_rmax=0, ph_thetamin=0, ph_thetamax=0, r_grid_innercorner=0, r_grid_outercorner=0, theta_grid_innercorner=0, theta_grid_outercorner=0; if (ph_inj_switch==0) { ph_rmin=min_r; ph_rmax=max_r; ph_thetamin=min_theta-2*0.017453292519943295; //min_theta - 2*Pi/180 (2 degrees) ph_thetamax=max_theta+2*0.017453292519943295; //max_theta + 2*Pi/180 (2 degrees) } file = H5Fopen (flash_file, H5F_ACC_RDONLY, H5P_DEFAULT); //ret=H5Pclose(acc_tpl1); fprintf(fPtr, ">> mc.py: Reading positional, density, pressure, and velocity information...\n"); fflush(fPtr); //printf("Reading coord\n"); dset = H5Dopen (file, "coordinates", H5P_DEFAULT); //get dimensions of array and save it space = H5Dget_space (dset); H5Sget_simple_extent_dims(space, dims, NULL); //save dimesnions in dims /* * Allocate array of pointers to rows. OPTIMIZE HERE: INITALIZE ALL THE BUFFERS AT ONCE IN 1 FOR LOOP */ coord_buffer = (double **) malloc (dims[0] * sizeof (double *)); coord_buffer[0] = (double *) malloc (dims[0] * dims[1] * sizeof (double)); block_sz_buffer= (double **) malloc (dims[0] * sizeof (double *)); block_sz_buffer[0] = (double *) malloc (dims[0] * COORD_DIM1 * sizeof (double)); node_buffer= (int **) malloc (dims[0] * sizeof (int *)); node_buffer[0] = (int *) malloc (dims[0] * sizeof (int)); vel_x_buffer= (double **) malloc (dims[0] * sizeof (double *)); vel_x_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double)); vel_y_buffer= (double **) malloc (dims[0] * sizeof (double *)); vel_y_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double)); dens_buffer= (double **) malloc (dims[0] * sizeof (double *)); dens_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double)); pres_buffer= (double **) malloc (dims[0] * sizeof (double *)); pres_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double)); /* * Set the rest of the pointers to rows to the correct addresses. */ for (i=1; i<dims[0]; i++) { coord_buffer[i] = coord_buffer[0] + i * dims[1]; block_sz_buffer[i] = block_sz_buffer[0] + i * COORD_DIM1; node_buffer[i] = node_buffer[0] + i ; vel_x_buffer[i] = vel_x_buffer[0] + i * PROP_DIM1*PROP_DIM2*PROP_DIM3; vel_y_buffer[i] = vel_y_buffer[0] + i * PROP_DIM1*PROP_DIM2*PROP_DIM3; dens_buffer[i] = dens_buffer[0] + i * PROP_DIM1*PROP_DIM2*PROP_DIM3; pres_buffer[i] = pres_buffer[0] + i * PROP_DIM1*PROP_DIM2*PROP_DIM3; } //read data such that first column is x and second column is y //printf("Reading Dataset\n"); status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,coord_buffer[0]); //close dataset status = H5Sclose (space); status = H5Dclose (dset); //printf("Reading block size\n"); dset = H5Dopen (file, "block size", H5P_DEFAULT); //printf("Reading Dataset\n"); status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,block_sz_buffer[0]); // first column of buffer is x and second column is y status = H5Dclose (dset); //printf("Reading node type\n"); dset = H5Dopen (file, "node type", H5P_DEFAULT); //printf("Reading Dataset\n"); status = H5Dread (dset, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT,node_buffer[0]); status = H5Dclose (dset); //printf("Reading velx\n"); dset = H5Dopen (file, "velx", H5P_DEFAULT); //printf("Reading Dataset\n"); status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,vel_x_buffer[0]); status = H5Dclose (dset); //printf("Reading vely\n"); dset = H5Dopen (file, "vely", H5P_DEFAULT); //printf("Reading Dataset\n"); status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,vel_y_buffer[0]); status = H5Dclose (dset); //printf("Reading dens\n"); dset = H5Dopen (file, "dens", H5P_DEFAULT); //printf("Reading Dataset\n"); status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,dens_buffer[0]); status = H5Dclose (dset); //printf("Reading pres\n"); dset = H5Dopen (file, "pres", H5P_DEFAULT); //printf("Reading Dataset\n"); status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,pres_buffer[0]); status = H5Dclose (dset); //H5Pclose(xfer_plist); status = H5Fclose (file); fprintf(fPtr,">> Selecting good node types (=1)\n"); //find out how many good nodes there are for (i=0;i<dims[0];i++) { if (node_buffer[i][0]==1 ){ num_nodes++; } } //allocate memory for arrays to hold unprocessed data pres_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); dens_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); velx_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); vely_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); x_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); y_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); r_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); szx_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); szy_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); //find where the good values corresponding to the good gones (=1) and save them to the previously allocated pointers which are 1D arrays //also create proper x and y arrays and block size arrays //and then free up the buffer memory space fprintf(fPtr,">> Creating and reshaping arrays\n"); count=0; for (i=0;i<dims[0];i++) { if (node_buffer[i][0]==1 ) { x1_count=0; y1_count=0; for (j=0;j<(PROP_DIM1*PROP_DIM2*PROP_DIM3);j++) { *(pres_unprc+count)=pres_buffer[i][j]; *(dens_unprc+count)=dens_buffer[i][j]; *(velx_unprc+count)=vel_x_buffer[i][j]; *(vely_unprc+count)=vel_y_buffer[i][j]; *(szx_unprc+count)=((block_sz_buffer[i][0])/8)*1e9; //divide by 8 for resolution, multiply by 1e9 to scale properly? *(szy_unprc+count)=((block_sz_buffer[i][1])/8)*1e9; if (j%8==0) { x1_count=0; } if ((j%8==0) && (j!=0)) { y1_count++; } *(x_unprc+count)=(coord_buffer[i][0]+block_sz_buffer[i][0]*x1[x1_count])*1e9; *(y_unprc+count)=(coord_buffer[i][1]+block_sz_buffer[i][1]*x1[y1_count])*1e9; //printf("%d,%d,%d,%d\n",count,j,x1_count,y1_count); x1_count++; count++; } } } free (pres_buffer[0]); free (dens_buffer[0]);free (vel_x_buffer[0]);free (vel_y_buffer[0]); free(coord_buffer[0]);free(block_sz_buffer[0]);free(node_buffer[0]); free (pres_buffer);free(dens_buffer);free(vel_x_buffer);free(vel_y_buffer);free(coord_buffer);free(block_sz_buffer);free(node_buffer); //fill in radius array and find in how many places r > injection radius elem_factor=1; r_count=0; while (r_count==0) { r_count=0; elem_factor++; for (i=0;i<count;i++) { *(r_unprc+i)=pow((pow(*(x_unprc+i),2)+pow(*(y_unprc+i),2)),0.5); if (ph_inj_switch==0) { r_grid_innercorner = pow((*(x_unprc+i) - *(szx_unprc+i)/2.0) * ((*(x_unprc+i) - *(szx_unprc+i)/2.0))+(*(y_unprc+i) - *(szx_unprc+i)/2.0) * (*(y_unprc+i) - *(szx_unprc+i)/2.0),0.5); r_grid_outercorner = pow((*(x_unprc+i) + *(szx_unprc+i)/2.0) * ((*(x_unprc+i) + *(szx_unprc+i)/2.0))+(*(y_unprc+i) + *(szx_unprc+i)/2.0) * (*(y_unprc+i) + *(szx_unprc+i)/2.0),0.5); theta_grid_innercorner = acos( (*(y_unprc+i) - *(szx_unprc+i)/2.0) /r_grid_innercorner); //arccos of y/r for the bottom left corner theta_grid_outercorner = acos( (*(y_unprc+i) + *(szx_unprc+i)/2.0) /r_grid_outercorner); if (((ph_rmin - elem_factor*C_LIGHT/fps) <= r_grid_outercorner) && (r_grid_innercorner <= (ph_rmax + elem_factor*C_LIGHT/fps) ) && (theta_grid_outercorner >= ph_thetamin) && (theta_grid_innercorner <= ph_thetamax) ) { r_count++; } } else { if (*(r_unprc+i)> (0.95*r_inj) ) { r_count++; } } } //fprintf(fPtr, "r_count: %d count: %d\n", r_count, count); } fprintf(fPtr, "Elem factor: %d Ph_rmin: %e rmax: %e Chosen FLASH min_r: %e max_r: %e min_theta: %e degrees max_theta: %e degrees\n", elem_factor, ph_rmin, ph_rmax, ph_rmin - (elem_factor*C_LIGHT/fps), ph_rmax + (elem_factor*C_LIGHT/fps), ph_thetamin*180/M_PI, ph_thetamax*180/M_PI); fflush(fPtr); //allocate memory to hold processed data (*pres)=malloc (r_count * sizeof (double )); (*velx)=malloc (r_count * sizeof (double )); (*vely)=malloc (r_count * sizeof (double )); (*dens)=malloc (r_count * sizeof (double )); (*x)=malloc (r_count * sizeof (double )); (*y)=malloc (r_count * sizeof (double )); (*r)=malloc (r_count * sizeof (double )); (*theta)=malloc (r_count * sizeof (double )); (*gamma)=malloc (r_count * sizeof (double )); (*dens_lab)=malloc (r_count * sizeof (double )); (*szx)=malloc (r_count * sizeof (double )); (*szy)=malloc (r_count * sizeof (double )); (*temp)=malloc (r_count * sizeof (double )); //assign values based on r> 0.95*r_inj j=0; for (i=0;i<count;i++) { if (ph_inj_switch==0) { r_grid_innercorner = pow((*(x_unprc+i) - *(szx_unprc+i)/2.0) * ((*(x_unprc+i) - *(szx_unprc+i)/2.0))+(*(y_unprc+i) - *(szx_unprc+i)/2.0) * (*(y_unprc+i) - *(szx_unprc+i)/2.0),0.5); r_grid_outercorner = pow((*(x_unprc+i) + *(szx_unprc+i)/2.0) * ((*(x_unprc+i) + *(szx_unprc+i)/2.0))+(*(y_unprc+i) + *(szx_unprc+i)/2.0) * (*(y_unprc+i) + *(szx_unprc+i)/2.0),0.5); theta_grid_innercorner = acos( (*(y_unprc+i) - *(szx_unprc+i)/2.0) /r_grid_innercorner); //arccos of y/r for the bottom left corner theta_grid_outercorner = acos( (*(y_unprc+i) + *(szx_unprc+i)/2.0) /r_grid_outercorner); if (((ph_rmin - elem_factor*C_LIGHT/fps) <= r_grid_outercorner) && (r_grid_innercorner <= (ph_rmax + elem_factor*C_LIGHT/fps) ) && (theta_grid_outercorner >= ph_thetamin) && (theta_grid_innercorner <= ph_thetamax)) { (*pres)[j]=*(pres_unprc+i); (*velx)[j]=*(velx_unprc+i); (*vely)[j]=*(vely_unprc+i); (*dens)[j]=*(dens_unprc+i); (*x)[j]=*(x_unprc+i); (*y)[j]=*(y_unprc+i); (*r)[j]=*(r_unprc+i); (*szx)[j]=*(szx_unprc+i); (*szy)[j]=*(szy_unprc+i); (*theta)[j]=atan2( *(x_unprc+i) , *(y_unprc+i) );//theta in radians in relation to jet axis (*gamma)[j]=pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1); //v is in units of c (*dens_lab)[j]= (*(dens_unprc+i)) * (pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1)); (*temp)[j]=pow(3*(*(pres_unprc+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0); j++; } } else { if (*(r_unprc+i)> (0.95*r_inj) ) { (*pres)[j]=*(pres_unprc+i); (*velx)[j]=*(velx_unprc+i); (*vely)[j]=*(vely_unprc+i); (*dens)[j]=*(dens_unprc+i); (*x)[j]=*(x_unprc+i); (*y)[j]=*(y_unprc+i); (*r)[j]=*(r_unprc+i); (*szx)[j]=*(szx_unprc+i); (*szy)[j]=*(szy_unprc+i); (*theta)[j]=atan2( *(x_unprc+i) , *(y_unprc+i) );//theta in radians in relation to jet axis (*gamma)[j]=pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1); //v is in units of c (*dens_lab)[j]= (*(dens_unprc+i)) * (pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1)); (*temp)[j]=pow(3*(*(pres_unprc+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0); j++; } } } *number=j; //fprintf(fPtr, "number: %d\n", j); free(pres_unprc); free(velx_unprc);free(vely_unprc);free(dens_unprc);free(x_unprc); free(y_unprc);free(r_unprc);free(szx_unprc);free(szy_unprc); } void photonInjection( struct photon **ph, int *ph_num, double r_inj, double ph_weight, int min_photons, int max_photons, char spect, int array_length, double fps, double theta_min, double theta_max,\ double *x, double *y, double *szx, double *szy, double *r, double *theta, double *temps, double *vx, double *vy, gsl_rng * rand, int riken_switch, FILE *fPtr) { int i=0, block_cnt=0, *ph_dens=NULL, ph_tot=0, j=0,k=0; double ph_dens_calc=0.0, fr_dum=0.0, y_dum=0.0, yfr_dum=0.0, fr_max=0, bb_norm=0, position_phi, ph_weight_adjusted, rmin, rmax; double com_v_phi, com_v_theta, *p_comv=NULL, *boost=NULL; //comoving phi, theta, comoving 4 momentum for a photon, and boost for photon(to go to lab frame) double *l_boost=NULL; //pointer to hold array of lorentz boost, to lab frame, values float num_dens_coeff; if (spect=='w') //from MCRAT paper, w for wien spectrum { num_dens_coeff=8.44; //printf("in wien spectrum\n"); } else { num_dens_coeff=20.29; //this is for black body spectrum //printf("in BB spectrum"); } //find how many blocks are near the injection radius within the angles defined in mc.par, get temperatures and calculate number of photons to allocate memory for //and then rcord which blocks have to have "x" amount of photons injected there rmin=r_inj - 0.5*C_LIGHT/fps; rmax=r_inj + 0.5*C_LIGHT/fps; for(i=0;i<array_length;i++) { //look at all boxes in width delta r=c/fps and within angles we are interested in NEED TO IMPLEMENT if ((*(r+i) >= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >=theta_min) ) { block_cnt++; } } //printf("Blocks: %d\n", block_cnt); ph_dens=malloc(block_cnt * sizeof(int)); //calculate the photon density for each block and save it to the array j=0; ph_tot=0; ph_weight_adjusted=ph_weight; //printf("%d %d\n", max_photons, min_photons); while ((ph_tot>max_photons) || (ph_tot<min_photons) ) { j=0; ph_tot=0; //allocate memory to record density of photons for each block //ph_dens=malloc(block_cnt * sizeof(int)); for (i=0;i<array_length;i++) { //printf("%d\n",i); //printf("%e, %e, %e, %e, %e, %e\n", *(r+i),(r_inj - C_LIGHT/fps), (r_inj + C_LIGHT/fps), *(theta+i) , theta_max, theta_min); if ((*(r+i) >= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >=theta_min) ) { if (riken_switch==0) { //using FLASH ph_dens_calc=(num_dens_coeff*2.0*M_PI*(*(x+i))*pow(*(temps+i),3.0)*pow(*(szx+i),2.0) /(ph_weight_adjusted))*pow(pow(1.0-(pow(*(vx+i),2)+pow(*(vy+i),2)),0.5),-1) ; //a*T^3/(weight) dV, dV=2*PI*x*dx^2, } else { ph_dens_calc=(num_dens_coeff*2.0*M_PI*pow(*(r+i),2)*sin(*(theta+i))*pow(*(temps+i),3.0)*(*(szx+i))*(*(szy+i)) /(ph_weight_adjusted))*pow(pow(1.0-(pow(*(vx+i),2)+pow(*(vy+i),2)),0.5),-1); //dV=2 *pi* r^2 Sin(theta) dr dtheta } (*(ph_dens+j))=gsl_ran_poisson(rand,ph_dens_calc) ; //choose from poission distribution with mean of ph_dens_calc //printf("%d, %lf \n",*(ph_dens+j), ph_dens_calc); //sum up all the densities to get total number of photons ph_tot+=(*(ph_dens+j)); j++; } } if (ph_tot>max_photons) { //if the number of photons is too big make ph_weight larger ph_weight_adjusted*=10; //free(ph_dens); } else if (ph_tot<min_photons) { ph_weight_adjusted*=0.5; //free(ph_dens); } //printf("dens: %d, photons: %d\n", *(ph_dens+(j-1)), ph_tot); } //printf("%d\n", ph_tot); //allocate memory for that many photons and also allocate memory to hold comoving 4 momentum of each photon and the velocity of the fluid (*ph)=malloc (ph_tot * sizeof (struct photon )); p_comv=malloc(4*sizeof(double)); boost=malloc(3*sizeof(double)); l_boost=malloc(4*sizeof(double)); //go through blocks and assign random energies/locations to proper number of photons ph_tot=0; k=0; for (i=0;i<array_length;i++) { if ((*(r+i) >= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >= theta_min) ) { //*(temps+i)=0.76*(*(temps+i)); for(j=0;j<( *(ph_dens+k) ); j++ ) { //have to get random frequency for the photon comoving frequency y_dum=1; //initalize loop yfr_dum=0; while (y_dum>yfr_dum) { fr_dum=gsl_rng_uniform_pos(rand)*6.3e11*(*(temps+i)); //in Hz //printf("%lf, %lf ",gsl_rng_uniform_pos(rand), (*(temps+i))); y_dum=gsl_rng_uniform_pos(rand); //printf("%lf ",fr_dum); if (spect=='w') { yfr_dum=(1.0/(1.29e31))*pow((fr_dum/(*(temps+i))),3.0)/(exp((PL_CONST*fr_dum)/(K_B*(*(temps+i)) ))-1); //curve is normalized to maximum } else { fr_max=(5.88e10)*(*(temps+i));//(C_LIGHT*(*(temps+i)))/(0.29); //max frequency of bb bb_norm=(PL_CONST*fr_max * pow((fr_max/C_LIGHT),2.0))/(exp(PL_CONST*fr_max/(K_B*(*(temps+i))))-1); //find value of bb at fr_max yfr_dum=((1.0/bb_norm)*PL_CONST*fr_dum * pow((fr_dum/C_LIGHT),2.0))/(exp(PL_CONST*fr_dum/(K_B*(*(temps+i))))-1); //curve is normalized to vaue of bb @ max frequency } //printf("%lf, %lf,%lf,%e \n",(*(temps+i)),fr_dum, y_dum, yfr_dum); } //printf("%lf\n ",fr_dum); position_phi=gsl_rng_uniform(rand)*2*M_PI; com_v_phi=gsl_rng_uniform(rand)*2*M_PI; com_v_theta=acos((gsl_rng_uniform(rand)*2)-1); //printf("%lf, %lf, %lf\n", position_phi, com_v_phi, com_v_theta); //populate 4 momentum comoving array *(p_comv+0)=PL_CONST*fr_dum/C_LIGHT; *(p_comv+1)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*cos(com_v_phi); *(p_comv+2)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*sin(com_v_phi); *(p_comv+3)=(PL_CONST*fr_dum/C_LIGHT)*cos(com_v_theta); //populate boost matrix, not sure why multiplying by -1, seems to give correct answer in old python code... *(boost+0)=-1*(*(vx+i))*cos(position_phi); *(boost+1)=-1*(*(vx+i))*sin(position_phi); *(boost+2)=-1*(*(vy+i)); //printf("%lf, %lf, %lf\n", *(boost+0), *(boost+1), *(boost+2)); //boost to lab frame lorentzBoost(boost, p_comv, l_boost, 'p', fPtr); //printf("Assignemnt: %e, %e, %e, %e\n", *(l_boost+0), *(l_boost+1), *(l_boost+2),*(l_boost+3)); (*ph)[ph_tot].p0=(*(l_boost+0)); (*ph)[ph_tot].p1=(*(l_boost+1)); (*ph)[ph_tot].p2=(*(l_boost+2)); (*ph)[ph_tot].p3=(*(l_boost+3)); (*ph)[ph_tot].r0= (*(x+i))*cos(position_phi); //put photons @ center of box that they are supposed to be in with random phi (*ph)[ph_tot].r1=(*(x+i))*sin(position_phi) ; (*ph)[ph_tot].r2=(*(y+i)); //y coordinate in flash becomes z coordinate in MCRaT (*ph)[ph_tot].num_scatt=0; (*ph)[ph_tot].weight=ph_weight_adjusted; (*ph)[ph_tot].nearest_block_index=0; //printf("%d\n",ph_tot); ph_tot++; } k++; } } *ph_num=ph_tot; //save number of photons //printf(" %d: %d\n", *(ph_dens+(k-1)), *ph_num); free(ph_dens); free(p_comv);free(boost); free(l_boost); } void lorentzBoost(double *boost, double *p_ph, double *result, char object, FILE *fPtr) { //function to perform lorentz boost //if doing boost for an electron last argument is 'e' and there wont be a check for zero norm //if doing boost for a photon last argument is 'p' and there will be a check for zero norm double beta=0, gamma=0, *boosted_p=NULL; gsl_vector_view b=gsl_vector_view_array(boost, 3); //make boost pointer into vector gsl_vector_view p=gsl_vector_view_array(p_ph, 4); //make boost pointer into vector gsl_matrix *lambda1= gsl_matrix_calloc (4, 4); //create matrix thats 4x4 to do lorentz boost gsl_vector *p_ph_prime =gsl_vector_calloc(4); //create vestor to hold lorentz boosted vector /* fprintf(fPtr,"Boost: %e, %e, %e, %e\n",gsl_blas_dnrm2(&b.vector), *(boost+0), *(boost+1), *(boost+2)); fflush(fPtr); fprintf(fPtr,"4 Momentum to Boost: %e, %e, %e, %e\n",*(p_ph+0), *(p_ph+1), *(p_ph+2), *(p_ph+3)); fflush(fPtr); */ //if magnitude of fluid velocity is != 0 do lorentz boost otherwise dont need to do a boost if (gsl_blas_dnrm2(&b.vector) > 0) { //fprintf(fPtr,"in If\n"); //fflush(fPtr); beta=gsl_blas_dnrm2(&b.vector); gamma=1.0/sqrt(1-pow(beta, 2.0)); //fprintf(fPtr,"Beta: %e\tGamma: %e\n",beta,gamma ); //fflush(fPtr); //initalize matrix values gsl_matrix_set(lambda1, 0,0, gamma); gsl_matrix_set(lambda1, 0,1, -1*gsl_vector_get(&b.vector,0)*gamma); gsl_matrix_set(lambda1, 0,2, -1*gsl_vector_get(&b.vector,1)*gamma); gsl_matrix_set(lambda1, 0,3, -1*gsl_vector_get(&b.vector,2)*gamma); gsl_matrix_set(lambda1, 1,1, 1+((gamma-1)*pow(gsl_vector_get(&b.vector,0),2.0)/pow(beta,2.0) ) ); gsl_matrix_set(lambda1, 1,2, ((gamma-1)*(gsl_vector_get(&b.vector,0)* gsl_vector_get(&b.vector,1)/pow(beta,2.0) ) )); gsl_matrix_set(lambda1, 1,3, ((gamma-1)*(gsl_vector_get(&b.vector,0)* gsl_vector_get(&b.vector,2)/pow(beta,2.0) ) )); gsl_matrix_set(lambda1, 2,2, 1+((gamma-1)*pow(gsl_vector_get(&b.vector,1),2.0)/pow(beta,2.0) ) ); gsl_matrix_set(lambda1, 2,3, ((gamma-1)*(gsl_vector_get(&b.vector,1)* gsl_vector_get(&b.vector,2)/pow(beta,2.0)) ) ); gsl_matrix_set(lambda1, 3,3, 1+((gamma-1)*pow(gsl_vector_get(&b.vector,2),2.0)/pow(beta,2.0) ) ); gsl_matrix_set(lambda1, 1,0, gsl_matrix_get(lambda1,0,1)); gsl_matrix_set(lambda1, 2,0, gsl_matrix_get(lambda1,0,2)); gsl_matrix_set(lambda1, 3,0, gsl_matrix_get(lambda1,0,3)); gsl_matrix_set(lambda1, 2,1, gsl_matrix_get(lambda1,1,2)); gsl_matrix_set(lambda1, 3,1, gsl_matrix_get(lambda1,1,3)); gsl_matrix_set(lambda1, 3,2, gsl_matrix_get(lambda1,2,3)); gsl_blas_dgemv(CblasNoTrans, 1, lambda1, &p.vector, 0, p_ph_prime ); /* fprintf(fPtr,"Lorentz Boost Matrix 0: %e,%e, %e, %e\n", gsl_matrix_get(lambda1, 0,0), gsl_matrix_get(lambda1, 0,1), gsl_matrix_get(lambda1, 0,2), gsl_matrix_get(lambda1, 0,3)); fflush(fPtr); fprintf(fPtr,"Lorentz Boost Matrix 1: %e,%e, %e, %e\n", gsl_matrix_get(lambda1, 1,0), gsl_matrix_get(lambda1, 1,1), gsl_matrix_get(lambda1, 1,2), gsl_matrix_get(lambda1, 1,3)); fflush(fPtr); fprintf(fPtr,"Lorentz Boost Matrix 2: %e,%e, %e, %e\n", gsl_matrix_get(lambda1, 2,0), gsl_matrix_get(lambda1, 2,1), gsl_matrix_get(lambda1, 2,2), gsl_matrix_get(lambda1, 2,3)); fflush(fPtr); fprintf(fPtr,"Lorentz Boost Matrix 3: %e,%e, %e, %e\n", gsl_matrix_get(lambda1, 3,0), gsl_matrix_get(lambda1, 3,1), gsl_matrix_get(lambda1, 3,2), gsl_matrix_get(lambda1, 3,3)); fflush(fPtr); fprintf(fPtr,"Before Check: %e %e %e %e\n ",gsl_vector_get(p_ph_prime, 0), gsl_vector_get(p_ph_prime, 1), gsl_vector_get(p_ph_prime, 2), gsl_vector_get(p_ph_prime, 3)); fflush(fPtr); */ //double check vector for 0 norm condition if photon if (object == 'p') { //fprintf(fPtr,"In if\n"); boosted_p=zeroNorm(gsl_vector_ptr(p_ph_prime, 0)); } else { boosted_p=gsl_vector_ptr(p_ph_prime, 0); } /* fprintf(fPtr,"After Check: %e %e %e %e\n ", *(boosted_p+0),*(boosted_p+1),*(boosted_p+2),*(boosted_p+3) ); fflush(fPtr); * */ } else { /* fprintf(fPtr,"in else"); fflush(fPtr); * */ //double check vector for 0 norm condition if (object=='p') { boosted_p=zeroNorm(p_ph); } else { //if 4 momentum isnt for photon and there is no boost to be done, we dont care about normality and just want back what was passed to lorentz boost boosted_p=gsl_vector_ptr(&p.vector, 0); } } //assign values to result *(result+0)=*(boosted_p+0); *(result+1)=*(boosted_p+1); *(result+2)=*(boosted_p+2); *(result+3)=*(boosted_p+3); //free up memory //free(boosted_p); gsl_matrix_free (lambda1); gsl_vector_free(p_ph_prime); } double *zeroNorm(double *p_ph) { //ensures zero norm condition of photon 4 monetum is held int i=0; double normalizing_factor=0; gsl_vector_view p=gsl_vector_view_array((p_ph+1), 3); //make last 3 elements of p_ph pointer into vector if (*(p_ph+0) != gsl_blas_dnrm2(&p.vector ) ) { normalizing_factor=(gsl_blas_dnrm2(&p.vector )); //fprintf(fPtr,"in zero norm if\n"); //fflush(fPtr); //go through and correct 4 momentum assuming the energy is correct *(p_ph+1)= ((*(p_ph+1))/(normalizing_factor))*(*(p_ph+0)); *(p_ph+2)= ((*(p_ph+2))/(normalizing_factor))*(*(p_ph+0)); *(p_ph+3)= ((*(p_ph+3))/(normalizing_factor))*(*(p_ph+0)); } /* if (pow((*(p_ph+0)),2) != ( pow((*(p_ph+1)),2)+pow((*(p_ph+2)),2)+pow((*(p_ph+3)),2) ) ) { printf("This isnt normalized in the function\nThe difference is: %e\n", pow((*(p_ph+0)),2) - ( pow((*(p_ph+1)),2)+pow((*(p_ph+2)),2)+pow((*(p_ph+3)),2) ) ); } */ //normalized within a factor of 10^-53 return p_ph; } int findNearestBlock(int array_num, double ph_x, double ph_y, double ph_z, double *x, double *y, double *z, int dim_switch_3d) { double dist=0, dist_min=1e15, block_dist=0; int min_index=0, j=0; dist_min=1e15;//set dist to impossible value to make sure at least first distance calulated is saved block_dist=3e9; while (dist_min==1e15) //if this is true, then the algorithm hasnt found blocks within the acceptable range given by block_dist { for(j=0;j<array_num;j++) { //if the distance between them is within 3e9, to restrict number of possible calculations, calulate the total distance between the box and photon if ((dim_switch_3d==0) && (fabs(ph_x- (*(x+j)))<block_dist) && (fabs(ph_y- (*(y+j)))<block_dist)) { dist= pow(pow(ph_x- (*(x+j)), 2.0) + pow(ph_y- (*(y+j)) , 2.0),0.5); //fprintf(fPtr,"Dist calculated as: %e, index: %d\n", dist, j); //printf("In outer if statement, OLD: %e, %d\n", dist_min, min_index); if((dist<dist_min)) { //fprintf(fPtr,"In innermost if statement, OLD: %e, %d\n", dist_min, min_index); dist_min=dist; //save new minimum distance min_index=j; //save index //printf("New Min dist: %e, New min Index: %d, Array_Num: %d\n", dist_min, min_index, array_num); } } else if ((dim_switch_3d==1) &&(fabs(ph_x- (*(x+j)))<block_dist) && (fabs(ph_y- (*(y+j)))<block_dist) && (fabs(ph_z- (*(z+j)))<block_dist)) { dist= pow(pow(ph_x- (*(x+j)), 2.0) + pow(ph_y- (*(y+j)),2.0 ) + pow(ph_z- (*(z+j)) , 2.0),0.5); if((dist<dist_min)) { //printf("In innermost if statement, OLD: %e, %d\n", dist_min, min_index); dist_min=dist; //save new minimum distance min_index=j; //save index //fprintf(fPtr,"New Min dist: %e, New min Index: %d, Array_Num: %e\n", dist_min, min_index, array_num); } } } block_dist*=10; //increase size of accepted distances for gris points, if dist_min==1e12 then the next time the acceptance range wil be larger } return min_index; } int findContainingBlock(int array_num, double ph_x, double ph_y, double ph_z, double *x, double *y, double *z, double *szx, double *szy, int dim_switch_3d, int riken_switch, FILE *fPtr) { int i=0, within_block_index=0; bool is_in_block=0; //boolean to determine if the photon is outside of a grid for (i=0;i<array_num;i++) { is_in_block=checkInBlock(i, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch); if (is_in_block) { within_block_index=i; //change for loop index once the block is found so the code doesnt search the rest of the grids to see if the photon is within those grids i=array_num; } } if (is_in_block==0) { fprintf(fPtr, "Couldn't find a block that the photon is in\n"); } return within_block_index; } int checkInBlock(int block_index, double ph_x, double ph_y, double ph_z, double *x, double *y, double *z, double *szx, double *szy, int dim_switch_3d, int riken_switch) { bool is_in_block=0; //boolean to determine if the photon is outside of its previously noted block double x0=0, x1=0, x2=0, sz_x0=0, sz_x1=0, sz_x2=0; //coordinate and sizes of grid block, in cartesian its x,y,z in spherical its r,theta,phi int return_val=0; if (dim_switch_3d==0) { if (riken_switch==1) { x0=pow(pow((*(x+block_index)),2.0)+pow((*(y+block_index)),2.0), 0.5); x1=atan2((*(x+block_index)), (*(y+block_index))); sz_x0=(*(szx+block_index)); sz_x1=(*(szy+block_index)); //pow(pow( ph_x, 2.0) + pow(ph_y, 2.0),0.5) atan2(ph_x, ph_y) is_in_block= (fabs(pow(pow( ph_x, 2.0) + pow(ph_y, 2.0),0.5) - x0) <= sz_x0/2.0) && (fabs(atan2(ph_x, ph_y) - x1 ) <= sz_x1/2.0); } else { x0=(*(x+block_index)); x1=(*(y+block_index)); sz_x0=(*(szx+block_index)); sz_x1=(*(szy+block_index)); is_in_block= (fabs(ph_x-x0) <= sz_x0/2.0) && (fabs(ph_y-x1) <= sz_x1/2.0); } } else { if (riken_switch==1) { x0=pow(pow((*(x+block_index)), 2.0) + pow((*(y+block_index)),2.0 ) + pow((*(z+block_index)) , 2.0),0.5); x1=acos((*(z+block_index))/pow(pow((*(x+block_index)), 2.0) + pow((*(y+block_index)),2.0 ) + pow((*(z+block_index)) , 2.0),0.5)); x2=atan2((*(y+block_index)), (*(x+block_index))); sz_x0=(*(szy+block_index)); sz_x1=(*(szx+block_index)); sz_x2=(*(szx+block_index)); is_in_block= (fabs(pow(pow( ph_x, 2.0) + pow(ph_y, 2.0)+pow(ph_z, 2.0),0.5) - x0) <= sz_x0/2.0) && (fabs(acos(ph_z/pow(pow(ph_x, 2.0) + pow(ph_y,2.0 ) + pow(ph_z , 2.0),0.5)) - x1 ) <= sz_x1/2.0) && (fabs(atan2(ph_y, ph_x) - x2 ) <= sz_x2/2.0); } } if (is_in_block) { return_val=1; } else { return_val=0; } return return_val; } int findNearestPropertiesAndMinMFP( struct photon *ph, int num_ph, int array_num, double hydro_domain_x, double hydro_domain_y, double *time_step, double *x, double *y, double *z, double *szx, double *szy, double *velx, double *vely, double *velz, double *dens_lab,\ double *temp, double *n_dens_lab, double *n_vx, double *n_vy, double *n_vz, double *n_temp, gsl_rng * rand, int dim_switch_3d, int find_nearest_block_switch, int riken_switch, FILE *fPtr) { int i=0, min_index=0, ph_block_index=0; double ph_x=0, ph_y=0, ph_phi=0, ph_z=0, ph_r=0; double fl_v_x=0, fl_v_y=0, fl_v_z=0; //to hold the fluid velocity in MCRaT coordinates double ph_v_norm=0, fl_v_norm=0; double n_cosangle=0, n_dens_lab_tmp=0,n_vx_tmp=0, n_vy_tmp=0, n_vz_tmp=0, n_temp_tmp=0 ; double rnd_tracker=0, n_dens_lab_min=0, n_vx_min=0, n_vy_min=0, n_vz_min=0, n_temp_min=0; int num_thread=omp_get_num_threads(); bool is_in_block=0; //boolean to determine if the photon is outside of its previously noted block int index=0; double mfp=0,min_mfp=0, beta=0; double *all_time_steps=NULL; gsl_permutation *perm = gsl_permutation_alloc(num_ph); //to hold sorted indexes of smallest to largest time_steps gsl_vector_view all_time_steps_vector; //initialize gsl random number generator fo each thread const gsl_rng_type *rng_t; gsl_rng **rng; gsl_rng_env_setup(); rng_t = gsl_rng_ranlxs0; rng = (gsl_rng **) malloc((num_thread ) * sizeof(gsl_rng *)); rng[0]=rand; //#pragma omp parallel for num_threads(nt) for(i=1;i<num_thread;i++) { rng[i] = gsl_rng_alloc (rng_t); gsl_rng_set(rng[i],gsl_rng_get(rand)); } //go through each photon and find the blocks around it and then get the distances to all of those blocks and choose the one thats the shortest distance away //can optimize here, exchange the for loops and change condition to compare to each of the photons is the radius of the block is .95 (or 1.05) times the min (max) photon radius //or just parallelize this part here all_time_steps=malloc(num_ph*sizeof(double)); min_mfp=1e12; #pragma omp parallel for num_threads(num_thread) firstprivate( is_in_block, ph_block_index, ph_r, ph_x, ph_y, ph_z, ph_phi, min_index, n_dens_lab_tmp,n_vx_tmp, n_vy_tmp, n_vz_tmp, n_temp_tmp, fl_v_x, fl_v_y, fl_v_z, fl_v_norm, ph_v_norm, n_cosangle, mfp, beta, rnd_tracker) private(i) shared(min_mfp ) for (i=0;i<num_ph; i++) { //printf("%d, %e,%e\n", i, ((ph+i)->r0), ((ph+i)->r1)); if (find_nearest_block_switch==0) { ph_block_index=(ph+i)->nearest_block_index; //if starting a new frame the number of indexes can change and cause a seg fault } else { ph_block_index=0; //if starting a new frame set index=0 to avoid this issue } if (dim_switch_3d==0) { ph_x=pow(pow(((ph+i)->r0),2.0)+pow(((ph+i)->r1),2.0), 0.5); //convert back to FLASH x coordinate ph_y=((ph+i)->r2); ph_phi=atan2(((ph+i)->r1), ((ph+i)->r0)); ph_r=pow(ph_x*ph_x + ph_y*ph_y, 0.5); } else { ph_x=((ph+i)->r0); ph_y=((ph+i)->r1); ph_z=((ph+i)->r2); ph_r=pow(ph_x*ph_x + ph_y*ph_y+ph_z*ph_z, 0.5); } //if the location of the photon is less than the domain of the hydro simulation then do all of this, otherwise assing huge mfp value so no scattering occurs and the next frame is loaded if ((ph_y<hydro_domain_y) && (ph_x<hydro_domain_x)) { //printf("ph_x:%e, ph_y:%e\n", ph_x, ph_y); is_in_block=checkInBlock(ph_block_index, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch); if (find_nearest_block_switch==0 && is_in_block) { //keep the saved grid index min_index=ph_block_index; } else { //find the new index of the block closest to the photon //min_index=findNearestBlock(array_num, ph_x, ph_y, ph_z, x, y, z, dim_switch_3d); //stop doing this one b/c nearest grid could be one that the photon isnt actually in due to adaptive mesh //find the new index of the block that the photon is actually in min_index=findContainingBlock(array_num, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch, fPtr); (ph+i)->nearest_block_index=min_index; //save the index } //fprintf(fPtr,"Outside\n"); //save values (n_dens_lab_tmp)= (*(dens_lab+min_index)); (n_vx_tmp)= (*(velx+min_index)); (n_vy_tmp)= (*(vely+min_index)); (n_temp_tmp)= (*(temp+min_index)); if (dim_switch_3d==1) { (n_vz_tmp)= (*(velz+min_index)); } if (dim_switch_3d==0) { fl_v_x=(*(velx+min_index))*cos(ph_phi); fl_v_y=(*(velx+min_index))*sin(ph_phi); fl_v_z=(*(vely+min_index)); } else { fl_v_x=(*(velx+min_index)); fl_v_y=(*(vely+min_index)); fl_v_z=(*(velz+min_index)); } fl_v_norm=pow(pow(fl_v_x, 2.0)+pow(fl_v_y, 2.0)+pow(fl_v_z, 2.0), 0.5); ph_v_norm=pow(pow(((ph+i)->p1), 2.0)+pow(((ph+i)->p2), 2.0)+pow(((ph+i)->p3), 2.0), 0.5); //(*(n_cosangle+i))=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //find cosine of the angle between the photon and the fluid velocities via a dot product (n_cosangle)=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //make 1 for cylindrical otherwise its undefined if (dim_switch_3d==0) { beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)),0.5); } else { beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)+pow((n_vz_tmp),2)),0.5); } //put this in to double check that random number is between 0 and 1 (exclusive) because there was a problem with this for parallel case rnd_tracker=0; rnd_tracker=gsl_rng_uniform_pos(rng[omp_get_thread_num()]); //printf("Rnd_tracker: %e Thread number %d \n",rnd_tracker, omp_get_thread_num() ); mfp=(-1)*(M_P/((n_dens_lab_tmp))/THOMP_X_SECT/(1.0-beta*((n_cosangle))))*log(rnd_tracker) ; //calulate the mfp and then multiply it by the ln of a random number to simulate distribution of mean free paths } else { mfp=min_mfp; //printf("In ELSE\n"); } *(all_time_steps+i)=mfp/C_LIGHT; } //free rand number generator for (i=1;i<num_thread;i++) { gsl_rng_free(rng[i]); } free(rng); //save variables I need all_time_steps_vector=gsl_vector_view_array(all_time_steps, num_ph); //makes a vector to use the time steps in another gsl function gsl_sort_vector_index (perm, &all_time_steps_vector.vector); //sorts timesteps from smallest to largest and saves the indexes fo the smallest to largest elements in perm, the all_time_steps vector stays in the same order as before (ordered by photons) //for (i=0;i<num_ph;i++) //{ // *(sorted_indexes+i)= (int) perm->data[i]; //save sorted indexes to array to use outside of function //} (*time_step)=*(all_time_steps+( (int) perm->data[0] )); index= (int) perm->data[0] ;//first element of sorted array, index of photon min_index=(ph+index)->nearest_block_index; //index of FLASH element closest to photon that will scatter *(n_dens_lab)= (*(dens_lab+min_index)); *(n_vx)= (*(velx+min_index)); *(n_vy)= (*(vely+min_index)); *(n_temp)= (*(temp+min_index)); if (dim_switch_3d==1) { *(n_vz)= (*(velz+min_index)); } free (all_time_steps); gsl_permutation_free(perm); all_time_steps=NULL; return index; } int interpolatePropertiesAndMinMFP( struct photon *ph, int num_ph, int array_num, double *time_step, double *x, double *y, double *z, double *szx, double *szy, double *velx, double *vely, double *velz, double *dens_lab,\ double *temp, double *n_dens_lab, double *n_vx, double *n_vy, double *n_vz, double *n_temp, gsl_rng * rand, int dim_switch_3d, int find_nearest_block_switch, int riken_switch, FILE *fPtr) { /* * THIS FUNCTION IS WRITTEN JUST FOR 2D SIMS AS OF NOW */ int i=0, j=0, min_index=0, ph_block_index=0; int left_block_index=0, right_block_index=0, bottom_block_index=0, top_block_index=0, all_adjacent_block_indexes[4]; double ph_x=0, ph_y=0, ph_phi=0, ph_z=0, dist=0, left_dist_min=0, right_dist_min=0, top_dist_min=0, bottom_dist_min=0, dv=0, v=0; double fl_v_x=0, fl_v_y=0, fl_v_z=0; //to hold the fluid velocity in MCRaT coordinates double r=0, theta=0; double ph_v_norm=0, fl_v_norm=0; double n_cosangle=0, n_dens_lab_tmp=0,n_vx_tmp=0, n_vy_tmp=0, n_vz_tmp=0, n_temp_tmp=0; double rnd_tracker=0, n_dens_lab_min=0, n_vx_min=0, n_vy_min=0, n_vz_min=0, n_temp_min=0; int num_thread=2;//omp_get_max_threads(); bool is_in_block=0; //boolean to determine if the photon is outside of its previously noted block int index=0; double mfp=0,min_mfp=0, beta=0; //initialize gsl random number generator fo each thread const gsl_rng_type *rng_t; gsl_rng **rng; gsl_rng_env_setup(); rng_t = gsl_rng_ranlxs0; rng = (gsl_rng **) malloc((num_thread ) * sizeof(gsl_rng *)); rng[0]=rand; //#pragma omp parallel for num_threads(nt) for(i=1;i<num_thread;i++) { rng[i] = gsl_rng_alloc (rng_t); gsl_rng_set(rng[i],gsl_rng_get(rand)); } //go through each photon and find the blocks around it and then get the distances to all of those blocks and choose the one thats the shortest distance away //can optimize here, exchange the for loops and change condition to compare to each of the photons is the radius of the block is .95 (or 1.05) times the min (max) photon radius //or just parallelize this part here min_mfp=1e12; #pragma omp parallel for num_threads(num_thread) firstprivate( r, theta,dv, v, all_adjacent_block_indexes, j, left_block_index, right_block_index, top_block_index, bottom_block_index, is_in_block, ph_block_index, ph_x, ph_y, ph_z, ph_phi, min_index, n_dens_lab_tmp,n_vx_tmp, n_vy_tmp, n_vz_tmp, n_temp_tmp, fl_v_x, fl_v_y, fl_v_z, fl_v_norm, ph_v_norm, n_cosangle, mfp, beta, rnd_tracker) private(i) shared(min_mfp ) for (i=0;i<num_ph; i++) { //printf("%d, %e,%e\n", i, ((ph+i)->r0), ((ph+i)->r1)); if (find_nearest_block_switch==0) { ph_block_index=(ph+i)->nearest_block_index; //if starting a new frame the number of indexes can change and cause a seg fault } else { ph_block_index=0; //if starting a new frame set index=0 to avoid this issue } if (dim_switch_3d==0) { ph_x=pow(pow(((ph+i)->r0),2.0)+pow(((ph+i)->r1),2.0), 0.5); //convert back to FLASH x coordinate ph_y=((ph+i)->r2); ph_phi=atan2(((ph+i)->r1), ((ph+i)->r0)); } else { ph_x=((ph+i)->r0); ph_y=((ph+i)->r1); ph_z=((ph+i)->r2); } //printf("ph_x:%e, ph_y:%e\n", ph_x, ph_y); is_in_block=checkInBlock(ph_block_index, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch); if (find_nearest_block_switch==0 && is_in_block) { //keep the saved grid index min_index=ph_block_index; } else { //find the new index of the block closest to the photon //min_index=findNearestBlock(array_num, ph_x, ph_y, ph_z, x, y, z, dim_switch_3d); //stop doing this one b/c nearest grid could be one that the photon isnt actually in due to adaptive mesh //find the new index of the block that the photon is actually in min_index=findContainingBlock(array_num, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch, fPtr); (ph+i)->nearest_block_index=min_index; //save the index } //look for the blocks surounding the block of interest and order them by the left_dist_min=1e15;//set dist to impossible value to make sure at least first distance calulated is saved right_dist_min=1e15; top_dist_min=1e15; bottom_dist_min=1e15; for (j=0;j<array_num;j++) { if ((dim_switch_3d==0)) { dist= pow(pow((*(x+min_index))- (*(x+j)), 2.0) + pow((*(y+min_index))- (*(y+j)) , 2.0),0.5); } else { dist= pow(pow((*(x+min_index))- (*(x+j)), 2.0) + pow((*(y+min_index))- (*(y+j)),2.0 ) + pow((*(z+min_index))- (*(z+j)) , 2.0),0.5); } if ((*(x+j))<(*(x+min_index)) && (dist < left_dist_min) ) { left_block_index=j; left_dist_min=dist; } else if ((*(x+j))>(*(x+min_index)) && (dist < right_dist_min)) { right_block_index=j; right_dist_min=dist; } if ((*(y+j))<(*(y+min_index)) && (dist < bottom_dist_min) ) { bottom_block_index=j; bottom_dist_min=dist; } else if ((*(y+j))>(*(y+min_index)) && (dist < top_dist_min) ) { top_block_index=j; top_dist_min=dist; } } all_adjacent_block_indexes[0]=left_block_index; all_adjacent_block_indexes[1]=right_block_index; all_adjacent_block_indexes[2]=bottom_block_index; all_adjacent_block_indexes[3]=top_block_index; //do a weighted average of the 4 nearest grids based on volume v=0; (n_dens_lab_tmp)=0; (n_vx_tmp)= 0; (n_vy_tmp)= 0; (n_temp_tmp)= 0; (n_vz_tmp)= 0; for (j=0;j<4;j++) { if (riken_switch==0) { //using FLASH dv=2.0*M_PI*(*(x+all_adjacent_block_indexes[j]))*pow(*(szx+all_adjacent_block_indexes[j]),2.0) ; } else { r=pow(pow((*(x+all_adjacent_block_indexes[j])),2.0)+pow((*(y+all_adjacent_block_indexes[j])),2.0), 0.5); theta=atan2((*(x+all_adjacent_block_indexes[j])), (*(y+all_adjacent_block_indexes[j]))); dv=2.0*M_PI*pow(r,2)*sin(theta)*(*(szx+all_adjacent_block_indexes[j]))*(*(szy+all_adjacent_block_indexes[j])) ; } v+=dv; //save values (n_dens_lab_tmp)+= (*(dens_lab+all_adjacent_block_indexes[j]))*dv; (n_vx_tmp)+= (*(velx+all_adjacent_block_indexes[j]))*dv; (n_vy_tmp)+= (*(vely+all_adjacent_block_indexes[j]))*dv; (n_temp_tmp)+= (*(temp+all_adjacent_block_indexes[j]))*dv; if (dim_switch_3d==1) { (n_vz_tmp)+= (*(velz+all_adjacent_block_indexes[j]))*dv; } } //fprintf(fPtr,"Outside\n"); //save values (n_dens_lab_tmp)/= v; (n_vx_tmp)/= v; (n_vy_tmp)/= v; (n_temp_tmp)/= v; if (dim_switch_3d==1) { (n_vz_tmp)/= v; } if (dim_switch_3d==0) { fl_v_x=n_vx_tmp*cos(ph_phi); fl_v_y=n_vx_tmp*sin(ph_phi); fl_v_z=n_vy_tmp; } else { fl_v_x=n_vx_tmp; fl_v_y=n_vy_tmp; fl_v_z=n_vz_tmp; } fl_v_norm=pow(pow(fl_v_x, 2.0)+pow(fl_v_y, 2.0)+pow(fl_v_z, 2.0), 0.5); ph_v_norm=pow(pow(((ph+i)->p1), 2.0)+pow(((ph+i)->p2), 2.0)+pow(((ph+i)->p3), 2.0), 0.5); //(*(n_cosangle+i))=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //find cosine of the angle between the photon and the fluid velocities via a dot product (n_cosangle)=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //make 1 for cylindrical otherwise its undefined if (dim_switch_3d==0) { beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)),0.5); } else { beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)+pow((n_vz_tmp),2)),0.5); } //put this in to double check that random number is between 0 and 1 (exclusive) because there was a problem with this for parallel case rnd_tracker=0; rnd_tracker=gsl_rng_uniform_pos(rng[omp_get_thread_num()]); mfp=(-1)*(M_P/((n_dens_lab_tmp))/THOMP_X_SECT/(1.0-beta*((n_cosangle))))*log(rnd_tracker) ; //calulate the mfp and then multiply it by the ln of a random number to simulate distribution of mean free paths #pragma omp critical if ( mfp<min_mfp) { min_mfp=mfp; n_dens_lab_min= n_dens_lab_tmp; n_vx_min= n_vx_tmp; n_vy_min= n_vy_tmp; if (dim_switch_3d==1) { n_vz_min= n_vz_tmp; } n_temp_min= n_temp_tmp; index=i; //fprintf(fPtr, "Thread is %d. new min: %e for photon %d with block properties: %e, %e, %e Located at: %e, %e, Dist: %e\n", omp_get_thread_num(), mfp, index, n_vx_tmp, n_vy_tmp, n_temp_tmp, *(x+min_index), *(y+min_index), dist_min); //fflush(fPtr); #pragma omp flush(min_mfp) } } //free rand number generator for (i=1;i<num_thread;i++) { gsl_rng_free(rng[i]); } free(rng); *(n_dens_lab)= n_dens_lab_min; *(n_vx)= n_vx_min; *(n_vy)= n_vy_min; if (dim_switch_3d==1) { *(n_vz)= n_vz_min; } *(n_temp)= n_temp_min; (*time_step)=min_mfp/C_LIGHT; return index; } void updatePhotonPosition(struct photon *ph, int num_ph, double t, FILE *fPtr) { //move photons by speed of light int i=0, num_thread=omp_get_num_threads(); double old_position=0, new_position=0, divide_p0=0; #pragma omp parallel for num_threads(num_thread) firstprivate(old_position, new_position, divide_p0) for (i=0;i<num_ph;i++) { old_position= pow( pow(ph->r0,2)+pow(ph->r1,2)+pow(ph->r2,2), 0.5 ); divide_p0=1.0/((ph+i)->p0); ((ph+i)->r0)+=((ph+i)->p1)*divide_p0*C_LIGHT*t; //update x position ((ph+i)->r1)+=((ph+i)->p2)*divide_p0*C_LIGHT*t;//update y ((ph+i)->r2)+=((ph+i)->p3)*divide_p0*C_LIGHT*t;//update z new_position= pow( pow(ph->r0,2)+pow(ph->r1,2)+pow(ph->r2,2), 0.5 ); if ((new_position-old_position)/t > C_LIGHT) { fprintf(fPtr, "PHOTON NUMBER %d IS SUPERLUMINAL. ITS SPEED IS %e c.\n", i, ((new_position-old_position)/t)/C_LIGHT); } //printf("In update function: %e, %e, %e, %e, %e, %e, %e\n",((ph+i)->r0), ((ph+i)->r1), ((ph+i)->r2), t, ((ph+i)->p1)/((ph+i)->p0), ((ph+i)->p2)/((ph+i)->p0), ((ph+i)->p3)/((ph+i)->p0) ); } //printf("In update function: %e, %e, %e, %e\n",t, ((ph)->p1)/((ph)->p0), ((ph)->p2)/((ph)->p0), ((ph)->p3)/((ph)->p0) ); } void photonScatter(struct photon *ph, double flash_vx, double flash_vy, double flash_vz, double fluid_temp, gsl_rng * rand,int dim_switch_3d, FILE *fPtr) { //function to perform single photon scattering double ph_phi=0; double *ph_p=malloc(4*sizeof(double)); //pointer to hold only photon 4 momentum @ start double *el_p_comov=malloc(4*sizeof(double));//pointer to hold the electron 4 momenta in comoving frame double *ph_p_comov=malloc(4*sizeof(double));//pointer to hold the comoving photon 4 momenta double *fluid_beta=malloc(3*sizeof(double));//pointer to hold fluid velocity vector double *negative_fluid_beta=malloc(3*sizeof(double));//pointer to hold negative fluid velocity vector ph_phi=atan2((ph->r1), ((ph->r0))); /* fprintf(fPtr,"ph_phi=%e\n", ph_phi); fflush(fPtr); */ //convert flash coordinated into MCRaT coordinates //printf("Getting fluid_beta\n"); if (dim_switch_3d==0) { (*(fluid_beta+0))=flash_vx*cos(ph_phi); (*(fluid_beta+1))=flash_vx*sin(ph_phi); (*(fluid_beta+2))=flash_vy; } else { (*(fluid_beta+0))=flash_vx; (*(fluid_beta+1))=flash_vy; (*(fluid_beta+2))=flash_vz; } /* fprintf(fPtr,"FLASH v: %e, %e\n", flash_vx,flash_vy); fflush(fPtr); */ //fill in photon 4 momentum //printf("filling in 4 momentum in photonScatter\n"); *(ph_p+0)=(ph->p0); *(ph_p+1)=(ph->p1); *(ph_p+2)=(ph->p2); *(ph_p+3)=(ph->p3); /* fprintf(fPtr,"Unscattered Photon in Lab frame: %e, %e, %e,%e, %e, %e, %e\n", *(ph_p+0), *(ph_p+1), *(ph_p+2), *(ph_p+3), (ph->r0), (ph->r1), (ph->r2)); fflush(fPtr); fprintf(fPtr,"Fluid Beta: %e, %e, %e\n", *(fluid_beta+0),*(fluid_beta+1), *(fluid_beta+2)); fflush(fPtr); */ //first we bring the photon to the fluid's comoving frame lorentzBoost(fluid_beta, ph_p, ph_p_comov, 'p', fPtr); /* fprintf(fPtr,"Old: %e, %e, %e,%e\n", ph->p0, ph->p1, ph->p2, ph->p3); fflush(fPtr); fprintf(fPtr, "Before Scattering, In Comov_frame:\n"); fflush(fPtr); fprintf(fPtr, "ph_comov: %e, %e, %e,%e\n", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3)); fflush(fPtr); */ //second we generate a thermal electron at the correct temperature singleElectron(el_p_comov, fluid_temp, ph_p_comov, rand, fPtr); //fprintf(fPtr,"el_comov: %e, %e, %e,%e\n", *(el_p_comov+0), *(el_p_comov+1), *(el_p_comov+2), *(el_p_comov+3)); //fflush(fPtr); //third we perform the scattering and save scattered photon 4 monetum in ph_p_comov @ end of function singleComptonScatter(el_p_comov, ph_p_comov, rand, fPtr); //fprintf(fPtr,"After Scattering, After Lorentz Boost to Comov frame: %e, %e, %e,%e\n", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3)); //fflush(fPtr); //fourth we bring the photon back to the lab frame *(negative_fluid_beta+0)=-1*( *(fluid_beta+0)); *(negative_fluid_beta+1)=-1*( *(fluid_beta+1)); *(negative_fluid_beta+2)=-1*( *(fluid_beta+2)); lorentzBoost(negative_fluid_beta, ph_p_comov, ph_p, 'p', fPtr); //fprintf(fPtr,"Scattered Photon in Lab frame: %e, %e, %e,%e\n", *(ph_p+0), *(ph_p+1), *(ph_p+2), *(ph_p+3)); fflush(fPtr); if (((*(ph_p+0))*C_LIGHT/1.6e-9) > 1e4) { fprintf(fPtr,"Extremely High Photon Energy!!!!!!!!\n"); fflush(fPtr); } //fprintf(fPtr,"Old: %e, %e, %e,%e\n", ph->p0, ph->p1, ph->p2, ph->p3); //fprintf(fPtr, "Old: %e, %e, %e,%e\n", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3)); //assign the photon its new lab 4 momentum (ph->p0)=(*(ph_p+0)); (ph->p1)=(*(ph_p+1)); (ph->p2)=(*(ph_p+2)); (ph->p3)=(*(ph_p+3)); //printf("Done assigning values to original struct\n"); free(el_p_comov); free(ph_p_comov); free(fluid_beta); free(negative_fluid_beta); free(ph_p); ph_p=NULL;negative_fluid_beta=NULL;ph_p_comov=NULL; el_p_comov=NULL; } void singleElectron(double *el_p, double temp, double *ph_p, gsl_rng * rand, FILE *fPtr) { //generates an electron with random energy double factor=0, gamma=0; double y_dum=0, f_x_dum=0, x_dum=0, beta_x_dum=0, beta=0, phi=0, theta=0, ph_theta=0, ph_phi=0; gsl_matrix *rot= gsl_matrix_calloc (3, 3); //create matrix thats 3x3 to do rotation gsl_vector_view el_p_prime ; //create vector to hold rotated electron 4 momentum gsl_vector *result=gsl_vector_alloc (3); //fprintf(fPtr, "Temp in singleElectron: %e\n", temp); if (temp>= 1e7) { //printf("In if\n"); factor=K_B*temp/(M_EL*pow(C_LIGHT,2.0)); y_dum=1; //initalize loop to get a random gamma from the distribution of electron velocities f_x_dum=0; while ((isnan(f_x_dum) !=0) || (y_dum>f_x_dum) ) { x_dum=gsl_rng_uniform_pos(rand)*(1+100*factor); beta_x_dum=pow(1-(pow(x_dum, -2.0)) ,0.5); y_dum=gsl_rng_uniform(rand)/2.0; f_x_dum=pow(x_dum,2)*(beta_x_dum/gsl_sf_bessel_Kn (2, 1.0/factor))*exp(-1*x_dum/factor); //not sure if this is right is giving small values of gamma -> beta=nan //fprintf(fPtr,"Choosing a Gamma: xdum: %e, f_x_dum: %e, y_dum: %e\n", x_dum, f_x_dum, y_dum); } gamma=x_dum; } else { //printf("In else\n"); factor=pow(K_B*temp/M_EL,0.5); //calculate a random gamma from 3 random velocities drawn from a gaussian distribution with std deviation of "factor" gamma=pow( 1- (pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2)+ pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2)+pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2) ) ,-0.5); } //fprintf(fPtr,"Chosen Gamma: %e\n",gamma); beta=pow( 1- (1/pow( gamma,2.0 )) ,0.5); //printf("Beta is: %e in singleElectron\n", beta); phi=gsl_rng_uniform(rand)*2*M_PI; y_dum=1; //initalize loop to get a random theta f_x_dum=0; while (y_dum>f_x_dum) { y_dum=gsl_rng_uniform(rand)*1.3; x_dum=gsl_rng_uniform(rand)*M_PI; f_x_dum=sin(x_dum)*(1-(beta*cos(x_dum))); } theta=x_dum; //fprintf(fPtr,"Beta: %e\tPhi: %e\tTheta: %e\n",beta,phi, theta); //fill in electron 4 momentum NOT SURE WHY THE ORDER IS AS SUCH SEEMS TO BE E/c, pz,py,px!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! *(el_p+0)=gamma*(M_EL)*(C_LIGHT); *(el_p+1)=gamma*(M_EL)*(C_LIGHT)*beta*cos(theta); *(el_p+2)=gamma*(M_EL)*(C_LIGHT)*beta*sin(theta)*sin(phi); *(el_p+3)=gamma*(M_EL)*(C_LIGHT)*beta*sin(theta)*cos(phi); //printf("Old: %e, %e, %e,%e\n", *(el_p+0), *(el_p+1), *(el_p+2), *(el_p+3)); el_p_prime=gsl_vector_view_array((el_p+1), 3); //find angles of photon NOT SURE WHY WERE CHANGING REFERENCE FRAMES HERE???!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ph_phi=atan2(*(ph_p+2), *(ph_p+3)); //Double Check ph_theta=atan2(pow( pow(*(ph_p+2),2)+ pow(*(ph_p+3),2) , 0.5) , (*(ph_p+1)) ); //printf("Calculated Photon phi and theta in singleElectron:%e, %e\n", ph_phi, ph_theta); //fill in rotation matrix to rotate around x axis to get rid of phi angle gsl_matrix_set(rot, 1,1,1); gsl_matrix_set(rot, 2,2,cos(ph_theta)); gsl_matrix_set(rot, 0,0,cos(ph_theta)); gsl_matrix_set(rot, 0,2,-sin(ph_theta)); gsl_matrix_set(rot, 2,0,sin(ph_theta)); gsl_blas_dgemv(CblasNoTrans, 1, rot, &el_p_prime.vector, 0, result); /* printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot, 0,0), gsl_matrix_get(rot, 0,1), gsl_matrix_get(rot, 0,2)); printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot, 1,0), gsl_matrix_get(rot, 1,1), gsl_matrix_get(rot, 1,2)); printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot, 2,0), gsl_matrix_get(rot, 2,1), gsl_matrix_get(rot, 2,2)); printf("Middle: %e, %e, %e,%e\n", *(el_p+0), gsl_vector_get(result,0), gsl_vector_get(result,1), gsl_vector_get(result,2)); */ gsl_matrix_set_all(rot,0); gsl_matrix_set(rot, 0,0,1); gsl_matrix_set(rot, 1,1,cos(-ph_phi)); gsl_matrix_set(rot, 2,2,cos(-ph_phi)); gsl_matrix_set(rot, 1,2,-sin(-ph_phi)); gsl_matrix_set(rot, 2,1,sin(-ph_phi)); gsl_blas_dgemv(CblasNoTrans, 1, rot, result, 0, &el_p_prime.vector); /* printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot, 0,0), gsl_matrix_get(rot, 0,1), gsl_matrix_get(rot, 0,2)); printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot, 1,0), gsl_matrix_get(rot, 1,1), gsl_matrix_get(rot, 1,2)); printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot, 2,0), gsl_matrix_get(rot, 2,1), gsl_matrix_get(rot, 2,2)); printf("Final EL_P_vec: %e, %e, %e,%e\n", *(el_p+0), gsl_vector_get(&el_p_prime.vector,0), gsl_vector_get(&el_p_prime.vector,1), gsl_vector_get(&el_p_prime.vector,2)); */ gsl_matrix_free (rot);gsl_vector_free(result); } void singleComptonScatter(double *el_comov, double *ph_comov, gsl_rng * rand, FILE *fPtr) { //This routine performs a Compton scattering between a photon and a moving electron. int i=0; double *el_v=malloc(3*sizeof(double)); double *negative_el_v=malloc(3*sizeof(double)); double *ph_p_prime=malloc(4*sizeof(double));//use this to keep track of how the ph 4 momentum changes with each rotation double *el_p_prime=malloc(4*sizeof(double)); double phi0=0, phi1=0, phi=0, theta=0; double y_dum, f_x_dum, x_dum; gsl_matrix *rot0= gsl_matrix_calloc (3, 3); //create matricies thats 3x3 to do rotations gsl_matrix *rot1= gsl_matrix_calloc (3, 3); gsl_vector *result0=gsl_vector_alloc (3); //vectors to hold results of rotations gsl_vector *result1=gsl_vector_alloc (3); gsl_vector *result=gsl_vector_alloc (4); gsl_vector *whole_ph_p=gsl_vector_alloc (4); gsl_vector_view ph_p ; //create vector to hold comoving photon and electron 4 momentum gsl_vector_view el_p ; //fill in electron velocity array and photon 4 momentum *(el_v+0)=(*(el_comov+1))/(*(el_comov+0)); *(el_v+1)=(*(el_comov+2))/(*(el_comov+0)); *(el_v+2)=(*(el_comov+3))/(*(el_comov+0)); //printf("el_v: %e, %e, %e\n", *(el_v+0), *(el_v+1), *(el_v+2)); //lorentz boost into frame where the electron is stationary lorentzBoost(el_v, el_comov, el_p_prime, 'e', fPtr); lorentzBoost(el_v, ph_comov, ph_p_prime, 'p', fPtr); //printf("New ph_p in electron rest frame: %e, %e, %e,%e\n", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3)); ph_p=gsl_vector_view_array((ph_p_prime+1), 3); el_p=gsl_vector_view_array(el_p_prime,4); phi0=atan2(*(ph_p_prime+2), *(ph_p_prime+1) ); //printf("Photon Phi: %e\n", phi0); //rotate the axes so that the photon incomes along the x-axis gsl_matrix_set(rot0, 2,2,1); gsl_matrix_set(rot0, 0,0,cos(-phi0)); gsl_matrix_set(rot0, 1,1,cos(-phi0)); gsl_matrix_set(rot0, 0,1,-sin(-phi0)); gsl_matrix_set(rot0, 1,0,sin(-phi0)); gsl_blas_dgemv(CblasNoTrans, 1, rot0, &ph_p.vector, 0, result0); /* printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot0, 0,0), gsl_matrix_get(rot0, 0,1), gsl_matrix_get(rot0, 0,2)); printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot0, 1,0), gsl_matrix_get(rot0, 1,1), gsl_matrix_get(rot0, 1,2)); printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot0, 2,0), gsl_matrix_get(rot0, 2,1), gsl_matrix_get(rot0, 2,2)); */ //set values of ph_p_prime equal to the result and get new phi from result *(ph_p_prime+1)=gsl_vector_get(result0,0); *(ph_p_prime+2)=0;//gsl_vector_get(result,1); //just directly setting it to 0 now? *(ph_p_prime+3)=gsl_vector_get(result0,2); phi1=atan2(gsl_vector_get(result0,2), gsl_vector_get(result0,0)); /* printf("rotation 1: %e, %e, %e\n", *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3)); printf("Photon Phi: %e\n", phi1); printf("make sure the vector view is good: %e, %e, %e,%e\n", *(ph_p_prime+0), gsl_vector_get(&ph_p.vector,0), gsl_vector_get(&ph_p.vector,1), gsl_vector_get(&ph_p.vector,2)); */ //rotate around y to bring it all along x gsl_matrix_set(rot1, 1,1,1); gsl_matrix_set(rot1, 0,0,cos(-phi1)); gsl_matrix_set(rot1, 2,2,cos(-phi1)); gsl_matrix_set(rot1, 0,2,-sin(-phi1)); gsl_matrix_set(rot1, 2,0,sin(-phi1)); gsl_blas_dgemv(CblasNoTrans, 1, rot1, &ph_p.vector, 0, result1); /* printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot1, 0,0), gsl_matrix_get(rot1, 0,1), gsl_matrix_get(rot1, 0,2)); printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot1, 1,0), gsl_matrix_get(rot1, 1,1), gsl_matrix_get(rot1, 1,2)); printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot1, 2,0), gsl_matrix_get(rot1, 2,1), gsl_matrix_get(rot1, 2,2)); */ //set values of ph_p_prime equal to the result and get new phi from result *(ph_p_prime+1)=*(ph_p_prime+0);//why setting it to the energy? *(ph_p_prime+2)=gsl_vector_get(result1,1); *(ph_p_prime+3)=0; //just directly setting it to 0 now? //printf("rotation 2: %e, %e, %e, %e\n", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3)); //generate random theta and phi angles for scattering phi=gsl_rng_uniform(rand)*2*M_PI; //printf("Phi: %e\n", phi); y_dum=1; //initalize loop to get a random theta f_x_dum=0; while (y_dum>f_x_dum) { y_dum=gsl_rng_uniform(rand)*1.09; x_dum=gsl_rng_uniform(rand)*M_PI; f_x_dum=sin(x_dum)*(1+pow(cos(x_dum),2)); } theta=x_dum; //printf("Theta: %e\n", theta); //perform scattering and compute new 4-momenta of electron and photon //scattered photon 4 momentum gsl_vector_set(result, 0, (*(ph_p_prime+0))/(1+ (( (*(ph_p_prime+0))*(1-cos(theta)) )/(M_EL*C_LIGHT )) ) ); //DOUBLE CHECK HERE!!!! gsl_vector_set(result, 1, gsl_vector_get(result,0)*cos(theta) ); gsl_vector_set(result, 2, gsl_vector_get(result,0)*sin(theta)*sin(phi) ); gsl_vector_set(result, 3, gsl_vector_get(result,0)*sin(theta)*cos(phi) ); //printf("%e\n", gsl_vector_get(result,0)); //calculate electron 4 momentum OPTIMIZE HERE: DONT USE A FOR LOOP HERE!!!! Done //prescattered photon 4 momentum gsl_vector_set(whole_ph_p, 0, (*(ph_p_prime+0))); gsl_vector_set(whole_ph_p, 1, (*(ph_p_prime+1))); gsl_vector_set(whole_ph_p, 2, (*(ph_p_prime+2))); gsl_vector_set(whole_ph_p, 3, (*(ph_p_prime+3))); /* for (i=0;i<4;i++) { gsl_vector_set(whole_ph_p, i, (*(ph_p_prime+i))); } */ gsl_vector_sub(whole_ph_p,result); //resut is saved into ph_p vector, unscattered-scattered 4 mometum of photon gsl_vector_add(&el_p.vector ,whole_ph_p); /* printf("After scattering:\n"); printf("el_p: %e, %e, %e,%e\n", gsl_vector_get(&el_p.vector,0), gsl_vector_get(&el_p.vector,1), gsl_vector_get(&el_p.vector,2), gsl_vector_get(&el_p.vector,3)); printf("ph_p: %e, %e, %e,%e\n", gsl_vector_get(result,0), gsl_vector_get(result,1), gsl_vector_get(result,2), gsl_vector_get(result,3)); */ //rotate back to comoving frame *(ph_p_prime+0)=gsl_vector_get(result,0); *(ph_p_prime+1)=gsl_vector_get(result,1); //set values of photon prime momentum from doing the scattering to use the vector view of it in dot product *(ph_p_prime+2)=gsl_vector_get(result,2); *(ph_p_prime+3)=gsl_vector_get(result,3); gsl_matrix_set_all(rot1,0); gsl_matrix_set(rot1, 1,1,1); gsl_matrix_set(rot1, 0,0,cos(-phi1)); gsl_matrix_set(rot1, 2,2,cos(-phi1)); gsl_matrix_set(rot1, 0,2,sin(-phi1)); gsl_matrix_set(rot1, 2,0,-sin(-phi1)); gsl_blas_dgemv(CblasNoTrans, 1, rot1, &ph_p.vector, 0, result1); /* printf("Photon Phi: %e\n", phi1); printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot1, 0,0), gsl_matrix_get(rot1, 0,1), gsl_matrix_get(rot1, 0,2)); printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot1, 1,0), gsl_matrix_get(rot1, 1,1), gsl_matrix_get(rot1, 1,2)); printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot1, 2,0), gsl_matrix_get(rot1, 2,1), gsl_matrix_get(rot1, 2,2)); */ //set values of ph_p_prime to result1 from undoing 2nd rotation *(ph_p_prime+1)=gsl_vector_get(result1,0); *(ph_p_prime+2)=gsl_vector_get(result1,1); *(ph_p_prime+3)=gsl_vector_get(result1,2); //printf("Undo rotation 2: %e, %e, %e, %e\n", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3)); //ignore the electron, dont care about it, undo the first rotation gsl_matrix_set_all(rot0,0); gsl_matrix_set(rot0, 2,2,1); gsl_matrix_set(rot0, 0,0,cos(-phi0)); gsl_matrix_set(rot0, 1,1,cos(-phi0)); gsl_matrix_set(rot0, 0,1,sin(-phi0)); gsl_matrix_set(rot0, 1,0,-sin(-phi0)); gsl_blas_dgemv(CblasNoTrans, 1, rot0, &ph_p.vector, 0, result0); /* printf("Photon Phi: %e\n", phi0); printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot0, 0,0), gsl_matrix_get(rot0, 0,1), gsl_matrix_get(rot0, 0,2)); printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot0, 1,0), gsl_matrix_get(rot0, 1,1), gsl_matrix_get(rot0, 1,2)); printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot0, 2,0), gsl_matrix_get(rot0, 2,1), gsl_matrix_get(rot0, 2,2)); */ *(ph_p_prime+1)=gsl_vector_get(result0,0); *(ph_p_prime+2)=gsl_vector_get(result0,1); *(ph_p_prime+3)=gsl_vector_get(result0,2); //printf("Undo rotation 1: %e, %e, %e, %e\n", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3)); //deboost photon to lab frame *(negative_el_v+0)=(-1*(*(el_v+0))); *(negative_el_v+1)=(-1*(*(el_v+1))); *(negative_el_v+2)=(-1*(*(el_v+2))); lorentzBoost(negative_el_v, ph_p_prime, ph_comov, 'p', fPtr); //printf("Undo boost 1: %e, %e, %e, %e\n", *(ph_comov+0), *(ph_comov+1), *(ph_comov+2), *(ph_comov+3)); gsl_matrix_free(rot0); gsl_matrix_free(rot1);gsl_vector_free(result0);gsl_vector_free(result1);gsl_vector_free(result); //gsl_rng_free (rand); gsl_vector_free(whole_ph_p);free(ph_p_prime);free(el_p_prime);free(el_v); free(negative_el_v); } double averagePhotonEnergy(struct photon *ph, int num_ph) { //to calculate weighted photon energy int i=0; double e_sum=0, w_sum=0; for (i=0;i<num_ph;i++) { e_sum+=(((ph+i)->p0)*((ph+i)->weight)); w_sum+=((ph+i)->weight); } return (e_sum*C_LIGHT)/w_sum; } void phScattStats(struct photon *ph, int ph_num, int *max, int *min, double *avg, double *r_avg ) { int temp_max=0, temp_min=-1, i=0; double sum=0, avg_r_sum=0; for (i=0;i<ph_num;i++) { sum+=((ph+i)->num_scatt); avg_r_sum+=pow(((ph+i)->r0)*((ph+i)->r0) + ((ph+i)->r1)*((ph+i)->r1) + ((ph+i)->r2)*((ph+i)->r2), 0.5); if (((ph+i)->num_scatt) > temp_max ) { temp_max=((ph+i)->num_scatt); //printf("The new max is: %d\n", temp_max); } if ((i==0) || (((ph+i)->num_scatt)<temp_min)) { temp_min=((ph+i)->num_scatt); //printf("The new min is: %d\n", temp_min); } } *avg=sum/ph_num; *r_avg=avg_r_sum/ph_num; *max=temp_max; *min=temp_min; } void cylindricalPrep(double *gamma, double *vx, double *vy, double *dens, double *dens_lab, double *pres, double *temp, int num_array) { double gamma_infinity=100, t_comov=1*pow(10, 5), ddensity=3e-7;// the comoving temperature in Kelvin, and the comoving density in g/cm^2 int i=0; double vel=pow(1-pow(gamma_infinity, -2.0) ,0.5), lab_dens=gamma_infinity*ddensity; for (i=0; i<num_array;i++) { *(gamma+i)=gamma_infinity; *(vx+i)=0; *(vy+i)=vel; *(dens+i)=ddensity; *(dens_lab+i)=lab_dens; *(pres+i)=(A_RAD*pow(t_comov, 4.0))/(3*pow(C_LIGHT, 2.0)); *(temp+i)=pow(3*(*(pres+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0); //just assign t_comov } } void sphericalPrep(double *r, double *x, double *y, double *gamma, double *vx, double *vy, double *dens, double *dens_lab, double *pres, double *temp, int num_array, FILE *fPtr) { double gamma_infinity=100, lumi=1e52, r00=1e8; double vel=0; int i=0; for (i=0;i<num_array;i++) { if ((*(r+i)) >= (r00*gamma_infinity)) { *(gamma+i)=gamma_infinity; *(pres+i)=(lumi*pow(r00, 2.0/3.0)*pow(*(r+i), -8.0/3.0) )/(12.0*M_PI*C_LIGHT*pow(gamma_infinity, 4.0/3.0)*pow(C_LIGHT, 2.0)); } else { *(gamma+i)=(*(r+i))/r00; *(pres+i)=(lumi*pow(r00, 2.0))/(12.0*M_PI*C_LIGHT*pow(C_LIGHT, 2.0)*pow(*(r+i), 4.0) ); } vel=pow(1-(pow(*(gamma+i), -2.0)) ,0.5); *(vx+i)=(vel*(*(x+i)))/pow(pow(*(x+i), 2)+ pow(*(y+i), 2) ,0.5); *(vy+i)=(vel*(*(y+i)))/pow(pow(*(x+i), 2)+ pow(*(y+i), 2) ,0.5); *(dens+i)=lumi/(4*M_PI*pow(*(r+i), 2.0)*pow(C_LIGHT, 3.0)*gamma_infinity*(*(gamma+i))); *(dens_lab+i)=(*(dens+i))*(*(gamma+i)); *(temp+i)=pow(3*(*(pres+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0); //fprintf(fPtr,"Gamma: %lf\nR: %lf\nPres: %e\nvel %lf\nX: %lf\nY %lf\nVx: %lf\nVy: %lf\nDens: %e\nLab_Dens: %e\nTemp: %lf\n", *(gamma+i), *(r+i), *(pres+i), vel, *(x+i), *(y+i), *(vx+i), *(vy+i), *(dens+i), *(dens_lab+i), *(temp+i)); } } void dirFileMerge(char dir[200], int start_frame, int last_frame, int numprocs, int angle_id, int dim_switch, int riken_switch, FILE *fPtr ) { //function to merge files in mcdir produced by various threads int i=0, j=0, k=0, num_files=8, num_thread=8; //omp_get_max_threads() number of files is number of types of mcdata files there are int increment=1; char filename_k[2000]="", file_no_thread_num[2000]="", cmd[2000]="", mcdata_type[200]=""; //printf("Merging files in %s\n", dir); //#pragma omp parallel for num_threads(num_thread) firstprivate( filename_k, file_no_thread_num, cmd,mcdata_type,num_files, increment ) private(i,j,k) // i < last frame because calculation before this function gives last_frame as the first frame of the next process set of frames to merge files for for (i=start_frame;i<last_frame;i=i+increment) { fprintf(fPtr, "Merging files for frame: %d\n", i); fflush(fPtr); if ((riken_switch==1) && (dim_switch==1) && (i>=3000)) { increment=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 } for (j=0;j<num_files;j=j+1) { switch (j) { case 0: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P0"); break; case 1: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P1");break; case 2: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P2"); break; case 3: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P3"); break; case 4: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R0"); break; case 5: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R1"); break; case 6: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R2"); break; case 7: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "NS"); break; } for (k=0;k<numprocs;k++) { snprintf(file_no_thread_num,sizeof(file_no_thread_num),"%s%s%d%s%s%s", dir,"mcdata_",i,"_", mcdata_type,".dat"); snprintf(filename_k,sizeof(filename_k),"%s%s%d%s%s%s%d%s", dir,"mcdata_",i,"_", mcdata_type ,"_",k, ".dat"); //check if both the file exists if (( access( filename_k, F_OK ) != -1 ) ) { //if they both do make command to cat the together always in the same order //fprintf(fPtr, "Merging: %s\n", filename_k); snprintf(cmd, sizeof(cmd), "%s%s %s%s", "cat ", filename_k, " >> ", file_no_thread_num); system(cmd); } //remove file snprintf(cmd, sizeof(cmd), "%s%s", "rm ", filename_k); system(cmd); } } } if (angle_id==0) { //merge photon weight files for (k=0;k<numprocs;k++) { snprintf(file_no_thread_num,sizeof(file_no_thread_num),"%s%s", dir,"mcdata_PW.dat"); snprintf(filename_k,sizeof(filename_k),"%s%s%d%s", dir,"mcdata_PW_",k,".dat"); if (( access( filename_k, F_OK ) != -1 ) ) { //if they both do make command to cat the together always in the same order snprintf(cmd, sizeof(cmd), "%s%s %s%s", "cat ", filename_k, " >> ", file_no_thread_num); system(cmd); } //remove files snprintf(cmd, sizeof(cmd), "%s%s", "rm ", filename_k); system(cmd); } } } void modifyFlashName(char flash_file[200], char prefix[200], int frame, int dim_switch) { int lim1=0, lim2=0, lim3=0; if (dim_switch==0) { //2D case lim1=10; lim2=100; lim3=1000; } else { //3d case lim1=100; lim2=1000; lim3=10000; } if (frame<lim1) { snprintf(flash_file,200, "%s%.3d%d",prefix,000,frame); } else if (frame<lim2) { snprintf(flash_file,200, "%s%.2d%d",prefix,00,frame); } else if (frame<lim3) { snprintf(flash_file,200, "%s%d%d",prefix,0,frame); } else { snprintf(flash_file,200, "%s%d",prefix,frame); } } void readHydro2D(char hydro_prefix[200], int frame, double r_inj, double fps, double **x, double **y, double **szx, double **szy, double **r, double **theta, double **velx, double **vely, double **dens, double **pres, double **gamma, double **dens_lab, double **temp, int *number, int ph_inj_switch, double min_r, double max_r, FILE *fPtr) { FILE *hydroPtr=NULL; char hydrofile[200]="", file_num[200]="", full_file[200]="", file_end[200]="" ; char buf[10]=""; int i=0, j=0, k=0, elem=0, elem_factor=0; int all_index_buffer=0, r_min_index=0, r_max_index=0, theta_min_index=0, theta_max_index=0; //all_index_buffer contains phi_min, phi_max, theta_min, theta_max, r_min, r_max indexes to get from grid files int r_index=0, theta_index=0; float buffer=0; float *dens_unprc=NULL,*vel_r_unprc=NULL, *vel_theta_unprc=NULL,*pres_unprc=NULL; double ph_rmin=0, ph_rmax=0; double r_in=1e10; //double *r_edge=malloc(sizeof(double)*(R_DIM_2D+1)); //double *dr=malloc(sizeof(double)*(R_DIM_2D)); double *r_unprc=malloc(sizeof(double)*R_DIM_2D); double *theta_unprc=malloc(sizeof(double)*THETA_DIM_2D); if (ph_inj_switch==0) { ph_rmin=min_r; ph_rmax=max_r; } snprintf(file_end,sizeof(file_end),"%s","small.data" ); //density snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 1,"-" ); modifyFlashName(file_num, hydrofile, frame,0); fprintf(fPtr,">> Opening file %s\n", file_num); fflush(fPtr); snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end); hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&theta_min_index, sizeof(int)*1, 1,hydroPtr); fread(&theta_max_index, sizeof(int)*1, 1,hydroPtr); fread(&r_min_index, sizeof(int)*1, 1,hydroPtr); fread(&r_max_index, sizeof(int)*1, 1,hydroPtr); fclose(hydroPtr); //fortran indexing starts @ 1, but C starts @ 0 r_min_index--;//=r_min_index-1; r_max_index--;//=r_max_index-1; theta_min_index--;//=theta_min_index-1; theta_max_index--;//=theta_max_index-1; elem=(r_max_index+1-r_min_index)*(theta_max_index+1-theta_min_index); //max index is max number of elements minus 1, there add one to get total number of elements fprintf(fPtr,"Elem %d\n", elem); fprintf(fPtr,"Limits %d, %d, %d, %d, %d, %d\n", all_index_buffer, all_index_buffer, theta_min_index, theta_max_index, r_min_index, r_max_index); fflush(fPtr); //now with number of elements allocate data dens_unprc=malloc(elem*sizeof(float)); vel_r_unprc=malloc(elem*sizeof(float)); vel_theta_unprc=malloc(elem*sizeof(float)); pres_unprc=malloc(elem*sizeof(float)); hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran /* for (i=0;i<elem;i++) { fread((dens_unprc+i), sizeof(float),1, hydroPtr); //read data } */ fread(dens_unprc, sizeof(float),elem, hydroPtr); fclose(hydroPtr); //V_r snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 2,"-" ); modifyFlashName(file_num, hydrofile, frame,0); snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end); hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(vel_r_unprc, sizeof(float),elem, hydroPtr); //data fclose(hydroPtr); //V_theta snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 3,"-" ); modifyFlashName(file_num, hydrofile, frame,0); snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end); hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(vel_theta_unprc, sizeof(float), elem, hydroPtr); //data fclose(hydroPtr); //u04 is phi component but is all 0 //pres snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 8,"-" ); modifyFlashName(file_num, hydrofile, frame,0); snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end); //fprintf(fPtr,">> Opening file %s\n", full_file); //fflush(fPtr); hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran //elem=(r_max_index-r_min_index)*(theta_max_index-theta_min_index); //fprintf(fPtr,"Elem %d\n", elem); //fprintf(fPtr,"Limits %d, %d, %d, %d, %d, %d\n", all_index_buffer, all_index_buffer, theta_min_index, theta_max_index, r_min_index, r_max_index); //fflush(fPtr); fread(pres_unprc, sizeof(float),elem, hydroPtr); //data fclose(hydroPtr); /* for (j=0 ;j<(theta_max_index+1-theta_min_index); j++) { for (k=0; k<(r_max_index+1-r_min_index); k++) { fprintf(fPtr,"Pres %d: %e\n", ( j*(r_max_index+1-r_min_index)+k ), *(pres_unprc+( j*(r_max_index+1-r_min_index)+k ))); //fprintf(fPtr,"Pres %d: %e\n", ( j*(r_max_index)+k ), *(pres_unprc+( j*(r_max_index)+k ))); fflush(fPtr); } } exit(0); */ //R snprintf(hydrofile,sizeof(hydrofile),"%s%s",hydro_prefix,"grid-x1.data" ); hydroPtr=fopen(hydrofile, "r"); //fprintf(fPtr,">> Opening file %s\n", hydrofile); //fflush(fPtr); i=0; while (i<R_DIM_2D) { fscanf(hydroPtr, "%lf", (r_unprc+i)); //read value fgets(buf, 3,hydroPtr); //read comma /* if (i<5) { //printf("Here\n"); fprintf(fPtr,"R %d: %e\n", i, *(r_unprc+i)); fflush(fPtr); } */ i++; } fclose(hydroPtr); //theta from y axis snprintf(hydrofile,sizeof(hydrofile),"%s%s",hydro_prefix,"grid-x2.data" ); hydroPtr=fopen(hydrofile, "r"); //fprintf(fPtr,">> Opening file %s\n", hydrofile); //fflush(fPtr); i=0; while (i<THETA_DIM_2D) { fscanf(hydroPtr, "%lf", (theta_unprc+i)); //read value fgets(buf, 3,hydroPtr); //read comma /* if (i<5) { fprintf(fPtr,"Theta %d: %e\n", i, *(theta_unprc+i)); fflush(fPtr); } */ i++; } fclose(hydroPtr); //limit number of array elements //fill in radius array and find in how many places r > injection radius elem_factor=0; elem=0; while (elem==0) { elem_factor++; elem=0; for (j=0 ;j<(theta_max_index+1-theta_min_index); j++) { for (k=0; k<(r_max_index+1-r_min_index); k++) { i=r_min_index+k; //look at indexes of r that are included in small hydro file //if I have photons do selection differently than if injecting photons if (ph_inj_switch==0) { //if calling this function when propagating photons, choose blocks based on where the photons are if (((ph_rmin - elem_factor*C_LIGHT/fps)<(*(r_unprc+i))) && (*(r_unprc+i) < (ph_rmax + elem_factor*C_LIGHT/fps) )) { // *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k ) elem++; } } else { //if calling this function to inject photons choose blocks based on injection parameters, r_inj, which is sufficient if (((r_inj - C_LIGHT/fps)<(*(r_unprc+i))) && (*(r_unprc+i) < (r_inj + C_LIGHT/fps) )) { // *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k ) elem++; } } } } } fprintf(fPtr, "Number of post restricted Elems: %d %e\n", elem, r_inj); fflush(fPtr); (*pres)=malloc (elem * sizeof (double )); (*velx)=malloc (elem * sizeof (double )); (*vely)=malloc (elem * sizeof (double )); (*dens)=malloc (elem * sizeof (double )); (*x)=malloc (elem * sizeof (double )); (*y)=malloc (elem * sizeof (double )); (*r)=malloc (elem * sizeof (double )); (*theta)=malloc (elem * sizeof (double )); (*gamma)=malloc (elem * sizeof (double )); (*dens_lab)=malloc (elem * sizeof (double )); //szx becomes delta r szy becomes delta theta (*szx)=malloc (elem * sizeof (double )); (*szy)=malloc (elem * sizeof (double )); (*temp)=malloc (elem * sizeof (double )); elem=0; for (j=0 ;j<(theta_max_index+1-theta_min_index); j++) { for (k=0; k<(r_max_index+1-r_min_index); k++) { r_index=r_min_index+k; //look at indexes of r that are included in small hydro file theta_index=theta_min_index+j; if (ph_inj_switch==0) { if (((ph_rmin - elem_factor*C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (ph_rmax + elem_factor*C_LIGHT/fps) )) { (*pres)[elem]=*(pres_unprc+( j*(r_max_index+1-r_min_index)+k )); (*velx)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index))+(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index)); (*vely)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index))-(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index)); (*dens)[elem]=*(dens_unprc+( j*(r_max_index+1-r_min_index)+k )); (*x)[elem]=(*(r_unprc+r_index))*sin(*(theta_unprc+theta_index)); (*y)[elem]=(*(r_unprc+r_index))*cos(*(theta_unprc+theta_index)); (*r)[elem]=*(r_unprc+r_index); (*szx)[elem]=(*(r_unprc+r_index))*((M_PI/2)/2000); (*szy)[elem]=(M_PI/2)/2000; (*theta)[elem]=*(theta_unprc+theta_index);//theta in radians in relation to jet axis (*gamma)[elem]=pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1); //v is in units of c (*dens_lab)[elem]= (*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ))) * pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1); (*temp)[elem]=pow(3*(*(pres_unprc+( j*(r_max_index+1-r_min_index)+k )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0); elem++; } } else { if (((r_inj - C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (r_inj + C_LIGHT/fps) )) { (*pres)[elem]=*(pres_unprc+( j*(r_max_index+1-r_min_index)+k )); (*velx)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index))+(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index)); (*vely)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index))-(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index)); (*dens)[elem]=*(dens_unprc+( j*(r_max_index+1-r_min_index)+k )); (*x)[elem]=(*(r_unprc+r_index))*sin(*(theta_unprc+theta_index)); (*y)[elem]=(*(r_unprc+r_index))*cos(*(theta_unprc+theta_index)); (*r)[elem]=*(r_unprc+r_index); (*szx)[elem]=(*(r_unprc+r_index))*((M_PI/2)/2000); (*szy)[elem]=(M_PI/2)/2000; (*theta)[elem]=*(theta_unprc+theta_index);//theta in radians in relation to jet axis (*gamma)[elem]=pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1); //v is in units of c (*dens_lab)[elem]= (*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ))) * pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1); (*temp)[elem]=pow(3*(*(pres_unprc+( j*(r_max_index+1-r_min_index)+k )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0); elem++; } } } } (*number)=elem; //fprintf(fPtr, "Number of post restricted Elems: %d %e\n", elem, r_inj); //fflush(fPtr); free(pres_unprc); //works when not being freed? //fprintf(fPtr, "pres Done\n\n"); //fflush(fPtr); free(vel_r_unprc); //fprintf(fPtr, "vel_r Done\n\n"); //fflush(fPtr); free(vel_theta_unprc); //fprintf(fPtr, "vel_theta Done\n\n"); //fflush(fPtr); free(dens_unprc); //fprintf(fPtr, "dens Done\n\n"); //fflush(fPtr); free(r_unprc); //fprintf(fPtr, "r Done\n\n"); //fflush(fPtr); free(theta_unprc); //fprintf(fPtr, "theta Done\n\n"); //fflush(fPtr); pres_unprc=NULL; vel_r_unprc=NULL; vel_theta_unprc=NULL; dens_unprc=NULL; r_unprc=NULL; theta_unprc=NULL; //fprintf(fPtr, "ALL Done\n\n"); //fflush(fPtr); }
operator_tune-inl.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. */ #ifndef MXNET_OPERATOR_OPERATOR_TUNE_INL_H_ #define MXNET_OPERATOR_OPERATOR_TUNE_INL_H_ #include <dmlc/base.h> #include <dmlc/logging.h> #include <mshadow/base.h> #include <atomic> #include <cstdint> #include <chrono> #include <thread> #include <string> #include <vector> #include <algorithm> #include <list> #include <random> #include <unordered_set> #include "./mxnet_op.h" #include "./operator_tune.h" #if (__GNUC__ >= 4 || (__GNUC__ >= 3 && __GNUC_MINOR__ >= 4)) && !defined(__mips__) # define HAS_CXA_DEMANGLE 1 #else # define HAS_CXA_DEMANGLE 0 #endif #if HAS_CXA_DEMANGLE #include <cxxabi.h> #endif namespace mxnet { namespace op { #ifndef MXNET_NO_INLINE #ifdef _MSC_VER #define MXNET_NO_INLINE __declspec(noinline) #else #define MXNET_NO_INLINE __attribute__((noinline)) #endif #endif // MXNET_NO_INLINE #define OUTSIDE_COUNT_SHIFT 9 namespace tune { /*! * \brief Convert TuningMode value to a string representation * \param tm Scalar TuningMode value * \return Character pointer to a string representing the TuningMode value */ inline const char *TuningModeToString(const TuningMode tm) { switch (tm) { case kAuto: return "Auto"; case kNeverOMP: return "NeverOMP"; case kAlwaysOMP: return "AlwaysOMP"; default: CHECK(false) << "Unknown TuningMode type: " << static_cast<int>(tm); return "<unknown>"; } } } // namespace tune /*! * \brief Engine to tune kernel operations * \tparam DType Data type to be used when tuning the kernel operations * \remarks The basic concept here is that we time how long a trivial loop takes with and without * OMP, subtracting the non-OMP run from the OMP run, which gives us the time * that the OMP overhead takes. Times were found to be relatively invariant with * regard ot the number of threads/cores on a given machine. * Secondly, supplied operators are run and timed (for each data type) in order to determine * their individual time cost. * * Knowing the following items, we can determine how long the OMP and non-OMP run * is expected to take: * 1) OMP overhead time * 2) Number of iterations required * 3) Number of threads to be used if we choose the OMP method * 4) The data type * * Therefore, at Kernel::Launch() time, we can estimate whether it is faster to use OMP or not * for the given kernel operator. * * Results and efficiency of the tuning is tested in the gtest OMP_TUNING test suite */ template<typename DType> class OperatorTune : public OperatorTuneByType<DType> { public: using Tick = OperatorTuneBase::Tick; using duration_t = OperatorTuneBase::duration_t; using OperatorTuneByType<DType>::tuning_mode_; /*! * \brief Constructor */ OperatorTune() { TuneAll(); } /*! * \brief Initialize the OperatorTune object * \return Whether the OperatorTune object was successfully initialized */ static bool Initialize() { if (!initialized_) { initialized_ = true; // Generate some random data for calling the operator kernels data_set_.reserve(0x100); std::random_device rd; std::mt19937 gen(rd()); if (!std::is_integral<DType>::value) { std::uniform_real_distribution<> dis(-1, 1); for (int n = 0; n < 0x100; ++n) { const auto val = static_cast<DType>(dis(gen)); // If too close to zero, try again if (std::fabs(static_cast<double>(val)) < 1e-5) { --n; continue; } data_set_.emplace_back(val); } } else { std::uniform_int_distribution<> dis(-128, 127); for (int n = 0; n < 0x100; ++n) { const auto val = static_cast<DType>(dis(gen)); // If zero, try again if (!val) { --n; continue; } data_set_.emplace_back(val); } } // Use this environment variable to generate new tuning statistics // In order to avoid printing too many copies, only the float32 object prints output_tuning_data_ = mshadow::DataType<DType>::kFlag == mshadow::kFloat32 && dmlc::GetEnv("MXNET_OUTPUT_TUNING_DATA", false); // If outputting tuning data, then also output verbose logging info OperatorTuneBase::verbose_tuning_info_ = dmlc::GetEnv("MXNET_VERBOSE_TUNING_INFO", false); OperatorTuneBase::tuning_weight_scale_ = dmlc::GetEnv("MXNET_TUNING_WEIGHT_SCALE", 0.0); // This isn't actually supposed to be multithreaded init, but just to be sure the change is // seen everywhere, using atomic bool. if (!OperatorTuneBase::calculated_.load()) { // Not especially concerned with a race condition, since this hsould // run when only one thread is active (static init), just don't cache this variable OperatorTuneBase::calculated_.store(true); OperatorTuneBase::omp_overhead_ns_ = GetOMPLoopOverhead(); std::string config = dmlc::GetEnv("MXNET_USE_OPERATOR_TUNING", std::string()); ParseEnablerConfig(config); } if (OperatorTuneBase::verbose_tuning_info_) { LOG(INFO) << "OMP overhead: " << OperatorTuneBase::omp_overhead_ns_ << " nanoseconds"; } } return true; } /*! * \brief Schedule a tuning run * \tparam OP Operator to tune * \param tune_func Function to call which tunes the operator * \return true if the tune operation was scheduled */ template<typename OP> static bool ScheduleTune(void (*tune_func)()) { #ifdef MXNET_USE_OPERATOR_TUNING if (tune_func) { GetTuningList()->push_back(tune_func); operator_names_.insert(demangle(typeid(OP).name())); return true; } return false; #else return true; #endif } /*! * \brief Is the template parameter type a tuned kernel? * \tparam OP kernel operator type * \return true if the operator/kernel is tuned */ template<typename OP> static bool IsTuned() { return operator_names_.find(demangle(typeid(OP).name())) != operator_names_.end(); } /*!\ * \brief Tune all registered kernel operators that haven't already been tuned */ static bool TuneAll() { Initialize(); std::list<void (*)()> *tl = GetTuningList(); const size_t size_save = tl->size(); // For checking if anything asynchronous is // adding or removing items, which is forbidden if (output_tuning_data_ && !tl->empty()) { // Only emit this once, use the most common case, 'float32' if (mshadow::DataType<DType>::kFlag == mshadow::kFloat32) { std::cout << "OperatorTuneBase::duration_t " << "OperatorTuneBase::omp_overhead_ns_ = " << OperatorTuneBase::omp_overhead_ns_ << ";" << std::endl << std::flush; } } const Tick start = std::chrono::high_resolution_clock::now(); for (auto i : *tl) { (*i)(); } if (OperatorTuneBase::verbose_tuning_info_) { const duration_t duration = OperatorTune::GetDurationInNanoseconds(start); LOG(INFO) << "Op Tuning for " << type_name<DType>() << " took " << (duration / 1000000) << " ms"; } CHECK_EQ(size_save, tl->size()) << "Tuning list size should not have changed while tuning"; tl->clear(); return true; } /*! * \brief Return set of operator names that were registered to be tuned. Does not imply * that the operator has been tuned. * \return Set of operator/kernel names that were registered for tuning */ static const std::unordered_set<std::string>& TunedOperatorNames() { return operator_names_; } protected: /*! * \brief Get the list of tuning function calls for the operators * \return Pointer to list of tuning function calls */ static std::list<void (*)()> *GetTuningList(); /*! * \brief Demangle typeid::name() in order to generate source macros * \param name C++ Mangled name * \return Demangled name as string */ static inline std::string demangle(const char *name) { #if HAS_CXA_DEMANGLE int status = -4; // some arbitrary value to eliminate the compiler warning std::unique_ptr<char, void (*)(void *)> res{ abi::__cxa_demangle(name, nullptr, nullptr, &status), &std::free }; return status ? name : res.get(); #else return name; #endif } /*! * \brief Type name as string * \tparam T Type * \return std::string representing the human-readable demangled type name */ template<typename T> static inline std::string type_name() { return demangle(typeid(T).name()); } /*! \brief Measure OMP overhead for a trivial OMP loop using all cores * \param omp_thread_count - Number of OMP threads to use in the timing test * \returns Duration in nanoseconds for the OMP overhead (time to initiate and close the * OMP session) */ static duration_t GetOMPLoopOverhead(const size_t omp_thread_count) { CHECK_GT(omp_thread_count, 1); // Don't try to use OMP for one thread int wl_count = OperatorTuneBase::WORKLOAD_COUNT; Tick start = std::chrono::high_resolution_clock::now(); // Use two loops in order to simulate OMP outside timing for (size_t i = 0; i < OUTSIDE_COUNT; ++i) { for (int x = 0; x < wl_count; ++x) { // trivial operation volatile_int_ += x; } } const OperatorTuneBase::duration_t no_omp_duration = OperatorTuneBase::GetDurationInNanoseconds(start); // Scale OMP iterations by type calculation complexity double factor; // if tuning_weight_scale_ is a number that looks valid, use it as the factor if (OperatorTuneBase::tuning_weight_scale_ > 0.01) { factor = OperatorTuneBase::tuning_weight_scale_; } else { // These are empirically-determined constants found by balancing between // a desktop (8 & 12 cpu's) and large cloud instances (32 & 64 cpu's) switch (mshadow::DataType<DType>::kFlag) { case mshadow::kUint8: case mshadow::kInt8: factor = 8.5; break; case mshadow::kInt32: factor = 4.5; break; case mshadow::kInt64: factor = 2; break; case mshadow::kFloat64: factor = 1.25; break; case mshadow::kFloat32: default: factor = 1.0; break; } } wl_count = static_cast<int>(factor * OperatorTuneBase::WORKLOAD_COUNT * omp_thread_count); start = std::chrono::high_resolution_clock::now(); for (size_t i = 0; i < OUTSIDE_COUNT; ++i) { #pragma omp parallel for num_threads(omp_thread_count) for (int x = 0; x < wl_count; ++x) { // trivial operation volatile_int_ += x; } } const duration_t omp_duration = OperatorTuneBase::GetDurationInNanoseconds(start) - no_omp_duration; return omp_duration >> OUTSIDE_COUNT_SHIFT; } /*! \brief Measure OMP overhead for a trivial OMP loop using all cores * \returns Time in nanoseconds to initialize/cleanup when excuting an OMP block */ static duration_t GetOMPLoopOverhead() { // It was found empirically that OMP times was not heavily tied to number of cores, // so take an average across all core counts const auto max_cores = static_cast<size_t>(omp_get_num_procs()) >> 1; if (max_cores >= 2) { std::vector<duration_t> core_times; // Take care of any OMP lazy-init with a throwaway call for (size_t omp_threads = 2; omp_threads <= max_cores; ++omp_threads) { GetOMPLoopOverhead(omp_threads); } std::vector<duration_t> durations; durations.reserve(max_cores - 1); for (size_t omp_threads = 2; omp_threads <= max_cores; ++omp_threads) { const duration_t duration = GetOMPLoopOverhead(omp_threads); if (OperatorTuneBase::verbose_tuning_info_) { LOG(INFO) << "OMP Thread Count: " << omp_threads << ", overhead: " << duration << " ns"; } durations.emplace_back(duration); } // return median std::sort(durations.begin(), durations.end()); return durations[durations.size() >> 1]; } return INT_MAX; // If only one core, then never use OMP (say the overhead is huge) } /*! * \brief Some string utility functions that aren't specific to tuning */ struct StringUtil { /*! * \brief Terim whitespace from beninning and end of string * \param s String to trimp * \return reference to the modified string. This is the same std::string object as what was * supplied in the parameters */ static std::string &trim(std::string *s) { s->erase(s->begin(), std::find_if(s->begin(), s->end(), [](int ch) { return !std::isspace(ch); })); s->erase(std::find_if(s->rbegin(), s->rend(), [](int ch) { return !std::isspace(ch); }).base(), s->end()); return *s; } /*! * \brief Tokenize a string into a list of tokens * \param s String to tokenize * \return std::list of tokens */ static std::list<std::string> string2list(const std::string &s) { std::list<std::string> res; std::istringstream iss(s); std::string token; while (std::getline(iss, token, ',')) { trim(&token); if (!token.empty()) { res.push_back(token); } } return res; } }; /*! * \brief Get data type from string representation * \warning Do not call from a performance-sensitive area */ static int type_from_string(const std::string& type_string) { if (type_string == "float32") return mshadow::kFloat32; if (type_string == "float64") return mshadow::kFloat64; if (type_string == "float16") return mshadow::kFloat16; if (type_string == "int8") return mshadow::kInt8; if (type_string == "uint8") return mshadow::kUint8; if (type_string == "int32") return mshadow::kInt32; if (type_string == "int64") return mshadow::kInt64; return -1; // invalid } /*! * \brief Parse MXNET_ENABLE_OPERATOR_TUNING environment variable * \param config String representation of MXNET_ENABLE_OPERATOR_TUNING environment variable * Values: * 0=disable all * 1=enable all * float32, float16, float32=list of types to enable, and disable those not listed */ static void ParseEnablerConfig(std::string config) { StringUtil::trim(&config); if (!config.empty()) { // First disable all OperatorTuneByType<float>::set_tuning_mode(tune::kAlwaysOMP); OperatorTuneByType<double>::set_tuning_mode(tune::kAlwaysOMP); OperatorTuneByType<int8_t>::set_tuning_mode(tune::kAlwaysOMP); OperatorTuneByType<uint8_t>::set_tuning_mode(tune::kAlwaysOMP); OperatorTuneByType<int32_t>::set_tuning_mode(tune::kAlwaysOMP); OperatorTuneByType<int64_t>::set_tuning_mode(tune::kAlwaysOMP); // See if it's a non-number (ie type or list of types) if (!::isdigit(config[0])) { OperatorTuneByType<mshadow::half::half_t>::set_tuning_mode(tune::kAuto); std::list<std::string> tokens = StringUtil::string2list(config); for (const std::string& stype : tokens) { // We don't have an enum for halt_t const int typ = type_from_string(stype); if (typ >= 0) { switch (typ) { case mshadow::kFloat32: OperatorTuneByType<float>::set_tuning_mode(tune::kAuto); break; case mshadow::kFloat64: OperatorTuneByType<double>::set_tuning_mode(tune::kAuto); break; case mshadow::kFloat16: OperatorTuneByType<mshadow::half::half_t>::set_tuning_mode(tune::kAuto); break; case mshadow::kInt8: OperatorTuneByType<int8_t>::set_tuning_mode(tune::kAuto); break; case mshadow::kUint8: OperatorTuneByType<uint8_t>::set_tuning_mode(tune::kAuto); break; case mshadow::kInt32: OperatorTuneByType<int32_t>::set_tuning_mode(tune::kAuto); break; case mshadow::kInt64: OperatorTuneByType<int64_t>::set_tuning_mode(tune::kAuto); break; default: CHECK(false) << "Unsupported tuning data type: " << stype; break; } } else { // -1 is error LOG(WARNING) << "Unknown data type to be tuned: " << stype; } } } else { if (std::atoi(config.c_str()) > 0) { OperatorTuneByType<float>::set_tuning_mode(tune::kAuto); OperatorTuneByType<double>::set_tuning_mode(tune::kAuto); OperatorTuneByType<int8_t>::set_tuning_mode(tune::kAuto); OperatorTuneByType<uint8_t>::set_tuning_mode(tune::kAuto); OperatorTuneByType<int32_t>::set_tuning_mode(tune::kAuto); OperatorTuneByType<int64_t>::set_tuning_mode(tune::kAuto); OperatorTuneByType<mshadow::half::half_t>::set_tuning_mode(tune::kAuto); } } } } /*! \brief Whether this object has been initialized */ static bool initialized_; /*! \brief Number of passes to obtain an average */ static constexpr duration_t OUTSIDE_COUNT = (1 << OUTSIDE_COUNT_SHIFT); /*! \brief Random data for timing operator calls */ static std::vector<DType> data_set_; /*! \brief Operators tuned */ static std::unordered_set<std::string> operator_names_; /*! \brief Arbitary object to modify in OMP loop */ static volatile int volatile_int_; /*! \brief Output insertable (into code) instantiation+default-value macros */ static bool output_tuning_data_; }; /*! * \brief Class that tunes unary operators * \tparam DType Data type to be used when tuning the kernel operations */ template<typename DType> class UnaryOpTune : public OperatorTune<DType> { protected: typedef OperatorTune<DType> Super; using duration_t = typename Super::duration_t; using Tick = typename Super::Tick; /*! * \brief Determine the time it takes a kernel operator to execute WORKLOAD_COUNT iterations * Used for kernels that take no arguments (ie set_zero) * \tparam OP Kernel operator * \return Duration in nanoseconds for the 'WORKLOAD_COUNT' operations */ template<typename OP> static duration_t GetBlankWorkload() { DType tmp; volatile DType *res = &tmp; const Tick start = std::chrono::high_resolution_clock::now(); for (size_t i = 0; i < Super::WORKLOAD_COUNT; ++i) { // Use a logical AND instead of mod to avoid affecting the timing result with a slow divide *res += OP::Map(); } const duration_t omp_duration = Super::GetDurationInNanoseconds(start); return omp_duration ? omp_duration : 1; } /*! * \brief Determine the time it takes a kernel operator to execute WORKLOAD_COUNT iterations * Used for kernels that take one argument (ie sqrt()) * \tparam OP Kernel operator * \return Duration in nanoseconds for the 'WORKLOAD_COUNT' operations */ template<typename OP> static duration_t GetUnaryWorkload() { DType tmp; volatile DType *res = &tmp; const Tick start = std::chrono::high_resolution_clock::now(); for (size_t i = 0; i < Super::WORKLOAD_COUNT; ++i) { // Use a logical AND instead of mod to avoid affecting the timing result with a slow divide *res = OP::Map(Super::data_set_[i & 0xFF]); } const duration_t omp_duration = Super::GetDurationInNanoseconds(start); return omp_duration ? omp_duration : 1; } /*! * \brief Determine the time it takes a kernel operator to execute WORKLOAD_COUNT iterations * Used for kernels that take two arguments (ie elemwise_add()) * \tparam OP Kernel operator * \return Duration in nanoseconds for the 'WORKLOAD_COUNT' operations */ template<typename OP> static inline duration_t GetBinaryWorkload() { DType tmp; volatile DType *res = &tmp; const Tick start = std::chrono::high_resolution_clock::now(); for (size_t i = 0; i < Super::WORKLOAD_COUNT; ++i) { // Use a logical AND instead of mod to avoid affecting the timing result with a slow divide *res = OP::Map(Super::data_set_[i & 0xFF], Super::data_set_[(i + 1) & 0xFF]); } const duration_t omp_duration = Super::GetDurationInNanoseconds(start); return omp_duration ? omp_duration : 1; } /*! * \brief Determine the time it takes a kernel operator to execute WORKLOAD_COUNT iterations * Used for kernels that take three arguments (ie backwards_grad<elemwise_add>()) * \tparam OP Kernel operator * \return Duration in nanoseconds for the 'WORKLOAD_COUNT' operations */ template<typename OP> static duration_t GetTertiaryWorkload() { DType tmp; volatile DType *res = &tmp; const Tick start = std::chrono::high_resolution_clock::now(); for (size_t i = 0; i < Super::WORKLOAD_COUNT; ++i) { // Use a logical AND instead of mod to avoid affecting the timing result with a slow divide *res = OP::Map(Super::data_set_[i & 0xFF], Super::data_set_[(i + 1) & 0xFF], Super::data_set_[i & 0xFF]); } const duration_t omp_duration = Super::GetDurationInNanoseconds(start); return omp_duration ? omp_duration : 1; } /*! * \brief Determine the time it takes a kernel operator to execute WORKLOAD_COUNT iterations * Used for mxnet-like kernels that take no arguments) * \tparam OP Kernel operator * \return Duration in nanoseconds for the 'WORKLOAD_COUNT' operations */ template<typename OP> static duration_t GetBlankWorkloadEx() { std::unique_ptr<DType> tmp(new DType[Super::WORKLOAD_COUNT]); DType *tmp_ptr = tmp.get(); const Tick start = std::chrono::high_resolution_clock::now(); for (size_t i = 0; i < Super::WORKLOAD_COUNT; ++i) { OP::Map(i, tmp_ptr); } const duration_t omp_duration = Super::GetDurationInNanoseconds(start); return omp_duration ? omp_duration : 1; } public: /*! * \brief Tune the specified kernel operator. Optionally print out C++ macro that defines the * tuning data variable and the default tuned value * This function tunes an operator which takes no arguments * \tparam OP The kernel operator to be tuned */ template<typename OP> static void TuneBlankOperator() { mxnet::op::mxnet_op::tuned_op<OP, DType>::workload_[0] = GetBlankWorkload<OP>(); if (Super::output_tuning_data_) { std::cout << "IMPLEMENT_UNARY_WORKLOAD_FWD(" << Super::template type_name<OP>() << "); // NOLINT()" << std::endl << std::flush; // For long lines } } /*! * \brief Tune the specified kernel operator. Optionally print out C++ macro that defines the * tuning data variable and the default tuned value * This function tunes an operator which takes one argument * \tparam OP The kernel operator to be tuned */ template<typename OP> static void TuneUnaryOperator() { mxnet::op::mxnet_op::tuned_op<OP, DType>::workload_[0] = GetUnaryWorkload<OP>(); if (Super::output_tuning_data_) { std::cout << "IMPLEMENT_UNARY_WORKLOAD_FWD(" << Super::template type_name<OP>() << "); // NOLINT()" << std::endl << std::flush; // For long lines } } /*! * \brief Tune the specified kernel operator. Optionally print out C++ macro that defines the * tuning data variable and the default tuned value * This function tunes a backward operator which takes one argument * \tparam OP The kernel operator to be tuned */ template<typename OP> static void TuneUnaryBackwardOperator() { mxnet::op::mxnet_op::tuned_op<mxnet_op::backward_grad_tuned<OP>, DType>::workload_[0] = GetBinaryWorkload<mxnet::op::mxnet_op::backward_grad_tuned<OP>>(); if (Super::output_tuning_data_) { std::cout << "IMPLEMENT_UNARY_WORKLOAD_BWD(" << Super::template type_name<OP>() << "); // NOLINT()" << std::endl << std::flush; // For long lines } } /*! * \brief Tune the specified "mxnet_op-type" kernel operator. * Optionally print out C++ macro that defines the * tuning data variable and the default tuned value * This function tunes an operator which takes no arguments * \tparam OP The kernel operator to be tuned */ template<typename OP> static void TuneBlankOperatorEx() { mxnet::op::mxnet_op::tuned_op<OP, DType>::workload_[0] = GetBlankWorkloadEx<OP>(); if (Super::output_tuning_data_) { std::cout << "IMPLEMENT_BLANK_WORKLOAD_FWD(" << Super::template type_name<OP>() << "); // NOLINT()" << std::endl << std::flush; // For long lines } } /*! * \brief Determine whether to use OMP based upon both timing and configuration using the * given (templated) operator's workload * \tparam OP Operator whose workload to use (tuned_op::workload_[0]) * \param N Number of iterations desired * \param thread_count Number of OMP threads available to perform the iterations * \returns Whether it's faster to use OMP for these iterations */ template<typename OP> inline static bool UseOMP(size_t N, size_t thread_count) { return OperatorTune<DType>::UseOMP(N, thread_count, static_cast<uint64_t>(N) * OP::workload_[0]); } }; /*! * \brief Class that tunes binary and unary operators * \tparam DType Data type to be used when tuning the kernel operations */ template<typename DType> class BinaryOpTune : public UnaryOpTune<DType> { protected: typedef UnaryOpTune<DType> Super; public: /*! * \brief Tune a generic binary operator * @tparam OP - Operator type */ template<typename OP> static void TuneBinaryOperator() { mxnet_op::tuned_op<OP, DType>::workload_[0] = Super::template GetBinaryWorkload<OP>(); if (Super::Super::output_tuning_data_) { std::cout << "IMPLEMENT_BINARY_WORKLOAD_FWD(" << Super::template type_name<OP>() << "); // NOLINT()" << std::endl << std::flush; // For long lines } } /*! * \brief Tune binary backward operator * \tparam OP - operator */ template<typename OP> static void TuneBinaryBackwardOperator() { mxnet::op::mxnet_op::tuned_op<mxnet_op::backward_grad_tuned<OP>, DType>::workload_[0] = Super::template GetTertiaryWorkload<mxnet::op::mxnet_op::backward_grad_tuned<OP>>(); if (Super::Super::output_tuning_data_) { std::cout << "IMPLEMENT_BINARY_WORKLOAD_BWD(" << Super::template type_name<OP>() << "); // NOLINT()" << std::endl << std::flush; // For long lines } } }; #undef OUTSIDE_COUNT_SHIFT #undef WORKLOAD_COUNT_SHIFT } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_OPERATOR_TUNE_INL_H_
sum_double_avx2.c
//sum.c #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/timeb.h> #include <malloc.h> #define N_RUNS 1000 #define N 120000 // read timer in second double read_timer() { struct timeb tm; ftime(&tm); return (double) tm.time + (double) tm.millitm / 1000.0; } //Create a matrix and a vector and fill with random numbers void init(double *X) { for (int i = 0; i<N; i++) { X[i] = (double)rand()/(double)(RAND_MAX/10.0); } } //Our sum function- what it does is pretty straight-forward. double sum(double *X) { double result = 0; #pragma omp simd reduction(+:result) simdlen(8) for (int i = 0; i<N; i++) { result += X[i]; } return result; } // Debug functions double sum_serial(double *X) { double result = 0; for (int i = 0; i<N; i++) { result += X[i]; } return result; } void print_vector(double *vector) { printf("["); for (int i = 0; i<8; i++) { printf("%.2f ", vector[i]); } puts("]"); } int main(int argc, char **argv) { //Set everything up double *X = malloc(sizeof(double)*N); double result, result_serial; srand(time(NULL)); init(X); double start = read_timer(); for (int i = 0; i<N_RUNS; i++) result = sum(X); double t = (read_timer() - start); double start_serial = read_timer(); for (int i = 0; i<N_RUNS; i++) result_serial = sum_serial(X); double t_serial = (read_timer() - start_serial); print_vector(X); puts("=\n"); printf("SIMD: %f\n", result); puts("---------------------------------"); printf("Serial: %f\n", result_serial); double gflops = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t); double gflops_serial = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t_serial); printf("==================================================================\n"); printf("Performance:\t\t\tRuntime (s)\t GFLOPS\n"); printf("------------------------------------------------------------------\n"); printf("Sum (SIMD):\t\t%4f\t%4f\n", t, gflops); printf("Sum (Serial):\t\t%4f\t%4f\n", t_serial, gflops_serial); printf("Correctness check: %f\n", result_serial - result); free(X); return 0; }
mpi_vector.h
#pragma once #include <cassert> #include <thrust/host_vector.h> #include <thrust/gather.h> #include "exceptions.h" #include "exblas/mpi_accumulate.h" #include "tensor_traits.h" #include "blas1_dispatch_shared.h" #include "mpi_communicator.h" #include "memory.h" #include "config.h" //TODO: should we catch the cases where outer_size \in {1,2,3} in NearestNeighborComm? namespace dg { /** * @brief mpi Vector class * * @ingroup mpi_structures * * This class is a simple wrapper around a container object and an MPI_Comm. * The blas1 and blas2 functionality is available iff it is available for the container type. * We use mpi to communicate (e.g. boundary points in matrix-vector multiplications) * and use the existing blas functions for the local computations. * (At the blas level 1 communication is needed only for scalar products) * @tparam container local container type. Must have a \c size() and a \c swap() member function and a specialization of the \c TensorTraits class. */ template<class container> struct MPI_Vector { typedef container container_type;//!< typedef to acces underlying container ///no data is allocated, communicators are \c MPI_COMM_NULL MPI_Vector(){ m_comm = m_comm128 = m_comm128Reduce = MPI_COMM_NULL; } /** * @brief construct a vector * * calls \c dg::exblas::mpi_reduce_communicator() (collective call) * @param data internal data copy * @param comm MPI communicator (may not be \c MPI_COMM_NULL) */ MPI_Vector( const container& data, MPI_Comm comm): m_data( data), m_comm(comm) { exblas::mpi_reduce_communicator( comm, &m_comm128, &m_comm128Reduce); } /** * @brief Conversion operator * * uses conversion between compatible containers * @tparam OtherContainer another container class (container must be copy constructible from OtherContainer) * @param src the source */ template<class OtherContainer> MPI_Vector( const MPI_Vector<OtherContainer>& src){ m_data = src.data(); m_comm = src.communicator(); m_comm128 = src.communicator_mod(); m_comm128Reduce = src.communicator_mod_reduce(); } ///@brief Get underlying data ///@return read access to data const container& data() const {return m_data;} ///@brief Set underlying data ///@return write access to data container& data() {return m_data;} ///@brief Get the communicator to which this vector belongs ///@return read access to MPI communicator MPI_Comm communicator() const{return m_comm;} ///@brief Returns a communicator of fixed size 128 MPI_Comm communicator_mod() const{return m_comm128;} /** * @brief Returns a communicator consisting of all processes with rank 0 in \c communicator_mod() * * @return returns MPI_COMM_NULL to processes not part of that group */ MPI_Comm communicator_mod_reduce() const{return m_comm128Reduce;} /** * @brief Set the communicators with \c dg::exblas::mpi_reduce_communicator * * The reason why you can't just set the comm and need three parameters is * that generating communicators involves communication, which you might want to * avoid when you do it many times. So you have to call the function as * @code * MPI_Comm comm = MPI_COMM_WORLD, comm_mod, comm_mod_reduce; * dg::exblas::mpi_reduce_communicator( comm, &comm_mod, &comm_mod_reduce); * mpi_vector.set_communicator( comm, comm_mod, comm_mod_reduce); * @endcode */ void set_communicator(MPI_Comm comm, MPI_Comm comm_mod, MPI_Comm comm_mod_reduce){ m_comm = comm; m_comm128 = comm_mod; m_comm128Reduce = comm_mod_reduce; } ///@brief Return the size of the data object ///@return local size unsigned size() const{return m_data.size();} ///@brief Swap data and communicator ///@param src communicator and data is swapped void swap( MPI_Vector& src){ m_data.swap(src.m_data); std::swap( m_comm , src.m_comm); std::swap( m_comm128 , src.m_comm128); std::swap( m_comm128Reduce , src.m_comm128Reduce); } private: container m_data; MPI_Comm m_comm, m_comm128, m_comm128Reduce; }; ///@cond //free function as required by the std to be swappable //https://en.cppreference.com/w/cpp/named_req/Swappable //even though with move assignments std::swap also works as fast template<class container> void swap( MPI_Vector<container>& a, MPI_Vector<container>& b){ a.swap(b); } ///@endcond ///@addtogroup dispatch ///@{ ///@brief prototypical MPI vector template<class container> struct TensorTraits<MPI_Vector<container> > { using value_type = get_value_type<container>; using tensor_category = MPIVectorTag; using execution_policy = get_execution_policy<container>; }; ///@} /////////////////////////////communicator////////////////////////// /** * @brief Communicator for asynchronous nearest neighbor communication * * Imagine a communicator with Cartesian topology and further imagine that the * grid topology is also Cartesian (vectors form a box) in two or three dimensions. * In each direction this box has a boundary layer (the halo) of a depth given by * the user. Each boundary layer has two neighboring layers, one on the same process * and one lying on the neighboring process. * What this class does is to provide you with six pointers to each of these * six layers (three on each side). The pointers either reference data in an * internal communication buffer (since it involves communciation to get the * layers from neighboring processes) another buffer (if mpi communication * requires to reorder input data) or the input vector itself (if the * communication goes along the last dimension there is no need to reorder, * in fact, here is the main gain we get from the pointer approach, we save * on unnecessary data copies, which might be significant in cases where * the communication to computation ratio is high). * The size of the data each pointer references is the halo size, \c buffer_size() * * The communication is done asynchronously i.e. the user can initiate * the communication and signal when the results are needed at a later stage. * * @note If the number of neighboring processes in the given direction is 1, * the buffer size is 0 and all members return immediately. * @note the pointers may alias each other (if the input contains less than 4 layers) * * @note the corresponding gather map is of general type and the communication * can also be modeled in \c GeneralComm, but not \c BijectiveComm or \c SurjectiveComm * @attention Currently we cannot handle the case where the whole vector is * the boundary layer (i.e. \c buffer_size()==input.size() and both neighboring layers are on different processes) * @ingroup mpi_structures * @tparam Index the type of index container (must be either thrust::host_vector<int> or thrust::device_vector<int>) * @tparam Buffer the container for the pointers to the buffer arrays * @tparam Vector the vector container type must have a resize() function and work * in the thrust library functions ( i.e. must a thrust::host_vector or thrust::device_vector) * @sa dg::RowColDistMat */ template<class Index, class Buffer, class Vector> struct NearestNeighborComm { using container_type = Vector; using buffer_type = Buffer; using pointer_type = get_value_type<Vector>*; using const_pointer_type = get_value_type<Vector> const *; ///@brief no communication NearestNeighborComm(){ m_comm = MPI_COMM_NULL; m_silent = true; } /** * @brief Construct * * @param n depth of the halo * @param vector_dimensions {x, y, z} dimension (total number of points) * @param comm the (cartesian) communicator * @param direction 0 is x, 1 is y, 2 is z */ NearestNeighborComm( unsigned n, const unsigned vector_dimensions[3], MPI_Comm comm, unsigned direction) { static_assert( std::is_same<const_pointer_type, get_value_type<Buffer>>::value, "Must be same pointer types"); construct( n, vector_dimensions, comm, direction); } /** * @brief Construct from other Communicator * * Simply copies halo size, dimensions, communicator and direction and constructs a new object * @tparam OtherIndex other index type * @tparam OtherVector other container type * @param src source object */ template< class OtherIndex, class OtherBuffer, class OtherVector> NearestNeighborComm( const NearestNeighborComm<OtherIndex, OtherBuffer, OtherVector>& src){ if( src.buffer_size() == 0) m_silent=true; else construct( src.n(), src.dims(), src.communicator(), src.direction()); } /** * @brief halo size * @return halo size */ unsigned n() const{return m_n;} /** * @brief The dimensionality of the input vector * @return dimensions ( 3) */ const unsigned* dims() const{return m_dim;} /** * @brief The direction of communication * * @return direction */ unsigned direction() const {return m_direction;} ///@copydoc aCommunicator::communicator() MPI_Comm communicator() const{return m_comm;} /** * @brief Allocate a buffer object * * The buffer object is only a colletion of pointers to the actual data * @return a buffer object on the stack * @note if \c buffer_size()==0 the default constructor of \c Buffer is called */ Buffer allocate_buffer( )const{ if( buffer_size() == 0 ) return Buffer(); return Buffer(6); } /** @brief The size of the halo * @return the size of the halo (0 if no communication) */ unsigned buffer_size() const; ///@copydoc aCommunicator::isCommunicating() bool isCommunicating() const{ if( buffer_size() == 0) return false; return true; } /** * @brief Map a local matrix index to a buffer index * @param i matrix index * @return buffer index (0,1,...,5) */ int map_index(int i) const{ if( i==-1) return 0; if( i== 0) return 1; if( i==+1) return 2; if( i==(int)m_outer_size-0) return 5; if( i==(int)m_outer_size-1) return 4; if( i==(int)m_outer_size-2) return 3; throw Error( Message(_ping_)<<"Index not mappable!"); return -1; } /** * @brief Gather values from given Vector and initiate asynchronous MPI communication * @param input from which to gather data (it is @b unsafe to change values on return) * @param buffer (write only) pointers to the received data after \c global_gather_wait() was called (must be allocated by \c allocate_buffer()) * @param rqst four request variables that can be used to call MPI_Waitall */ void global_gather_init( const_pointer_type input, buffer_type& buffer, MPI_Request rqst[4])const { unsigned size = buffer_size(); //init pointers on host const_pointer_type host_ptr[6]; if(m_trivial) { host_ptr[0] = thrust::raw_pointer_cast(&m_internal_buffer.data()[0*size]); host_ptr[1] = input; host_ptr[2] = input+size; host_ptr[3] = input+(m_outer_size-2)*size; host_ptr[4] = input+(m_outer_size-1)*size; host_ptr[5] = thrust::raw_pointer_cast(&m_internal_buffer.data()[5*size]); } else { host_ptr[0] = thrust::raw_pointer_cast(&m_internal_buffer.data()[0*size]); host_ptr[1] = thrust::raw_pointer_cast(&m_internal_buffer.data()[1*size]); host_ptr[2] = thrust::raw_pointer_cast(&m_internal_buffer.data()[2*size]); host_ptr[3] = thrust::raw_pointer_cast(&m_internal_buffer.data()[3*size]); host_ptr[4] = thrust::raw_pointer_cast(&m_internal_buffer.data()[4*size]); host_ptr[5] = thrust::raw_pointer_cast(&m_internal_buffer.data()[5*size]); } //copy pointers to device thrust::copy( host_ptr, host_ptr+6, buffer.begin()); //fill internal_buffer if !trivial do_global_gather_init( get_execution_policy<Vector>(), input, rqst); sendrecv( host_ptr[1], host_ptr[4], thrust::raw_pointer_cast(&m_internal_buffer.data()[0*size]), //host_ptr is const! thrust::raw_pointer_cast(&m_internal_buffer.data()[5*size]), //host_ptr is const! rqst); } /** * @brief Wait for asynchronous communication to finish and gather received data into buffer * * Calls MPI_Waitall on the \c rqst variables and may do additional cleanup. After this call returns it is safe to use data the buffer points to. * @param input from which to gather data (it is safe to change values on return since values to communicate are copied into \c buffer) * @param buffer (write only) where received data resides on return (must be allocated by \c allocate_buffer()) * @param rqst the same four request variables that were used in global_gather_init */ void global_gather_wait(const_pointer_type input, const buffer_type& buffer, MPI_Request rqst[4])const { MPI_Waitall( 4, rqst, MPI_STATUSES_IGNORE ); #ifdef _DG_CUDA_UNAWARE_MPI if( std::is_same< get_execution_policy<Vector>, CudaTag>::value ) //could be serial tag { unsigned size = buffer_size(); cudaMemcpy( thrust::raw_pointer_cast(&m_internal_buffer.data()[0*size]), //dst thrust::raw_pointer_cast(&m_internal_host_buffer.data()[0*size]), //src size*sizeof(get_value_type<Vector>), cudaMemcpyHostToDevice); cudaMemcpy( thrust::raw_pointer_cast(&m_internal_buffer.data()[5*size]), //dst thrust::raw_pointer_cast(&m_internal_host_buffer.data()[5*size]), //src size*sizeof(get_value_type<Vector>), cudaMemcpyHostToDevice); } #endif } private: void do_global_gather_init( OmpTag, const_pointer_type, MPI_Request rqst[4])const; void do_global_gather_init( SerialTag, const_pointer_type, MPI_Request rqst[4])const; void do_global_gather_init( CudaTag, const_pointer_type, MPI_Request rqst[4])const; void construct( unsigned n, const unsigned vector_dimensions[3], MPI_Comm comm, unsigned direction); unsigned m_n, m_dim[3]; //deepness, dimensions MPI_Comm m_comm; unsigned m_direction; bool m_silent, m_trivial=false; //silent -> no comm, m_trivial-> comm in last dim unsigned m_outer_size = 1; //size of vector in units of buffer_size Index m_gather_map_middle; dg::Buffer<Vector> m_internal_buffer; #ifdef _DG_CUDA_UNAWARE_MPI //a copy of the data on the host (we need to send data manually through the host) dg::Buffer<thrust::host_vector<get_value_type<Vector>>> m_internal_host_buffer; #endif void sendrecv(const_pointer_type, const_pointer_type, pointer_type, pointer_type, MPI_Request rqst[4])const; int m_source[2], m_dest[2]; }; ///@cond template<class I, class B, class V> void NearestNeighborComm<I,B,V>::construct( unsigned n, const unsigned dimensions[3], MPI_Comm comm, unsigned direction) { static_assert( std::is_base_of<SharedVectorTag, get_tensor_category<V>>::value, "Only Shared vectors allowed"); m_silent=false; m_n=n; m_dim[0] = dimensions[0], m_dim[1] = dimensions[1], m_dim[2] = dimensions[2]; m_direction = direction; if( dimensions[2] == 1 && direction == 1) m_trivial = true; else if( direction == 2) m_trivial = true; else m_trivial = false; assert( direction <3); m_comm = comm; //mpi_cart_shift may return MPI_PROC_NULL then the receive buffer is not modified MPI_Cart_shift( m_comm, m_direction, -1, &m_source[0], &m_dest[0]); MPI_Cart_shift( m_comm, m_direction, +1, &m_source[1], &m_dest[1]); { int ndims; MPI_Cartdim_get( comm, &ndims); int dims[ndims], periods[ndims], coords[ndims]; MPI_Cart_get( comm, ndims, dims, periods, coords); if( dims[direction] == 1) m_silent = true; } if( !m_silent) { m_outer_size = dimensions[0]*dimensions[1]*dimensions[2]/buffer_size(); assert( m_outer_size > 1 && "Parallelization too fine grained!"); //right now we cannot have that thrust::host_vector<int> mid_gather( 4*buffer_size()); switch( direction) { case( 0): for( unsigned i=0; i<m_dim[2]*m_dim[1]; i++) for( unsigned j=0; j<n; j++) { mid_gather[(0*n+j)*m_dim[2]*m_dim[1]+i] = i*m_dim[0] + j; mid_gather[(1*n+j)*m_dim[2]*m_dim[1]+i] = i*m_dim[0] + n + j; mid_gather[(2*n+j)*m_dim[2]*m_dim[1]+i] = i*m_dim[0] + m_dim[0]-2*n + j; mid_gather[(3*n+j)*m_dim[2]*m_dim[1]+i] = i*m_dim[0] + m_dim[0]- n + j; } break; case( 1): for( unsigned i=0; i<m_dim[2]; i++) for( unsigned j=0; j<n; j++) for( unsigned k=0; k<m_dim[0]; k++) { mid_gather[((0*n+j)*m_dim[2]+i)*m_dim[0] + k] = (i*m_dim[1] + j)*m_dim[0] + k; mid_gather[((1*n+j)*m_dim[2]+i)*m_dim[0] + k] = (i*m_dim[1] + n + j)*m_dim[0] + k; mid_gather[((2*n+j)*m_dim[2]+i)*m_dim[0] + k] = (i*m_dim[1] + m_dim[1]-2*n + j)*m_dim[0] + k; mid_gather[((3*n+j)*m_dim[2]+i)*m_dim[0] + k] = (i*m_dim[1] + m_dim[1]- n + j)*m_dim[0] + k; } break; case( 2): for( unsigned i=0; i<n; i++) for( unsigned j=0; j<m_dim[0]*m_dim[1]; j++) { mid_gather[(0*n+i)*m_dim[0]*m_dim[1]+j] = (i )*m_dim[0]*m_dim[1] + j; mid_gather[(1*n+i)*m_dim[0]*m_dim[1]+j] = (i + n )*m_dim[0]*m_dim[1] + j; mid_gather[(2*n+i)*m_dim[0]*m_dim[1]+j] = (i + m_dim[2]-2*n )*m_dim[0]*m_dim[1] + j; mid_gather[(3*n+i)*m_dim[0]*m_dim[1]+j] = (i + m_dim[2]- n )*m_dim[0]*m_dim[1] + j; } break; } m_gather_map_middle = mid_gather; //transfer to device m_internal_buffer.data().resize( 6*buffer_size() ); #ifdef _DG_CUDA_UNAWARE_MPI m_internal_host_buffer.data().resize( 6*buffer_size() ); #endif } } template<class I, class B, class V> unsigned NearestNeighborComm<I,B,V>::buffer_size() const { if( m_silent) return 0; switch( m_direction) { case( 0): //x-direction return m_n*m_dim[1]*m_dim[2]; case( 1): //y-direction return m_n*m_dim[0]*m_dim[2]; case( 2): //z-direction return m_n*m_dim[0]*m_dim[1]; //no further m_n (hide in m_dim) default: return 0; } } template<class I, class B, class V> void NearestNeighborComm<I,B,V>::do_global_gather_init( SerialTag, const_pointer_type input, MPI_Request rqst[4]) const { if( !m_trivial) { unsigned size = buffer_size(); for( unsigned i=0; i<4*size; i++) m_internal_buffer.data()[i+size] = input[m_gather_map_middle[i]]; } } #ifdef _OPENMP template<class I, class B, class V> void NearestNeighborComm<I,B,V>::do_global_gather_init( OmpTag, const_pointer_type input, MPI_Request rqst[4]) const { if(!m_trivial) { unsigned size = buffer_size(); #pragma omp parallel for for( unsigned i=0; i<4*size; i++) m_internal_buffer.data()[size+i] = input[m_gather_map_middle[i]]; } } #endif #if THRUST_DEVICE_SYSTEM==THRUST_DEVICE_SYSTEM_CUDA template<class I, class B, class V> void NearestNeighborComm<I,B,V>::do_global_gather_init( CudaTag, const_pointer_type input, MPI_Request rqst[4]) const { //gather values from input into sendbuffer if(!m_trivial) { unsigned size = buffer_size(); thrust::gather( thrust::cuda::tag(), m_gather_map_middle.begin(), m_gather_map_middle.end(), input, m_internal_buffer.data().begin()+size); } cudaDeviceSynchronize(); //wait until device functions are finished before sending data } #endif template<class I, class B, class V> void NearestNeighborComm<I,B,V>::sendrecv( const_pointer_type sb1_ptr, const_pointer_type sb2_ptr, pointer_type rb1_ptr, pointer_type rb2_ptr, MPI_Request rqst[4]) const { unsigned size = buffer_size(); #ifdef _DG_CUDA_UNAWARE_MPI if( std::is_same< get_execution_policy<V>, CudaTag>::value ) //could be serial tag { cudaMemcpy( thrust::raw_pointer_cast(&m_internal_host_buffer.data()[1*size]),//dst sb1_ptr, size*sizeof(get_value_type<V>), cudaMemcpyDeviceToHost); //src cudaMemcpy( thrust::raw_pointer_cast(&m_internal_host_buffer.data()[4*size]), //dst sb2_ptr, size*sizeof(get_value_type<V>), cudaMemcpyDeviceToHost); //src sb1_ptr = thrust::raw_pointer_cast(&m_internal_host_buffer.data()[1*size]); sb2_ptr = thrust::raw_pointer_cast(&m_internal_host_buffer.data()[4*size]); rb1_ptr = thrust::raw_pointer_cast(&m_internal_host_buffer.data()[0*size]); rb2_ptr = thrust::raw_pointer_cast(&m_internal_host_buffer.data()[5*size]); } //This is a mistake if called with a host_vector #endif MPI_Isend( sb1_ptr, size, getMPIDataType<get_value_type<V>>(), //sender m_dest[0], 3, m_comm, &rqst[0]); //destination MPI_Irecv( rb2_ptr, size, getMPIDataType<get_value_type<V>>(), //receiver m_source[0], 3, m_comm, &rqst[1]); //source MPI_Isend( sb2_ptr, size, getMPIDataType<get_value_type<V>>(), //sender m_dest[1], 9, m_comm, &rqst[2]); //destination MPI_Irecv( rb1_ptr, size, getMPIDataType<get_value_type<V>>(), //receiver m_source[1], 9, m_comm, &rqst[3]); //source } ///@endcond }//namespace dg
ofmo-oneint-core.c
/** * @file ofmo-oneint-core.c * 1つのCSペアに対する1電子積分を計算する関数群 * */ /** * @defgroup core-oneint 1電子積分を行う関数群 * * 1つのCSペアに対する1電子積分を計算する関数群。 * 2011/06/16現在は、(s,s)から(d,d)までの積分を行える * ようになっている。 * この関数は粒度が小さいので、CとFortranで共通のAPIにするため、 * すべての引数が参照渡しになっている。 * * 各種積分を行う関数 \c oneint_core_xx_ はすべて同じ * 引数をとる。その引数の説明を記す。 * * @param[in] *ips0 1つ目のCSに属するPSの先頭PS番号 * @param[in] *nps_i 1つ目のCSの縮約長(PS数) * @param[in] A[3] 1つ目のCSの中心座標(au 単位) * @param[in] *ips0 2つ目のCSに属するPSの先頭PS番号 * @param[in] *nps_j 2つ目のCSの縮約長(PS数) * @param[in] B[3] 2つ目のCSの中心座標(au 単位) * @param[in] prim_exp[ips] PS番号 \c ips 番目のPSの軌道指数 * @param[in] prim_coe[ips] PS番号 \c ips 番目のPSの規格化定数込みの * 縮約係数 * @param[in] *nat 原子数 * @param[in] atom_x[iat] 原子の番号 \c iat の原子のx座標 * @param[in] atom_y[iat] 原子の番号 \c iat の原子のy座標 * @param[in] atom_z[iat] 原子の番号 \c iat の原子のz座標 * @param[in] atomic_number[iat] 原子の番号 \c iat の原子の原子番号 * * @param[out] OVI[] 計算した重なり積分を代入する配列 * @param[out] HCORE[] 計算した1電子ハミルトン行列要素 * (運動エネルギー積分+核-引力積分)を代入する配列 * * @ingroup integ-core * */ #include <stdio.h> #include <math.h> #include "fmt.h" #include "ofmo-def.h" #define ZERO 0.e0 #define HALF .5e0 #define EPS_PS_PAIR 1.e-32 static double EPS_PS_PAIR_NAI; static double _PI_32_; static double _2PI_; static double _inv2_; static double _inv3_; static double _spi2_; /** 1電子積分関数の初期化を行う関数 * * 1電子積分計算で必要な定数などの初期化を行う * @ingroup core-oneint * */ int ofmo_oneint_init( ) { double pi; static int called = false; if ( called ) return 0; pi = 4.e0 * atan( 1.e0 ); _PI_32_ = pi * sqrt(pi); _2PI_ = 2.e0 * pi; _inv2_ = 1.e0/2.e0; _inv3_ = 1.e0/3.e0; _spi2_ = sqrt( 0.5e0*pi ); EPS_PS_PAIR_NAI = EPS_PS_PAIR; called = true; return 0; } int ofmo_oneint_set_sum_atomic_numbers( const int sum_atomic_number ) { if ( sum_atomic_number < 1 ) { EPS_PS_PAIR_NAI = EPS_PS_PAIR; } else { EPS_PS_PAIR_NAI = EPS_PS_PAIR / (double)sum_atomic_number; } return 0; } extern double *FMT_fmt_table0; extern double *FMT_fmt_table1; extern double *FMT_fmt_table2; extern double *FMT_fmt_table3; extern double *FMT_fmt_table4; extern double FMT_fmt_step_size; extern double FMT_fmt_inv_step_size; extern double FMT_pi_div2; /** 1つのCS対のSSタイプの1電子積分を計算する * @ingroup core-oneint * */ void oneint_core_ss__( const int *ips0, const int *nps_i, const double A[3], const int *jps0, const int *nps_j, const double B[3], const double prim_exp[], const double prim_coe[], const int *nat, const double atom_x[], const double atom_y[], const double atom_z[], const int atomic_number[], double OVI[], double HCORE[] ) { int i, ips, jps, kat, ips1, jps1; double zeta_a, zeta_b, zeta, coef_a, coef_b, coef; double sqrzi, zi, xiza, xi, xiab2, exp_ab, css; double oviss, keiss, naiss; double sum, PC2, dq, U; double BA[3], P[3], AB2; double _pi32_ = _PI_32_, _2pi_ = _2PI_; OVI[0] = ZERO; HCORE[0] = ZERO; AB2 = ZERO; for ( i=0; i<3; i++ ) { BA[i] = B[i]-A[i]; AB2 += BA[i]*BA[i]; } ips1 = *ips0 + (*nps_i); jps1 = *jps0 + (*nps_j); /*// debug //#pragma omp master { printf("FMT_fmt_table0 = %p\n", FMT_fmt_table0 ); printf("ips1, jps1 = %d, %d\n", ips1, jps1 ); fflush(stdout); }*/ for ( ips=(*ips0); ips<ips1; ips++ ) { zeta_a = prim_exp[ips]; coef_a = prim_coe[ips]; for ( jps=(*jps0); jps<jps1; jps++ ) { zeta_b = prim_exp[jps]; coef_b = prim_coe[jps]; zeta = zeta_a + zeta_b; sqrzi = sqrt( 1.e0 / zeta ); zi = sqrzi * sqrzi; coef = coef_a * coef_b; xiza = zeta_b * zi; xi = xiza * zeta_a; xiab2 = xi * AB2; exp_ab = coef * exp( -xiab2 ); oviss = _pi32_ * zi * sqrzi * exp_ab; keiss = xi * ( 3.e0 - 2.e0 * xiab2 ) * oviss; OVI[0] += oviss; HCORE[0] += keiss; css = _2pi_ * zi * exp_ab; if ( fabs(css) < EPS_PS_PAIR_NAI ) continue; for ( i=0; i<3; i++ ) P[i] = xiza*BA[i] + A[i]; sum = ZERO; for ( kat=0; kat<(*nat); kat++ ) { dq = (double)atomic_number[kat]; PC2 = (P[0]-atom_x[kat])*(P[0]-atom_x[kat]); PC2 += (P[1]-atom_y[kat])*(P[1]-atom_y[kat]); PC2 += (P[2]-atom_z[kat])*(P[2]-atom_z[kat]); U = zeta * PC2; { int it0, pos; double dT; if ( U < 36e0 ) { it0 = (int)(0.5e0 + U * FMT_fmt_inv_step_size); dT = it0 * FMT_fmt_step_size - U; pos = it0 * 4; naiss = css * ((( FMT_fmt_table0[pos+3] * dT + FMT_fmt_table0[pos+2] ) * dT + FMT_fmt_table0[pos+1] ) * dT + FMT_fmt_table0[pos+0] ); } else { naiss = css * _spi2_ * sqrt( 1.e0/(U+U) ); } } //fmt( &naiss, 0, U, css ); sum += (dq*naiss); } HCORE[0] -= sum; } } } /** 1つのCS対のPSタイプの1電子積分を計算する * @ingroup core-oneint * */ void oneint_core_ps__( const int *ips0, const int *nps_i, const double A[3], const int *jps0, const int *nps_j, const double B[3], const double prim_exp[], const double prim_coe[], const int *nat, const double atom_x[], const double atom_y[], const double atom_z[], const int atomic_number[], double OVI[], double HCORE[] ) { int i, ips, jps, kat, ips1, jps1; double zeta_a, zeta_b, zeta, coef_a, coef_b, coef; double sqrzi, zi, xiza, xi, xiab2, xi2, exp_ab, css, cnass; double oviss, keiss; double PC2, dq, U; double BA[3], P[3], PA[3], PC[3], AB2; double keips[3], ovips[3], naips[3]; double naiss[1+1]; double _pi32_ = _PI_32_, _2pi_ = _2PI_; for ( i=0; i<3; i++ ) OVI[i] = HCORE[i] = ZERO; AB2 = ZERO; for ( i=0; i<3; i++ ) { BA[i] = B[i]-A[i]; AB2 += BA[i]*BA[i]; } ips1 = *ips0 + (*nps_i); jps1 = *jps0 + (*nps_j); for ( ips=(*ips0); ips<ips1; ips++ ) { zeta_a = prim_exp[ips]; coef_a = prim_coe[ips]; for ( jps=(*jps0); jps<jps1; jps++ ) { zeta_b = prim_exp[jps]; coef_b = prim_coe[jps]; zeta = zeta_a + zeta_b; sqrzi = sqrt( 1.e0 / zeta ); zi = sqrzi * sqrzi; coef = coef_a * coef_b; xiza = zeta_b * zi; xi = xiza * zeta_a; xiab2 = xi * AB2; xi2 = 2.e0 * xi; exp_ab = coef * exp( -xiab2 ); oviss = _pi32_ * zi * sqrzi * exp_ab; keiss = xi * ( 3.e0 - 2.e0 * xiab2 ) * oviss; css = _2pi_ * zi * exp_ab; if ( fabs(css) < EPS_PS_PAIR_NAI ) continue; for ( i=0; i<3; i++ ) { P[i] = xiza*BA[i] + A[i]; PA[i] = xiza*BA[i]; } // overlap integral for ( i=0; i<3; i++ ) ovips[i] = PA[i]*oviss; // kinetic energy integral for ( i=0; i<3; i++ ) keips[i] = PA[i]*keiss + xi2*ovips[i]; for ( i=0; i<3; i++ ) naips[i] = ZERO; for ( kat=0; kat<(*nat); kat++ ) { dq = (double)atomic_number[kat]; PC[0] = P[0]-atom_x[kat]; PC[1] = P[1]-atom_y[kat]; PC[2] = P[2]-atom_z[kat]; PC2 = PC[0]*PC[0] + PC[1]*PC[1] + PC[2]*PC[2]; cnass = dq * css; U = zeta * PC2; { int it0, pos; double dT, t_inv, st_inv, dT2, dT3; if ( U < 38e0 ) { it0 = (int)(0.5e0 + U * FMT_fmt_inv_step_size); dT = it0 * FMT_fmt_step_size - U; dT2 = dT * _inv2_; dT3 = dT * _inv3_; pos = it0 * (1+4); naiss[0] = cnass*(((FMT_fmt_table1[pos+3] * dT3 + FMT_fmt_table1[pos+2] ) * dT2 + FMT_fmt_table1[pos+1] ) * dT + FMT_fmt_table1[pos+0] ); naiss[1] = cnass*(((FMT_fmt_table1[pos+4] * dT3 + FMT_fmt_table1[pos+3] ) * dT2 + FMT_fmt_table1[pos+2] ) * dT + FMT_fmt_table1[pos+1] ); } else { st_inv = sqrt( 0.5e0 / U ); t_inv = st_inv * st_inv; naiss[0] = cnass * _spi2_ * st_inv; naiss[1] = t_inv * naiss[0]; } } //fmt( naiss, 1, U, cnass ); for ( i=0; i<3; i++ ) naips[i] += PA[i]*naiss[0]-PC[i]*naiss[1]; } // contraction for ( i=0; i<3; i++ ) { OVI[i] += ovips[i]; HCORE[i] += (keips[i] - naips[i]); } } } } /** 1つのCS対のPPタイプの1電子積分を計算する * @ingroup core-oneint * */ void oneint_core_pp__( const int *ips0, const int *nps_i, const double A[3], const int *jps0, const int *nps_j, const double B[3], const double prim_exp[], const double prim_coe[], const int *nat, const double atom_x[], const double atom_y[], const double atom_z[], const int atomic_number[], double OVI[], double HCORE[] ) { int i, m, ips, jps, kat, ips1, jps1; double zeta_a, zeta_b, zeta, coef_a, coef_b, coef; double sqrzi, zi, xiza, xi, xiab2, xi2, exp_ab, css, zeta2; double oviss, keiss, tmp; double BA[3], P[3], PA[3], PC[3], PB[3], AB2; double keips[3], keipp[3*3], ovips[3], ovipp[3*3]; double PC2, dq, U; double naiss[2+1], naips[2][3], naipp[3*3]; double _pi32_ = _PI_32_, _2pi_ = _2PI_; for ( i=0; i<3*3; i++ ) OVI[i] = HCORE[i] = ZERO; AB2 = ZERO; for ( i=0; i<3; i++ ) { BA[i] = B[i]-A[i]; AB2 += BA[i]*BA[i]; } ips1 = *ips0 + (*nps_i); jps1 = *jps0 + (*nps_j); for ( ips=(*ips0); ips<ips1; ips++ ) { zeta_a = prim_exp[ips]; coef_a = prim_coe[ips]; for ( jps=(*jps0); jps<jps1; jps++ ) { zeta_b = prim_exp[jps]; coef_b = prim_coe[jps]; zeta = zeta_a + zeta_b; sqrzi = sqrt( 1.e0 / zeta ); zi = sqrzi * sqrzi; coef = coef_a * coef_b; xiza = zeta_b * zi; xi = xiza * zeta_a; xiab2 = xi * AB2; xi2 = 2.e0 * xi; zeta2 = HALF * zi; exp_ab = coef * exp( -xiab2 ); oviss = _pi32_ * zi * sqrzi * exp_ab; keiss = xi * ( 3.e0 - 2.e0 * xiab2 ) * oviss; css = _2pi_ * zi * exp_ab; if ( fabs(css) < EPS_PS_PAIR_NAI ) continue; for ( i=0; i<3; i++ ) { P[i] = xiza*BA[i] + A[i]; PA[i] = xiza*BA[i]; PB[i] = xiza*BA[i] - BA[i]; } // overlap integral // (p|s) for ( i=0; i<3; i++ ) ovips[i] = PA[i]*oviss; // (p|p) ovipp[0*3+0] = PB[0]*ovips[0] + zeta2*oviss; ovipp[0*3+1] = PB[1]*ovips[0]; ovipp[0*3+2] = PB[2]*ovips[0]; ovipp[1*3+0] = PB[0]*ovips[1]; ovipp[1*3+1] = PB[1]*ovips[1] + zeta2*oviss; ovipp[1*3+2] = PB[2]*ovips[1]; ovipp[2*3+0] = PB[0]*ovips[2]; ovipp[2*3+1] = PB[1]*ovips[2]; ovipp[2*3+2] = PB[2]*ovips[2] + zeta2*oviss; // kinetic energy integral // (p|T|s) for ( i=0; i<3; i++ ) keips[i] = PA[i]*keiss + xi2*ovips[i]; // (p|T|p) keipp[0*3+0] = PB[0]*keips[0] + xi2*ovipp[0*3+0] + zeta2*keiss; keipp[0*3+1] = PB[1]*keips[0] + xi2*ovipp[0*3+1]; keipp[0*3+2] = PB[2]*keips[0] + xi2*ovipp[0*3+2]; keipp[1*3+0] = PB[0]*keips[1] + xi2*ovipp[1*3+0]; keipp[1*3+1] = PB[1]*keips[1] + xi2*ovipp[1*3+1] + zeta2*keiss; keipp[1*3+2] = PB[2]*keips[1] + xi2*ovipp[1*3+2]; keipp[2*3+0] = PB[0]*keips[2] + xi2*ovipp[2*3+0]; keipp[2*3+1] = PB[1]*keips[2] + xi2*ovipp[2*3+1]; keipp[2*3+2] = PB[2]*keips[2] + xi2*ovipp[2*3+2] + zeta2*keiss; for ( i=0; i<3*3; i++ ) naipp[i] = ZERO; for ( kat=0; kat<(*nat); kat++ ) { dq = (double)atomic_number[kat]; PC[0] = P[0]-atom_x[kat]; PC[1] = P[1]-atom_y[kat]; PC[2] = P[2]-atom_z[kat]; PC2 = PC[0]*PC[0] + PC[1]*PC[1] + PC[2]*PC[2]; U = zeta * PC2; { int it0, pos; double dT, t_inv, st_inv, dT2, dT3, cnass; cnass = dq*css; if ( U < 40e0 ) { it0 = (int)(0.5e0 + U * FMT_fmt_inv_step_size); dT = it0 * FMT_fmt_step_size - U; dT2 = dT * _inv2_; dT3 = dT * _inv3_; pos = it0 * (2+4); naiss[0] = cnass*(((FMT_fmt_table2[pos+3] * dT3 + FMT_fmt_table2[pos+2] ) * dT2 + FMT_fmt_table2[pos+1] ) * dT + FMT_fmt_table2[pos+0] ); naiss[1] = cnass*(((FMT_fmt_table2[pos+4] * dT3 + FMT_fmt_table2[pos+3] ) * dT2 + FMT_fmt_table2[pos+2] ) * dT + FMT_fmt_table2[pos+1] ); naiss[2] = cnass*(((FMT_fmt_table2[pos+5] * dT3 + FMT_fmt_table2[pos+4] ) * dT2 + FMT_fmt_table2[pos+3] ) * dT + FMT_fmt_table2[pos+2] ); } else { st_inv = sqrt( 0.5e0 / U ); t_inv = st_inv * st_inv; naiss[0] = cnass * _spi2_ * st_inv; naiss[1] = t_inv * naiss[0]; naiss[2] = 3.e0 * t_inv * naiss[1]; } } //fmt( naiss, 2, U, dq*css ); // -- (P|A(0)|S) -- for ( m=0; m<=1; m++) { naips[m][0] = PA[0]*naiss[m] - PC[0]*naiss[m+1]; naips[m][1] = PA[1]*naiss[m] - PC[1]*naiss[m+1]; naips[m][2] = PA[2]*naiss[m] - PC[2]*naiss[m+1]; } // -- (P|A|P) -- tmp = zeta2*( naiss[0] - naiss[1] ); naipp[0*3+0] += PB[0]*naips[0][0]-PC[0]*naips[1][0]+tmp; naipp[0*3+1] += PB[1]*naips[0][0]-PC[1]*naips[1][0]; naipp[0*3+2] += PB[2]*naips[0][0]-PC[2]*naips[1][0]; naipp[1*3+0] += PB[0]*naips[0][1]-PC[0]*naips[1][1]; naipp[1*3+1] += PB[1]*naips[0][1]-PC[1]*naips[1][1]+tmp; naipp[1*3+2] += PB[2]*naips[0][1]-PC[2]*naips[1][1]; naipp[2*3+0] += PB[0]*naips[0][2]-PC[0]*naips[1][2]; naipp[2*3+1] += PB[1]*naips[0][2]-PC[1]*naips[1][2]; naipp[2*3+2] += PB[2]*naips[0][2]-PC[2]*naips[1][2]+tmp; } // contraction for ( i=0; i<3*3; i++ ) { OVI[i] += ovipp[i]; HCORE[i] += (keipp[i] - naipp[i]); } } // jps } // ips } /** 1つのCS対のDSタイプの1電子積分を計算する * @ingroup core-oneint * */ void oneint_core_ds__( const int *ips0, const int *nps_i, const double A[3], const int *jps0, const int *nps_j, const double B[3], const double prim_exp[], const double prim_coe[], const int *nat, const double atom_x[], const double atom_y[], const double atom_z[], const int atomic_number[], double OVI[], double HCORE[] ) { int i, m, ips, jps, kat, ips1, jps1; double zeta_a, zeta_b, zeta, coef_a, coef_b, coef; double sqrzi, zi, xiza, xi, xiab2, xi2, exp_ab, css, zeta2; double oviss, keiss, tmp; double BA[3], P[3], PA[3], PC[3], AB2; double keips[3], keids[6], ovips[3], ovids[6]; double PC2, dq, U; double naiss[2+1], naips[2][3], naids[6]; double _pi32_ = _PI_32_, _2pi_ = _2PI_; double sqr3; sqr3 = sqrt(3.e0); for ( i=0; i<6; i++ ) OVI[i] = HCORE[i] = ZERO; AB2 = ZERO; for ( i=0; i<3; i++ ) { BA[i] = B[i]-A[i]; AB2 += BA[i]*BA[i]; } ips1 = *ips0 + (*nps_i); jps1 = *jps0 + (*nps_j); for ( ips=(*ips0); ips<ips1; ips++ ) { zeta_a = prim_exp[ips]; coef_a = prim_coe[ips]; for ( jps=(*jps0); jps<jps1; jps++ ) { zeta_b = prim_exp[jps]; coef_b = prim_coe[jps]; zeta = zeta_a + zeta_b; sqrzi = sqrt( 1.e0 / zeta ); zi = sqrzi * sqrzi; coef = coef_a * coef_b; xiza = zeta_b * zi; xi = xiza * zeta_a; xiab2 = xi * AB2; xi2 = 2.e0 * xi; zeta2 = HALF * zi; exp_ab = coef * exp( -xiab2 ); oviss = _pi32_ * zi * sqrzi * exp_ab; keiss = xi * ( 3.e0 - 2.e0 * xiab2 ) * oviss; css = _2pi_ * zi * exp_ab; if ( fabs(css) < EPS_PS_PAIR_NAI ) continue; for ( i=0; i<3; i++ ) { P[i] = xiza*BA[i] + A[i]; PA[i] = xiza*BA[i]; } // overlap integral // -- (P||S) -- ovips[0] = PA[0]*oviss; ovips[1] = PA[1]*oviss; ovips[2] = PA[2]*oviss; // -- (D||S) -- ovids[0] = PA[0]*ovips[0] + zeta2*oviss; ovids[1] = PA[1]*ovips[1] + zeta2*oviss; ovids[2] = PA[2]*ovips[2] + zeta2*oviss; ovids[3] = PA[0]*ovips[1]; ovids[4] = PA[1]*ovips[2]; ovids[5] = PA[2]*ovips[0]; // kinetic energy integral // -- (P|T|S) -- keips[0] = PA[0]*keiss + xi2*ovips[0]; keips[1] = PA[1]*keiss + xi2*ovips[1]; keips[2] = PA[2]*keiss + xi2*ovips[2]; // -- (D|T|S) -- tmp = zeta2*keiss - xiza*oviss; keids[0] = PA[0]*keips[0] + xi2*ovids[0] + tmp; keids[1] = PA[1]*keips[1] + xi2*ovids[1] + tmp; keids[2] = PA[2]*keips[2] + xi2*ovids[2] + tmp; keids[3] = PA[0]*keips[1] + xi2*ovids[3]; keids[4] = PA[1]*keips[2] + xi2*ovids[4]; keids[5] = PA[2]*keips[0] + xi2*ovids[5]; for ( i=0; i<6; i++ ) naids[i] = ZERO; for ( kat=0; kat<(*nat); kat++ ) { dq = (double)atomic_number[kat]; PC[0] = P[0]-atom_x[kat]; PC[1] = P[1]-atom_y[kat]; PC[2] = P[2]-atom_z[kat]; PC2 = PC[0]*PC[0] + PC[1]*PC[1] + PC[2]*PC[2]; U = zeta * PC2; { int it0, pos; double dT, t_inv, st_inv, dT2, dT3, cnass; cnass = dq*css; if ( U < 40e0 ) { it0 = (int)(0.5e0 + U * FMT_fmt_inv_step_size); dT = it0 * FMT_fmt_step_size - U; dT2 = dT * _inv2_; dT3 = dT * _inv3_; pos = it0 * (2+4); naiss[0] = cnass*(((FMT_fmt_table2[pos+3] * dT3 + FMT_fmt_table2[pos+2] ) * dT2 + FMT_fmt_table2[pos+1] ) * dT + FMT_fmt_table2[pos+0] ); naiss[1] = cnass*(((FMT_fmt_table2[pos+4] * dT3 + FMT_fmt_table2[pos+3] ) * dT2 + FMT_fmt_table2[pos+2] ) * dT + FMT_fmt_table2[pos+1] ); naiss[2] = cnass*(((FMT_fmt_table2[pos+5] * dT3 + FMT_fmt_table2[pos+4] ) * dT2 + FMT_fmt_table2[pos+3] ) * dT + FMT_fmt_table2[pos+2] ); } else { st_inv = sqrt( 0.5e0 / U ); t_inv = st_inv * st_inv; naiss[0] = cnass * _spi2_ * st_inv; naiss[1] = t_inv * naiss[0]; naiss[2] = 3.e0 * t_inv * naiss[1]; } } //fmt( naiss, 2, U, dq*css ); // -- (P|A(0)|S) -- for ( m=0; m<=1; m++) { naips[m][0] = PA[0]*naiss[m] - PC[0]*naiss[m+1]; naips[m][1] = PA[1]*naiss[m] - PC[1]*naiss[m+1]; naips[m][2] = PA[2]*naiss[m] - PC[2]*naiss[m+1]; } // -- (D|A|S) -- tmp = zeta2*( naiss[0] - naiss[1] ); naids[0] += PA[0]*naips[0][0] - PC[0]*naips[1][0] + tmp; naids[1] += PA[1]*naips[0][1] - PC[1]*naips[1][1] + tmp; naids[2] += PA[2]*naips[0][2] - PC[2]*naips[1][2] + tmp; naids[3] += PA[0]*naips[0][1] - PC[0]*naips[1][1]; naids[4] += PA[1]*naips[0][2] - PC[1]*naips[1][2]; naids[5] += PA[2]*naips[0][0] - PC[2]*naips[1][0]; } // contraction for ( i=0; i<6; i++ ) { OVI[i] += ovids[i]; HCORE[i] += (keids[i] - naids[i]); } } // jps } // ips for ( i=3; i<6; i++ ) { OVI[i] *= sqr3; HCORE[i] *= sqr3; } } /** 1つのCS対のDPタイプの1電子積分を計算する * @ingroup core-oneint * */ void oneint_core_dp__( const int *ips0, const int *nps_i, const double A[3], const int *jps0, const int *nps_j, const double B[3], const double prim_exp[], const double prim_coe[], const int *nat, const double atom_x[], const double atom_y[], const double atom_z[], const int atomic_number[], double OVI[], double HCORE[] ) { int i, j, ij, m, ips, jps, kat, ips1, jps1; double zeta_a, zeta_b, zeta, coef_a, coef_b, coef; double sqrzi, zi, xiza, xi, xiab2, xi2, exp_ab, css, zeta2; double oviss, keiss, tmp, tmpps[3]; double BA[3], P[3], PA[3], PC[3], PB[3], AB2; double keips[3], keids[6], keidp[6*3]; double ovips[3], ovids[6], ovidp[6*3]; double PC2, dq, U; double naiss[3+1], naips[2+1][3], naids[1+1][6], naidp[6*3]; double _pi32_ = _PI_32_, _2pi_ = _2PI_; double sqr3; sqr3 = sqrt(3.e0); for ( i=0; i<6*3; i++ ) OVI[i] = HCORE[i] = ZERO; AB2 = ZERO; for ( i=0; i<3; i++ ) { BA[i] = B[i]-A[i]; AB2 += BA[i]*BA[i]; } ips1 = *ips0 + (*nps_i); jps1 = *jps0 + (*nps_j); for ( ips=(*ips0); ips<ips1; ips++ ) { zeta_a = prim_exp[ips]; coef_a = prim_coe[ips]; for ( jps=(*jps0); jps<jps1; jps++ ) { zeta_b = prim_exp[jps]; coef_b = prim_coe[jps]; zeta = zeta_a + zeta_b; sqrzi = sqrt( 1.e0 / zeta ); zi = sqrzi * sqrzi; coef = coef_a * coef_b; xiza = zeta_b * zi; xi = xiza * zeta_a; xiab2 = xi * AB2; xi2 = 2.e0 * xi; zeta2 = HALF * zi; exp_ab = coef * exp( -xiab2 ); oviss = _pi32_ * zi * sqrzi * exp_ab; keiss = xi * ( 3.e0 - 2.e0 * xiab2 ) * oviss; css = _2pi_ * zi * exp_ab; if ( fabs(css) < EPS_PS_PAIR_NAI ) continue; for ( i=0; i<3; i++ ) { P[i] = xiza*BA[i] + A[i]; PA[i] = xiza*BA[i]; PB[i] = xiza*BA[i] - BA[i]; } // overlap integral // -- (P||S) -- ovips[0] = PA[0]*oviss; ovips[1] = PA[1]*oviss; ovips[2] = PA[2]*oviss; // -- (D||S) -- ovids[0] = PA[0]*ovips[0] + zeta2*oviss; ovids[1] = PA[1]*ovips[1] + zeta2*oviss; ovids[2] = PA[2]*ovips[2] + zeta2*oviss; ovids[3] = PA[0]*ovips[1]; ovids[4] = PA[1]*ovips[2]; ovids[5] = PA[2]*ovips[0]; // -- (D||P) -- ovidp[0*3+0] = PB[0]*ovids[0] + zi *ovips[0]; ovidp[0*3+1] = PB[1]*ovids[0]; ovidp[0*3+2] = PB[2]*ovids[0]; ovidp[1*3+0] = PB[0]*ovids[1]; ovidp[1*3+1] = PB[1]*ovids[1] + zi *ovips[1]; ovidp[1*3+2] = PB[2]*ovids[1]; ovidp[2*3+0] = PB[0]*ovids[2]; ovidp[2*3+1] = PB[1]*ovids[2]; ovidp[2*3+2] = PB[2]*ovids[2] + zi *ovips[2]; ovidp[3*3+0] = PB[0]*ovids[3] + zeta2*ovips[1]; ovidp[3*3+1] = PB[1]*ovids[3] + zeta2*ovips[0]; ovidp[3*3+2] = PB[2]*ovids[3]; ovidp[4*3+0] = PB[0]*ovids[4]; ovidp[4*3+1] = PB[1]*ovids[4] + zeta2*ovips[2]; ovidp[4*3+2] = PB[2]*ovids[4] + zeta2*ovips[1]; ovidp[5*3+0] = PB[0]*ovids[5] + zeta2*ovips[2]; ovidp[5*3+1] = PB[1]*ovids[5]; ovidp[5*3+2] = PB[2]*ovids[5] + zeta2*ovips[0]; // kinetic energy integral // -- (P|T|S) -- keips[0] = PA[0]*keiss + xi2*ovips[0]; keips[1] = PA[1]*keiss + xi2*ovips[1]; keips[2] = PA[2]*keiss + xi2*ovips[2]; // -- (D|T|S) -- tmp = zeta2*keiss - xiza*oviss; keids[0] = PA[0]*keips[0] + xi2*ovids[0] + tmp; keids[1] = PA[1]*keips[1] + xi2*ovids[1] + tmp; keids[2] = PA[2]*keips[2] + xi2*ovids[2] + tmp; keids[3] = PA[0]*keips[1] + xi2*ovids[3]; keids[4] = PA[1]*keips[2] + xi2*ovids[4]; keids[5] = PA[2]*keips[0] + xi2*ovids[5]; // -- (D|T|P) -- keidp[0*3+0] = PB[0]*keids[0] + xi2*ovidp[0*3+0] + zi*keips[0]; keidp[0*3+1] = PB[1]*keids[0] + xi2*ovidp[0*3+1]; keidp[0*3+2] = PB[2]*keids[0] + xi2*ovidp[0*3+2]; keidp[1*3+0] = PB[0]*keids[1] + xi2*ovidp[1*3+0]; keidp[1*3+1] = PB[1]*keids[1] + xi2*ovidp[1*3+1] + zi*keips[1]; keidp[1*3+2] = PB[2]*keids[1] + xi2*ovidp[1*3+2]; keidp[2*3+0] = PB[0]*keids[2] + xi2*ovidp[2*3+0]; keidp[2*3+1] = PB[1]*keids[2] + xi2*ovidp[2*3+1]; keidp[2*3+2] = PB[2]*keids[2] + xi2*ovidp[2*3+2] + zi*keips[2]; keidp[3*3+0] = PB[0]*keids[3] + xi2*ovidp[3*3+0] + zeta2*keips[1]; keidp[3*3+1] = PB[1]*keids[3] + xi2*ovidp[3*3+1] + zeta2*keips[0]; keidp[3*3+2] = PB[2]*keids[3] + xi2*ovidp[3*3+2]; keidp[4*3+0] = PB[0]*keids[4] + xi2*ovidp[4*3+0]; keidp[4*3+1] = PB[1]*keids[4] + xi2*ovidp[4*3+1] + zeta2*keips[2]; keidp[4*3+2] = PB[2]*keids[4] + xi2*ovidp[4*3+2] + zeta2*keips[1]; keidp[5*3+0] = PB[0]*keids[5] + xi2*ovidp[5*3+0] + zeta2*keips[2]; keidp[5*3+1] = PB[1]*keids[5] + xi2*ovidp[5*3+1]; keidp[5*3+2] = PB[2]*keids[5] + xi2*ovidp[5*3+2] + zeta2*keips[0]; for ( i=0; i<6*3; i++ ) naidp[i] = ZERO; for ( kat=0; kat<(*nat); kat++ ) { dq = (double)atomic_number[kat]; PC[0] = P[0]-atom_x[kat]; PC[1] = P[1]-atom_y[kat]; PC[2] = P[2]-atom_z[kat]; PC2 = PC[0]*PC[0] + PC[1]*PC[1] + PC[2]*PC[2]; U = zeta * PC2; { int it0, pos; double dT, t_inv, st_inv, dT2, dT3, cnass; cnass = dq*css; if ( U < 42e0 ) { it0 = (int)(0.5e0 + U * FMT_fmt_inv_step_size); dT = it0 * FMT_fmt_step_size - U; dT2 = dT * _inv2_; dT3 = dT * _inv3_; pos = it0 * (3+4); naiss[0] = cnass*(((FMT_fmt_table3[pos+3] * dT3 + FMT_fmt_table3[pos+2] ) * dT2 + FMT_fmt_table3[pos+1] ) * dT + FMT_fmt_table3[pos+0] ); naiss[1] = cnass*(((FMT_fmt_table3[pos+4] * dT3 + FMT_fmt_table3[pos+3] ) * dT2 + FMT_fmt_table3[pos+2] ) * dT + FMT_fmt_table3[pos+1] ); naiss[2] = cnass*(((FMT_fmt_table3[pos+5] * dT3 + FMT_fmt_table3[pos+4] ) * dT2 + FMT_fmt_table3[pos+3] ) * dT + FMT_fmt_table3[pos+2] ); naiss[3] = cnass*(((FMT_fmt_table3[pos+6] * dT3 + FMT_fmt_table3[pos+5] ) * dT2 + FMT_fmt_table3[pos+4] ) * dT + FMT_fmt_table3[pos+3] ); } else { st_inv = sqrt( 0.5e0 / U ); t_inv = st_inv * st_inv; naiss[0] = cnass * _spi2_ * st_inv; naiss[1] = t_inv * naiss[0]; naiss[2] = 3.e0 * t_inv * naiss[1]; naiss[3] = 5.e0 * t_inv * naiss[2]; } } //fmt( naiss, 3, U, dq*css ); // -- (P|A(0)|S) -- for ( m=0; m<=2; m++) { naips[m][0] = PA[0]*naiss[m] - PC[0]*naiss[m+1]; naips[m][1] = PA[1]*naiss[m] - PC[1]*naiss[m+1]; naips[m][2] = PA[2]*naiss[m] - PC[2]*naiss[m+1]; } // -- (D|A(0)|S) -- for (m=0; m<=1; m++) { tmp = naiss[m] - naiss[m+1]; naids[m][0] = PA[0]*naips[m][0]-PC[0]*naips[m+1][0] + zeta2*tmp; naids[m][1] = PA[1]*naips[m][1]-PC[1]*naips[m+1][1] + zeta2*tmp; naids[m][2] = PA[2]*naips[m][2]-PC[2]*naips[m+1][2] + zeta2*tmp; naids[m][3] = PA[0]*naips[m][1]-PC[0]*naips[m+1][1]; naids[m][4] = PA[1]*naips[m][2]-PC[1]*naips[m+1][2]; naids[m][5] = PA[2]*naips[m][0]-PC[2]*naips[m+1][0]; } // -- (D|A|P) -- tmpps[0] = naips[0][0] - naips[1][0]; tmpps[1] = naips[0][1] - naips[1][1]; tmpps[2] = naips[0][2] - naips[1][2]; naidp[0*3+0] += PB[0]*naids[0][0] - PC[0]*naids[1][0] + zi*tmpps[0]; naidp[0*3+1] += PB[1]*naids[0][0] - PC[1]*naids[1][0]; naidp[0*3+2] += PB[2]*naids[0][0] - PC[2]*naids[1][0]; naidp[1*3+0] += PB[0]*naids[0][1] - PC[0]*naids[1][1]; naidp[1*3+1] += PB[1]*naids[0][1] - PC[1]*naids[1][1] + zi*tmpps[1]; naidp[1*3+2] += PB[2]*naids[0][1] - PC[2]*naids[1][1]; naidp[2*3+0] += PB[0]*naids[0][2] - PC[0]*naids[1][2]; naidp[2*3+1] += PB[1]*naids[0][2] - PC[1]*naids[1][2]; naidp[2*3+2] += PB[2]*naids[0][2] - PC[2]*naids[1][2] + zi*tmpps[2]; naidp[3*3+0] += PB[0]*naids[0][3] - PC[0]*naids[1][3] + zeta2*tmpps[1]; naidp[3*3+1] += PB[1]*naids[0][3] - PC[1]*naids[1][3] + zeta2*tmpps[0]; naidp[3*3+2] += PB[2]*naids[0][3] - PC[2]*naids[1][3]; naidp[4*3+0] += PB[0]*naids[0][4] - PC[0]*naids[1][4]; naidp[4*3+1] += PB[1]*naids[0][4] - PC[1]*naids[1][4] + zeta2*tmpps[2]; naidp[4*3+2] += PB[2]*naids[0][4] - PC[2]*naids[1][4] + zeta2*tmpps[1]; naidp[5*3+0] += PB[0]*naids[0][5] - PC[0]*naids[1][5] + zeta2*tmpps[2]; naidp[5*3+1] += PB[1]*naids[0][5] - PC[1]*naids[1][5]; naidp[5*3+2] += PB[2]*naids[0][5] - PC[2]*naids[1][5] + zeta2*tmpps[0]; } // contraction for ( i=0; i<6*3; i++ ) { OVI[i] += ovidp[i]; HCORE[i] += (keidp[i] - naidp[i]); } } // jps } // ips for ( i=3; i<6; i++ ) { for ( j=0; j<3; j++ ) { ij = i*3+j; OVI[ij] *= sqr3; HCORE[ij] *= sqr3; } } } /** 1つのCS対のDDタイプの1電子積分を計算する * @ingroup core-oneint * */ void oneint_core_dd__( const int *ips0, const int *nps_i, const double A[3], const int *jps0, const int *nps_j, const double B[3], const double prim_exp[], const double prim_coe[], const int *nat, const double atom_x[], const double atom_y[], const double atom_z[], const int atomic_number[], double OVI[], double HCORE[] ) { int i, j, ij, m, ips, jps, kat, ips1, jps1; double zeta_a, zeta_b, zeta, coef_a, coef_b, coef; double sqrzi, zi, xiza, xizb, xi, xiab2, xi2, exp_ab, css, zeta2; double oviss, keiss, tmp, tmpps[3], tmppp[3*3], tmpds[6]; double BA[3], P[3], PA[3], PC[3], PB[3], AB2; double keips[3], keids[6], keipp[3*3], keidp[6*3], keidd[6*6]; double ovips[3], ovids[6], ovipp[3*3], ovidp[6*3], ovidd[6*6]; double PC2, dq, U; double naiss[4+1], naips[3+1][3], naids[2+1][6], naidp[1+1][6*3]; double naipp[1+1][3*3], naidd[6*6]; double _pi32_ = _PI_32_, _2pi_ = _2PI_; double sqr3, coe_a, coe; sqr3 = sqrt(3.e0); for ( i=0; i<6*6; i++ ) OVI[i] = HCORE[i] = ZERO; AB2 = ZERO; for ( i=0; i<3; i++ ) { BA[i] = B[i]-A[i]; AB2 += BA[i]*BA[i]; } ips1 = *ips0 + (*nps_i); jps1 = *jps0 + (*nps_j); for ( ips=(*ips0); ips<ips1; ips++ ) { zeta_a = prim_exp[ips]; coef_a = prim_coe[ips]; for ( jps=(*jps0); jps<jps1; jps++ ) { zeta_b = prim_exp[jps]; coef_b = prim_coe[jps]; zeta = zeta_a + zeta_b; sqrzi = sqrt( 1.e0 / zeta ); zi = sqrzi * sqrzi; coef = coef_a * coef_b; xiza = zeta_b * zi; xizb = zeta_a * zi; xi = xiza * zeta_a; xiab2 = xi * AB2; xi2 = 2.e0 * xi; zeta2 = HALF * zi; exp_ab = coef * exp( -xiab2 ); oviss = _pi32_ * zi * sqrzi * exp_ab; keiss = xi * ( 3.e0 - 2.e0 * xiab2 ) * oviss; css = _2pi_ * zi * exp_ab; if ( fabs(css) < EPS_PS_PAIR_NAI ) continue; for ( i=0; i<3; i++ ) { P[i] = xiza*BA[i] + A[i]; PA[i] = xiza*BA[i]; PB[i] = xiza*BA[i] - BA[i]; } // overlap integral // -- (P||S) -- ovips[0] = PA[0]*oviss; ovips[1] = PA[1]*oviss; ovips[2] = PA[2]*oviss; // -- (D||S) -- ovids[0] = PA[0]*ovips[0] + zeta2*oviss; ovids[1] = PA[1]*ovips[1] + zeta2*oviss; ovids[2] = PA[2]*ovips[2] + zeta2*oviss; ovids[3] = PA[0]*ovips[1]; ovids[4] = PA[1]*ovips[2]; ovids[5] = PA[2]*ovips[0]; // -- (P||P) -- ovipp[0*3+0] = PB[0]*ovips[0] + zeta2*oviss; ovipp[0*3+1] = PB[1]*ovips[0]; ovipp[0*3+2] = PB[2]*ovips[0]; ovipp[1*3+0] = PB[0]*ovips[1]; ovipp[1*3+1] = PB[1]*ovips[1] + zeta2*oviss; ovipp[1*3+2] = PB[2]*ovips[1]; ovipp[2*3+0] = PB[0]*ovips[2]; ovipp[2*3+1] = PB[1]*ovips[2]; ovipp[2*3+2] = PB[2]*ovips[2] + zeta2*oviss; // -- (D||P) -- ovidp[0*3+0] = PB[0]*ovids[0] + zi *ovips[0]; ovidp[0*3+1] = PB[1]*ovids[0]; ovidp[0*3+2] = PB[2]*ovids[0]; ovidp[1*3+0] = PB[0]*ovids[1]; ovidp[1*3+1] = PB[1]*ovids[1] + zi *ovips[1]; ovidp[1*3+2] = PB[2]*ovids[1]; ovidp[2*3+0] = PB[0]*ovids[2]; ovidp[2*3+1] = PB[1]*ovids[2]; ovidp[2*3+2] = PB[2]*ovids[2] + zi *ovips[2]; ovidp[3*3+0] = PB[0]*ovids[3] + zeta2*ovips[1]; ovidp[3*3+1] = PB[1]*ovids[3] + zeta2*ovips[0]; ovidp[3*3+2] = PB[2]*ovids[3]; ovidp[4*3+0] = PB[0]*ovids[4]; ovidp[4*3+1] = PB[1]*ovids[4] + zeta2*ovips[2]; ovidp[4*3+2] = PB[2]*ovids[4] + zeta2*ovips[1]; ovidp[5*3+0] = PB[0]*ovids[5] + zeta2*ovips[2]; ovidp[5*3+1] = PB[1]*ovids[5]; ovidp[5*3+2] = PB[2]*ovids[5] + zeta2*ovips[0]; // -- (D||D) -- ovidd[0*6+0] = PB[0]*ovidp[0*3+0] + zeta2*ovids[0] + zi*ovipp[0*3+0]; ovidd[0*6+1] = PB[1]*ovidp[0*3+1] + zeta2*ovids[0]; ovidd[0*6+2] = PB[2]*ovidp[0*3+2] + zeta2*ovids[0]; ovidd[0*6+3] = PB[0]*ovidp[0*3+1] + zi*ovipp[0*3+1]; ovidd[0*6+4] = PB[1]*ovidp[0*3+2]; ovidd[0*6+5] = PB[2]*ovidp[0*3+0]; ovidd[1*6+0] = PB[0]*ovidp[1*3+0] + zeta2*ovids[1]; ovidd[1*6+1] = PB[1]*ovidp[1*3+1] + zeta2*ovids[1] + zi*ovipp[1*3+1]; ovidd[1*6+2] = PB[2]*ovidp[1*3+2] + zeta2*ovids[1]; ovidd[1*6+3] = PB[0]*ovidp[1*3+1]; ovidd[1*6+4] = PB[1]*ovidp[1*3+2] + zi*ovipp[1*3+2]; ovidd[1*6+5] = PB[2]*ovidp[1*3+0]; ovidd[2*6+0] = PB[0]*ovidp[2*3+0] + zeta2*ovids[2]; ovidd[2*6+1] = PB[1]*ovidp[2*3+1] + zeta2*ovids[2]; ovidd[2*6+2] = PB[2]*ovidp[2*3+2] + zeta2*ovids[2] + zi*ovipp[2*3+2]; ovidd[2*6+3] = PB[0]*ovidp[2*3+1]; ovidd[2*6+4] = PB[1]*ovidp[2*3+2]; ovidd[2*6+5] = PB[2]*ovidp[2*3+0] + zi*ovipp[2*3+0]; ovidd[3*6+0] = PB[0]*ovidp[3*3+0] + zeta2*ovids[3] + zeta2*ovipp[1*3+0]; ovidd[3*6+1] = PB[1]*ovidp[3*3+1] + zeta2*ovids[3] + zeta2*ovipp[0*3+1]; ovidd[3*6+2] = PB[2]*ovidp[3*3+2] + zeta2*ovids[3]; ovidd[3*6+3] = PB[0]*ovidp[3*3+1] + zeta2*ovipp[1*3+1]; ovidd[3*6+4] = PB[1]*ovidp[3*3+2] + zeta2*ovipp[0*3+2]; ovidd[3*6+5] = PB[2]*ovidp[3*3+0]; ovidd[4*6+0] = PB[0]*ovidp[4*3+0] + zeta2*ovids[4]; ovidd[4*6+1] = PB[1]*ovidp[4*3+1] + zeta2*ovids[4] + zeta2*ovipp[2*3+1]; ovidd[4*6+2] = PB[2]*ovidp[4*3+2] + zeta2*ovids[4] + zeta2*ovipp[1*3+2]; ovidd[4*6+3] = PB[0]*ovidp[4*3+1]; ovidd[4*6+4] = PB[1]*ovidp[4*3+2] + zeta2*ovipp[2*3+2]; ovidd[4*6+5] = PB[2]*ovidp[4*3+0] + zeta2*ovipp[1*3+0]; ovidd[5*6+0] = PB[0]*ovidp[5*3+0] + zeta2*ovids[5] + zeta2*ovipp[2*3+0]; ovidd[5*6+1] = PB[1]*ovidp[5*3+1] + zeta2*ovids[5]; ovidd[5*6+2] = PB[2]*ovidp[5*3+2] + zeta2*ovids[5] + zeta2*ovipp[0*3+2]; ovidd[5*6+3] = PB[0]*ovidp[5*3+1] + zeta2*ovipp[2*3+1]; ovidd[5*6+4] = PB[1]*ovidp[5*3+2]; ovidd[5*6+5] = PB[2]*ovidp[5*3+0] + zeta2*ovipp[0*3+0]; // kinetic energy integral // -- (P|T|S) -- keips[0] = PA[0]*keiss + xi2*ovips[0]; keips[1] = PA[1]*keiss + xi2*ovips[1]; keips[2] = PA[2]*keiss + xi2*ovips[2]; // -- (D|T|S) -- tmp = zeta2*keiss - xiza*oviss; keids[0] = PA[0]*keips[0] + xi2*ovids[0] + tmp; keids[1] = PA[1]*keips[1] + xi2*ovids[1] + tmp; keids[2] = PA[2]*keips[2] + xi2*ovids[2] + tmp; keids[3] = PA[0]*keips[1] + xi2*ovids[3]; keids[4] = PA[1]*keips[2] + xi2*ovids[4]; keids[5] = PA[2]*keips[0] + xi2*ovids[5]; // -- (P|T|P) -- keipp[0*3+0]=PB[0]*keips[0]+xi2*ovipp[0*3+0]+zeta2*keiss; keipp[0*3+1]=PB[1]*keips[0]+xi2*ovipp[0*3+1]; keipp[0*3+2]=PB[2]*keips[0]+xi2*ovipp[0*3+2]; keipp[1*3+0]=PB[0]*keips[1]+xi2*ovipp[1*3+0]; keipp[1*3+1]=PB[1]*keips[1]+xi2*ovipp[1*3+1]+zeta2*keiss; keipp[1*3+2]=PB[2]*keips[1]+xi2*ovipp[1*3+2]; keipp[2*3+0]=PB[0]*keips[2]+xi2*ovipp[2*3+0]; keipp[2*3+1]=PB[1]*keips[2]+xi2*ovipp[2*3+1]; keipp[2*3+2]=PB[2]*keips[2]+xi2*ovipp[2*3+2]+zeta2*keiss; // -- (D|T|P) -- keidp[0*3+0]=PB[0]*keids[0]+xi2*ovidp[0*3+0]+zi*keips[0]; keidp[0*3+1]=PB[1]*keids[0]+xi2*ovidp[0*3+1]; keidp[0*3+2]=PB[2]*keids[0]+xi2*ovidp[0*3+2]; keidp[1*3+0]=PB[0]*keids[1]+xi2*ovidp[1*3+0]; keidp[1*3+1]=PB[1]*keids[1]+xi2*ovidp[1*3+1]+zi*keips[1]; keidp[1*3+2]=PB[2]*keids[1]+xi2*ovidp[1*3+2]; keidp[2*3+0]=PB[0]*keids[2]+xi2*ovidp[2*3+0]; keidp[2*3+1]=PB[1]*keids[2]+xi2*ovidp[2*3+1]; keidp[2*3+2]=PB[2]*keids[2]+xi2*ovidp[2*3+2]+zi*keips[2]; keidp[3*3+0]=PB[0]*keids[3]+xi2*ovidp[3*3+0] +zeta2*keips[1]; keidp[3*3+1]=PB[1]*keids[3]+xi2*ovidp[3*3+1] +zeta2*keips[0]; keidp[3*3+2]=PB[2]*keids[3]+xi2*ovidp[3*3+2]; keidp[4*3+0]=PB[0]*keids[4]+xi2*ovidp[4*3+0]; keidp[4*3+1]=PB[1]*keids[4]+xi2*ovidp[4*3+1] +zeta2*keips[2]; keidp[4*3+2]=PB[2]*keids[4]+xi2*ovidp[4*3+2] +zeta2*keips[1]; keidp[5*3+0]=PB[0]*keids[5]+xi2*ovidp[5*3+0] +zeta2*keips[2]; keidp[5*3+1]=PB[1]*keids[5]+xi2*ovidp[5*3+1]; keidp[5*3+2]=PB[2]*keids[5]+xi2*ovidp[5*3+2] +zeta2*keips[0]; // -- (D|T|D) -- tmpds[0] = zeta2*keids[0] - xizb*ovids[0]; tmpds[1] = zeta2*keids[1] - xizb*ovids[1]; tmpds[2] = zeta2*keids[2] - xizb*ovids[2]; tmpds[3] = zeta2*keids[3] - xizb*ovids[3]; tmpds[4] = zeta2*keids[4] - xizb*ovids[4]; tmpds[5] = zeta2*keids[5] - xizb*ovids[5]; keidd[0*6+0] = PB[0]*keidp[0*3+0]+xi2*ovidd[0*6+0] + tmpds[0]+zi*keipp[0*3+0]; keidd[0*6+1] = PB[1]*keidp[0*3+1]+xi2*ovidd[0*6+1]+tmpds[0]; keidd[0*6+2] = PB[2]*keidp[0*3+2]+xi2*ovidd[0*6+2]+tmpds[0]; keidd[0*6+3] = PB[0]*keidp[0*3+1]+xi2*ovidd[0*6+3] +zi*keipp[0*3+1]; keidd[0*6+4] = PB[1]*keidp[0*3+2]+xi2*ovidd[0*6+4]; keidd[0*6+5] = PB[2]*keidp[0*3+0]+xi2*ovidd[0*6+5]; keidd[1*6+0] = PB[0]*keidp[1*3+0]+xi2*ovidd[1*6+0]+tmpds[1]; keidd[1*6+1] = PB[1]*keidp[1*3+1]+xi2*ovidd[1*6+1] + tmpds[1]+zi*keipp[1*3+1]; keidd[1*6+2] = PB[2]*keidp[1*3+2]+xi2*ovidd[1*6+2]+tmpds[1]; keidd[1*6+3] = PB[0]*keidp[1*3+1]+xi2*ovidd[1*6+3]; keidd[1*6+4] = PB[1]*keidp[1*3+2]+xi2*ovidd[1*6+4] +zi*keipp[1*3+2]; keidd[1*6+5] = PB[2]*keidp[1*3+0]+xi2*ovidd[1*6+5]; keidd[2*6+0] = PB[0]*keidp[2*3+0]+xi2*ovidd[2*6+0]+tmpds[2]; keidd[2*6+1] = PB[1]*keidp[2*3+1]+xi2*ovidd[2*6+1]+tmpds[2]; keidd[2*6+2] = PB[2]*keidp[2*3+2]+xi2*ovidd[2*6+2] + tmpds[2]+zi*keipp[2*3+2]; keidd[2*6+3] = PB[0]*keidp[2*3+1]+xi2*ovidd[2*6+3]; keidd[2*6+4] = PB[1]*keidp[2*3+2]+xi2*ovidd[2*6+4]; keidd[2*6+5] = PB[2]*keidp[2*3+0]+xi2*ovidd[2*6+5] +zi*keipp[2*3+0]; keidd[3*6+0] = PB[0]*keidp[3*3+0]+xi2*ovidd[3*6+0] + tmpds[3]+zeta2*keipp[1*3+0]; keidd[3*6+1] = PB[1]*keidp[3*3+1]+xi2*ovidd[3*6+1] + tmpds[3]+zeta2*keipp[0*3+1]; keidd[3*6+2] = PB[2]*keidp[3*3+2]+xi2*ovidd[3*6+2]+tmpds[3]; keidd[3*6+3] = PB[0]*keidp[3*3+1]+xi2*ovidd[3*6+3] +zeta2*keipp[1*3+1]; keidd[3*6+4] = PB[1]*keidp[3*3+2]+xi2*ovidd[3*6+4] +zeta2*keipp[0*3+2]; keidd[3*6+5] = PB[2]*keidp[3*3+0]+xi2*ovidd[3*6+5]; keidd[4*6+0] = PB[0]*keidp[4*3+0]+xi2*ovidd[4*6+0]+tmpds[4]; keidd[4*6+1] = PB[1]*keidp[4*3+1]+xi2*ovidd[4*6+1] + tmpds[4]+zeta2*keipp[2*3+1]; keidd[4*6+2] = PB[2]*keidp[4*3+2]+xi2*ovidd[4*6+2] + tmpds[4]+zeta2*keipp[1*3+2]; keidd[4*6+3] = PB[0]*keidp[4*3+1]+xi2*ovidd[4*6+3]; keidd[4*6+4] = PB[1]*keidp[4*3+2]+xi2*ovidd[4*6+4] +zeta2*keipp[2*3+2]; keidd[4*6+5] = PB[2]*keidp[4*3+0]+xi2*ovidd[4*6+5] +zeta2*keipp[1*3+0]; keidd[5*6+0] = PB[0]*keidp[5*3+0]+xi2*ovidd[5*6+0] + tmpds[5]+zeta2*keipp[2*3+0]; keidd[5*6+1] = PB[1]*keidp[5*3+1]+xi2*ovidd[5*6+1]+tmpds[5]; keidd[5*6+2] = PB[2]*keidp[5*3+2]+xi2*ovidd[5*6+2] + tmpds[5]+zeta2*keipp[0*3+2]; keidd[5*6+3] = PB[0]*keidp[5*3+1]+xi2*ovidd[5*6+3] +zeta2*keipp[2*3+1]; keidd[5*6+4] = PB[1]*keidp[5*3+2]+xi2*ovidd[5*6+4]; keidd[5*6+5] = PB[2]*keidp[5*3+0]+xi2*ovidd[5*6+5] +zeta2*keipp[0*3+0]; for ( i=0; i<6*6; i++ ) naidd[i] = ZERO; for ( kat=0; kat<(*nat); kat++ ) { dq = (double)atomic_number[kat]; PC[0] = P[0]-atom_x[kat]; PC[1] = P[1]-atom_y[kat]; PC[2] = P[2]-atom_z[kat]; PC2 = PC[0]*PC[0] + PC[1]*PC[1] + PC[2]*PC[2]; U = zeta * PC2; { int it0, pos; double dT, t_inv, st_inv, dT2, dT3, cnass; cnass = dq*css; if ( U < 44e0 ) { it0 = (int)(0.5e0 + U * FMT_fmt_inv_step_size); dT = it0 * FMT_fmt_step_size - U; dT2 = dT * _inv2_; dT3 = dT * _inv3_; pos = it0 * (4+4); naiss[0] = cnass*(((FMT_fmt_table4[pos+3] * dT3 + FMT_fmt_table4[pos+2] ) * dT2 + FMT_fmt_table4[pos+1] ) * dT + FMT_fmt_table4[pos+0] ); naiss[1] = cnass*(((FMT_fmt_table4[pos+4] * dT3 + FMT_fmt_table4[pos+3] ) * dT2 + FMT_fmt_table4[pos+2] ) * dT + FMT_fmt_table4[pos+1] ); naiss[2] = cnass*(((FMT_fmt_table4[pos+5] * dT3 + FMT_fmt_table4[pos+4] ) * dT2 + FMT_fmt_table4[pos+3] ) * dT + FMT_fmt_table4[pos+2] ); naiss[3] = cnass*(((FMT_fmt_table4[pos+6] * dT3 + FMT_fmt_table4[pos+5] ) * dT2 + FMT_fmt_table4[pos+4] ) * dT + FMT_fmt_table4[pos+3] ); naiss[4] = cnass*(((FMT_fmt_table4[pos+7] * dT3 + FMT_fmt_table4[pos+6] ) * dT2 + FMT_fmt_table4[pos+5] ) * dT + FMT_fmt_table4[pos+4] ); } else { st_inv = sqrt( 0.5e0 / U ); t_inv = st_inv * st_inv; naiss[0] = cnass * _spi2_ * st_inv; naiss[1] = t_inv * naiss[0]; naiss[2] = 3.e0 * t_inv * naiss[1]; naiss[3] = 5.e0 * t_inv * naiss[2]; naiss[4] = 7.e0 * t_inv * naiss[3]; } } //fmt( naiss, 4, U, dq*css ); // -- (P|A(0)|S) -- for ( m=0; m<=3; m++) { naips[m][0] = PA[0]*naiss[m] - PC[0]*naiss[m+1]; naips[m][1] = PA[1]*naiss[m] - PC[1]*naiss[m+1]; naips[m][2] = PA[2]*naiss[m] - PC[2]*naiss[m+1]; } // -- (D|A(0)|S) -- for (m=0; m<=2; m++) { tmp = naiss[m] - naiss[m+1]; naids[m][0] = PA[0]*naips[m][0]-PC[0]*naips[m+1][0] + zeta2*tmp; naids[m][1] = PA[1]*naips[m][1]-PC[1]*naips[m+1][1] + zeta2*tmp; naids[m][2] = PA[2]*naips[m][2]-PC[2]*naips[m+1][2] + zeta2*tmp; naids[m][3] = PA[0]*naips[m][1]-PC[0]*naips[m+1][1]; naids[m][4] = PA[1]*naips[m][2]-PC[1]*naips[m+1][2]; naids[m][5] = PA[2]*naips[m][0]-PC[2]*naips[m+1][0]; } // -- (P|A|P) -- for (m=0; m<=1; m++) { tmp = naiss[m] - naiss[m+1]; naipp[m][0*3+0]=PB[0]*naips[m][0]-PC[0]*naips[m+1][0] +zeta2*tmp; naipp[m][0*3+1]=PB[1]*naips[m][0]-PC[1]*naips[m+1][0]; naipp[m][0*3+2]=PB[2]*naips[m][0]-PC[2]*naips[m+1][0]; naipp[m][1*3+0]=PB[0]*naips[m][1]-PC[0]*naips[m+1][1]; naipp[m][1*3+1]=PB[1]*naips[m][1]-PC[1]*naips[m+1][1] +zeta2*tmp; naipp[m][1*3+2]=PB[2]*naips[m][1]-PC[2]*naips[m+1][1]; naipp[m][2*3+0]=PB[0]*naips[m][2]-PC[0]*naips[m+1][2]; naipp[m][2*3+1]=PB[1]*naips[m][2]-PC[1]*naips[m+1][2]; naipp[m][2*3+2]=PB[2]*naips[m][2]-PC[2]*naips[m+1][2] +zeta2*tmp; } // -- (D|A|P) -- for (m=0; m<=1; m++) { tmpps[0] = naips[m][0]-naips[m+1][0]; tmpps[1] = naips[m][1]-naips[m+1][1]; tmpps[2] = naips[m][2]-naips[m+1][2]; naidp[m][0*3+0]=PB[0]*naids[m][0]-PC[0]*naids[m+1][0] +zi*tmpps[0]; naidp[m][0*3+1]=PB[1]*naids[m][0]-PC[1]*naids[m+1][0]; naidp[m][0*3+2]=PB[2]*naids[m][0]-PC[2]*naids[m+1][0]; naidp[m][1*3+0]=PB[0]*naids[m][1]-PC[0]*naids[m+1][1]; naidp[m][1*3+1]=PB[1]*naids[m][1]-PC[1]*naids[m+1][1] +zi*tmpps[1]; naidp[m][1*3+2]=PB[2]*naids[m][1]-PC[2]*naids[m+1][1]; naidp[m][2*3+0]=PB[0]*naids[m][2]-PC[0]*naids[m+1][2]; naidp[m][2*3+1]=PB[1]*naids[m][2]-PC[1]*naids[m+1][2]; naidp[m][2*3+2]=PB[2]*naids[m][2]-PC[2]*naids[m+1][2] +zi*tmpps[2]; naidp[m][3*3+0]=PB[0]*naids[m][3]-PC[0]*naids[m+1][3] + zeta2*tmpps[1]; naidp[m][3*3+1]=PB[1]*naids[m][3]-PC[1]*naids[m+1][3] +zeta2*tmpps[0]; naidp[m][3*3+2]=PB[2]*naids[m][3]-PC[2]*naids[m+1][3]; naidp[m][4*3+0]=PB[0]*naids[m][4]-PC[0]*naids[m+1][4]; naidp[m][4*3+1]=PB[1]*naids[m][4]-PC[1]*naids[m+1][4] +zeta2*tmpps[2]; naidp[m][4*3+2]=PB[2]*naids[m][4]-PC[2]*naids[m+1][4] +zeta2*tmpps[1]; naidp[m][5*3+0]=PB[0]*naids[m][5]-PC[0]*naids[m+1][5] +zeta2*tmpps[2]; naidp[m][5*3+1]=PB[1]*naids[m][5]-PC[1]*naids[m+1][5]; naidp[m][5*3+2]=PB[2]*naids[m][5]-PC[2]*naids[m+1][5] +zeta2*tmpps[0]; } // -- (D|A|D) -- tmpds[0]=naids[0][0]-naids[1][0]; tmpds[1]=naids[0][1]-naids[1][1]; tmpds[2]=naids[0][2]-naids[1][2]; tmpds[3]=naids[0][3]-naids[1][3]; tmpds[4]=naids[0][4]-naids[1][4]; tmpds[5]=naids[0][5]-naids[1][5]; tmppp[0*3+0]=naipp[0][0*3+0]-naipp[1][0*3+0]; tmppp[0*3+1]=naipp[0][0*3+1]-naipp[1][0*3+1]; tmppp[0*3+2]=naipp[0][0*3+2]-naipp[1][0*3+2]; tmppp[1*3+0]=naipp[0][1*3+0]-naipp[1][1*3+0]; tmppp[1*3+1]=naipp[0][1*3+1]-naipp[1][1*3+1]; tmppp[1*3+2]=naipp[0][1*3+2]-naipp[1][1*3+2]; tmppp[2*3+0]=naipp[0][2*3+0]-naipp[1][2*3+0]; tmppp[2*3+1]=naipp[0][2*3+1]-naipp[1][2*3+1]; tmppp[2*3+2]=naipp[0][2*3+2]-naipp[1][2*3+2]; naidd[0*6+0]+=PB[0]*naidp[0][0*3+0]-PC[0]*naidp[1][0*3+0] + zeta2*tmpds[0]+zi*tmppp[0*3+0]; naidd[0*6+1]+=PB[1]*naidp[0][0*3+1]-PC[1]*naidp[1][0*3+1] + zeta2*tmpds[0]; naidd[0*6+2]+=PB[2]*naidp[0][0*3+2]-PC[2]*naidp[1][0*3+2] + zeta2*tmpds[0]; naidd[0*6+3]+=PB[0]*naidp[0][0*3+1]-PC[0]*naidp[1][0*3+1] + zi*tmppp[0*3+1]; naidd[0*6+4]+=PB[1]*naidp[0][0*3+2]-PC[1]*naidp[1][0*3+2]; naidd[0*6+5]+=PB[2]*naidp[0][0*3+0]-PC[2]*naidp[1][0*3+0]; naidd[1*6+0]+=PB[0]*naidp[0][1*3+0]-PC[0]*naidp[1][1*3+0] + zeta2*tmpds[1]; naidd[1*6+1]+=PB[1]*naidp[0][1*3+1]-PC[1]*naidp[1][1*3+1] + zeta2*tmpds[1]+zi*tmppp[1*3+1]; naidd[1*6+2]+=PB[2]*naidp[0][1*3+2]-PC[2]*naidp[1][1*3+2] + zeta2*tmpds[1]; naidd[1*6+3]+=PB[0]*naidp[0][1*3+1]-PC[0]*naidp[1][1*3+1]; naidd[1*6+4]+=PB[1]*naidp[0][1*3+2]-PC[1]*naidp[1][1*3+2] + zi*tmppp[1*3+2]; naidd[1*6+5]+=PB[2]*naidp[0][1*3+0]-PC[2]*naidp[1][1*3+0]; naidd[2*6+0]+=PB[0]*naidp[0][2*3+0]-PC[0]*naidp[1][2*3+0] + zeta2*tmpds[2]; naidd[2*6+1]+=PB[1]*naidp[0][2*3+1]-PC[1]*naidp[1][2*3+1] + zeta2*tmpds[2]; naidd[2*6+2]+=PB[2]*naidp[0][2*3+2]-PC[2]*naidp[1][2*3+2] + zeta2*tmpds[2]+zi*tmppp[2*3+2]; naidd[2*6+3]+=PB[0]*naidp[0][2*3+1]-PC[0]*naidp[1][2*3+1]; naidd[2*6+4]+=PB[1]*naidp[0][2*3+2]-PC[1]*naidp[1][2*3+2]; naidd[2*6+5]+=PB[2]*naidp[0][2*3+0]-PC[2]*naidp[1][2*3+0] + zi*tmppp[2*3+0]; naidd[3*6+0]+=PB[0]*naidp[0][3*3+0]-PC[0]*naidp[1][3*3+0] + zeta2*tmpds[3]+ zeta2*tmppp[1*3+0]; naidd[3*6+1]+=PB[1]*naidp[0][3*3+1]-PC[1]*naidp[1][3*3+1] + zeta2*tmpds[3]+ zeta2*tmppp[0*3+1]; naidd[3*6+2]+=PB[2]*naidp[0][3*3+2]-PC[2]*naidp[1][3*3+2] + zeta2*tmpds[3]; naidd[3*6+3]+=PB[0]*naidp[0][3*3+1]-PC[0]*naidp[1][3*3+1] + zeta2*tmppp[1*3+1]; naidd[3*6+4]+=PB[1]*naidp[0][3*3+2]-PC[1]*naidp[1][3*3+2] + zeta2*tmppp[0*3+2]; naidd[3*6+5]+=PB[2]*naidp[0][3*3+0]-PC[2]*naidp[1][3*3+0]; naidd[4*6+0]+=PB[0]*naidp[0][4*3+0]-PC[0]*naidp[1][4*3+0] + zeta2*tmpds[4]; naidd[4*6+1]+=PB[1]*naidp[0][4*3+1]-PC[1]*naidp[1][4*3+1] + zeta2*tmpds[4]+ zeta2*tmppp[2*3+1]; naidd[4*6+2]+=PB[2]*naidp[0][4*3+2]-PC[2]*naidp[1][4*3+2] + zeta2*tmpds[4]+ zeta2*tmppp[1*3+2]; naidd[4*6+3]+=PB[0]*naidp[0][4*3+1]-PC[0]*naidp[1][4*3+1]; naidd[4*6+4]+=PB[1]*naidp[0][4*3+2]-PC[1]*naidp[1][4*3+2] + zeta2*tmppp[2*3+2]; naidd[4*6+5]+=PB[2]*naidp[0][4*3+0]-PC[2]*naidp[1][4*3+0] + zeta2*tmppp[1*3+0]; naidd[5*6+0]+=PB[0]*naidp[0][5*3+0]-PC[0]*naidp[1][5*3+0] + zeta2*tmpds[5]+ zeta2*tmppp[2*3+0]; naidd[5*6+1]+=PB[1]*naidp[0][5*3+1]-PC[1]*naidp[1][5*3+1] + zeta2*tmpds[5]; naidd[5*6+2]+=PB[2]*naidp[0][5*3+2]-PC[2]*naidp[1][5*3+2] + zeta2*tmpds[5]+ zeta2*tmppp[0*3+2]; naidd[5*6+3]+=PB[0]*naidp[0][5*3+1]-PC[0]*naidp[1][5*3+1] + zeta2*tmppp[2*3+1]; naidd[5*6+4]+=PB[1]*naidp[0][5*3+2]-PC[1]*naidp[1][5*3+2]; naidd[5*6+5]+=PB[2]*naidp[0][5*3+0]-PC[2]*naidp[1][5*3+0] + zeta2*tmppp[0*3+0]; } // contraction for ( i=0; i<6*6; i++ ) { OVI[i] += ovidd[i]; HCORE[i] += (keidd[i]-naidd[i]); } } // jps } // ips ij = 0; for ( i=0; i<6; i++ ) { coe_a = (i<3? 1.e0 : sqr3 ); for ( j=0; j<6; j++ ) { coe = coe_a * (j<3? 1.e0 : sqr3 ); OVI[ij] *= coe; HCORE[ij] *= coe; ij++; } } }
c-tree.h
/* Definitions for C parsing and type checking. Copyright (C) 1987-2021 Free Software Foundation, Inc. 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/>. */ #ifndef GCC_C_TREE_H #define GCC_C_TREE_H #include "c-family/c-common.h" #include "diagnostic.h" /* struct lang_identifier is private to c-decl.c, but langhooks.c needs to know how big it is. This is sanity-checked in c-decl.c. */ #define C_SIZEOF_STRUCT_LANG_IDENTIFIER \ (sizeof (struct c_common_identifier) + 3 * sizeof (void *)) /* In a RECORD_TYPE or UNION_TYPE, nonzero if any component is read-only. */ #define C_TYPE_FIELDS_READONLY(TYPE) TREE_LANG_FLAG_1 (TYPE) /* In a RECORD_TYPE or UNION_TYPE, nonzero if any component is volatile. */ #define C_TYPE_FIELDS_VOLATILE(TYPE) TREE_LANG_FLAG_2 (TYPE) /* In a RECORD_TYPE or UNION_TYPE or ENUMERAL_TYPE nonzero if the definition of the type has already started. */ #define C_TYPE_BEING_DEFINED(TYPE) TYPE_LANG_FLAG_0 (TYPE) /* In an incomplete RECORD_TYPE, UNION_TYPE or ENUMERAL_TYPE, a list of variable declarations whose type would be completed by completing that type. */ #define C_TYPE_INCOMPLETE_VARS(TYPE) \ TYPE_LANG_SLOT_1 (TREE_CHECK4 (TYPE, RECORD_TYPE, UNION_TYPE, \ QUAL_UNION_TYPE, ENUMERAL_TYPE)) /* In an IDENTIFIER_NODE, nonzero if this identifier is actually a keyword. C_RID_CODE (node) is then the RID_* value of the keyword. */ #define C_IS_RESERVED_WORD(ID) TREE_LANG_FLAG_0 (ID) /* Record whether a type or decl was written with nonconstant size. Note that TYPE_SIZE may have simplified to a constant. */ #define C_TYPE_VARIABLE_SIZE(TYPE) TYPE_LANG_FLAG_1 (TYPE) #define C_DECL_VARIABLE_SIZE(TYPE) DECL_LANG_FLAG_0 (TYPE) /* Record whether a type is defined inside a struct or union type. This is used for -Wc++-compat. */ #define C_TYPE_DEFINED_IN_STRUCT(TYPE) TYPE_LANG_FLAG_2 (TYPE) /* Record whether a typedef for type `int' was actually `signed int'. */ #define C_TYPEDEF_EXPLICITLY_SIGNED(EXP) DECL_LANG_FLAG_1 (EXP) /* For a FUNCTION_DECL, nonzero if it was defined without an explicit return type. */ #define C_FUNCTION_IMPLICIT_INT(EXP) DECL_LANG_FLAG_1 (EXP) /* For a FUNCTION_DECL, nonzero if it was an implicit declaration. */ #define C_DECL_IMPLICIT(EXP) DECL_LANG_FLAG_2 (EXP) /* For a PARM_DECL, nonzero if it was declared as an array. */ #define C_ARRAY_PARAMETER(NODE) DECL_LANG_FLAG_0 (NODE) /* For FUNCTION_DECLs, evaluates true if the decl is built-in but has been declared. */ #define C_DECL_DECLARED_BUILTIN(EXP) \ DECL_LANG_FLAG_3 (FUNCTION_DECL_CHECK (EXP)) /* For FUNCTION_DECLs, evaluates true if the decl is built-in, has a built-in prototype and does not have a non-built-in prototype. */ #define C_DECL_BUILTIN_PROTOTYPE(EXP) \ DECL_LANG_FLAG_6 (FUNCTION_DECL_CHECK (EXP)) /* Record whether a decl was declared register. This is strictly a front-end flag, whereas DECL_REGISTER is used for code generation; they may differ for structures with volatile fields. */ #define C_DECL_REGISTER(EXP) DECL_LANG_FLAG_4 (EXP) /* Record whether a decl was used in an expression anywhere except an unevaluated operand of sizeof / typeof / alignof. This is only used for functions declared static but not defined, though outside sizeof and typeof it is set for other function decls as well. */ #define C_DECL_USED(EXP) DECL_LANG_FLAG_5 (FUNCTION_DECL_CHECK (EXP)) /* Record whether a variable has been declared threadprivate by #pragma omp threadprivate. */ #define C_DECL_THREADPRIVATE_P(DECL) DECL_LANG_FLAG_3 (VAR_DECL_CHECK (DECL)) /* Set on VAR_DECLs for compound literals. */ #define C_DECL_COMPOUND_LITERAL_P(DECL) \ DECL_LANG_FLAG_5 (VAR_DECL_CHECK (DECL)) /* Nonzero for a decl which either doesn't exist or isn't a prototype. N.B. Could be simplified if all built-in decls had complete prototypes (but this is presently difficult because some of them need FILE*). */ #define C_DECL_ISNT_PROTOTYPE(EXP) \ (EXP == 0 \ || (!prototype_p (TREE_TYPE (EXP)) \ && !fndecl_built_in_p (EXP))) /* For FUNCTION_TYPE, a hidden list of types of arguments. The same as TYPE_ARG_TYPES for functions with prototypes, but created for functions without prototypes. */ #define TYPE_ACTUAL_ARG_TYPES(NODE) \ TYPE_LANG_SLOT_1 (FUNCTION_TYPE_CHECK (NODE)) /* For a CONSTRUCTOR, whether some initializer contains a subexpression meaning it is not a constant expression. */ #define CONSTRUCTOR_NON_CONST(EXPR) TREE_LANG_FLAG_1 (CONSTRUCTOR_CHECK (EXPR)) /* For a SAVE_EXPR, nonzero if the operand of the SAVE_EXPR has already been folded. */ #define SAVE_EXPR_FOLDED_P(EXP) TREE_LANG_FLAG_1 (SAVE_EXPR_CHECK (EXP)) /* Record parser information about an expression that is irrelevant for code generation alongside a tree representing its value. */ struct c_expr { /* The value of the expression. */ tree value; /* Record the original unary/binary operator of an expression, which may have been changed by fold, STRING_CST for unparenthesized string constants, C_MAYBE_CONST_EXPR for __builtin_constant_p calls (even if parenthesized), for subexpressions, and for non-constant initializers, or ERROR_MARK for other expressions (including parenthesized expressions). */ enum tree_code original_code; /* If not NULL, the original type of an expression. This will differ from the type of the value field for an enum constant. The type of an enum constant is a plain integer type, but this field will be the enum type. */ tree original_type; /* The source range of this expression. This is redundant for node values that have locations, but not all node kinds have locations (e.g. constants, and references to params, locals, etc), so we stash a copy here. */ source_range src_range; /* Access to the first and last locations within the source spelling of this expression. */ location_t get_start () const { return src_range.m_start; } location_t get_finish () const { return src_range.m_finish; } location_t get_location () const { if (EXPR_HAS_LOCATION (value)) return EXPR_LOCATION (value); else return make_location (get_start (), get_start (), get_finish ()); } /* Set the value to error_mark_node whilst ensuring that src_range is initialized. */ void set_error () { value = error_mark_node; src_range.m_start = UNKNOWN_LOCATION; src_range.m_finish = UNKNOWN_LOCATION; } }; /* Type alias for struct c_expr. This allows to use the structure inside the VEC types. */ typedef struct c_expr c_expr_t; /* A kind of type specifier. Note that this information is currently only used to distinguish tag definitions, tag references and typeof uses. */ enum c_typespec_kind { /* No typespec. This appears only in struct c_declspec. */ ctsk_none, /* A reserved keyword type specifier. */ ctsk_resword, /* A reference to a tag, previously declared, such as "struct foo". This includes where the previous declaration was as a different kind of tag, in which case this is only valid if shadowing that tag in an inner scope. */ ctsk_tagref, /* Likewise, with standard attributes present in the reference. */ ctsk_tagref_attrs, /* A reference to a tag, not previously declared in a visible scope. */ ctsk_tagfirstref, /* Likewise, with standard attributes present in the reference. */ ctsk_tagfirstref_attrs, /* A definition of a tag such as "struct foo { int a; }". */ ctsk_tagdef, /* A typedef name. */ ctsk_typedef, /* An ObjC-specific kind of type specifier. */ ctsk_objc, /* A typeof specifier, or _Atomic ( type-name ). */ ctsk_typeof }; /* A type specifier: this structure is created in the parser and passed to declspecs_add_type only. */ struct c_typespec { /* What kind of type specifier this is. */ enum c_typespec_kind kind; /* Whether the expression has operands suitable for use in constant expressions. */ bool expr_const_operands; /* The specifier itself. */ tree spec; /* An expression to be evaluated before the type specifier, in the case of typeof specifiers, or NULL otherwise or if no such expression is required for a particular typeof specifier. In particular, when typeof is applied to an expression of variably modified type, that expression must be evaluated in order to determine array sizes that form part of the type, but the expression itself (as opposed to the array sizes) forms no part of the type and so needs to be recorded separately. */ tree expr; }; /* A storage class specifier. */ enum c_storage_class { csc_none, csc_auto, csc_extern, csc_register, csc_static, csc_typedef }; /* A type specifier keyword "void", "_Bool", "char", "int", "float", "double", "_Decimal32", "_Decimal64", "_Decimal128", "_Fract", "_Accum", or none of these. */ enum c_typespec_keyword { cts_none, cts_void, cts_bool, cts_char, cts_int, cts_float, cts_int_n, cts_double, cts_dfloat32, cts_dfloat64, cts_dfloat128, cts_floatn_nx, cts_fract, cts_accum, cts_auto_type }; /* This enum lists all the possible declarator specifiers, storage class or attribute that a user can write. There is at least one enumerator per possible declarator specifier in the struct c_declspecs below. It is used to index the array of declspec locations in struct c_declspecs. */ enum c_declspec_word { cdw_typespec /* A catch-all for a typespec. */, cdw_storage_class /* A catch-all for a storage class */, cdw_attributes, cdw_typedef, cdw_explicit_signed, cdw_deprecated, cdw_default_int, cdw_long, cdw_long_long, cdw_short, cdw_signed, cdw_unsigned, cdw_complex, cdw_inline, cdw_noreturn, cdw_thread, cdw_const, cdw_volatile, cdw_restrict, cdw_atomic, cdw_saturating, cdw_alignas, cdw_address_space, cdw_gimple, cdw_rtl, cdw_number_of_elements /* This one must always be the last enumerator. */ }; enum c_declspec_il { cdil_none, cdil_gimple, /* __GIMPLE */ cdil_gimple_cfg, /* __GIMPLE(cfg) */ cdil_gimple_ssa, /* __GIMPLE(ssa) */ cdil_rtl /* __RTL */ }; /* A sequence of declaration specifiers in C. When a new declaration specifier is added, please update the enum c_declspec_word above accordingly. */ struct c_declspecs { location_t locations[cdw_number_of_elements]; /* The type specified, if a single type specifier such as a struct, union or enum specifier, typedef name or typeof specifies the whole type, or NULL_TREE if none or a keyword such as "void" or "char" is used. Does not include qualifiers. */ tree type; /* Any expression to be evaluated before the type, from a typeof specifier. */ tree expr; /* The attributes from a typedef decl. */ tree decl_attr; /* When parsing, the GNU attributes and prefix standard attributes. Outside the parser, this will be NULL; attributes (possibly from multiple lists) will be passed separately. */ tree attrs; /* When parsing, postfix standard attributes (which appertain to the type specified by the preceding declaration specifiers, unlike prefix standard attributes which appertain to the declaration or declarations as a whole). */ tree postfix_attrs; /* The pass to start compiling a __GIMPLE or __RTL function with. */ char *gimple_or_rtl_pass; /* ENTRY BB count. */ profile_count entry_bb_count; /* The base-2 log of the greatest alignment required by an _Alignas specifier, in bytes, or -1 if no such specifiers with nonzero alignment. */ int align_log; /* For the __intN declspec, this stores the index into the int_n_* arrays. */ int int_n_idx; /* For the _FloatN and _FloatNx declspec, this stores the index into the floatn_nx_types array. */ int floatn_nx_idx; /* The storage class specifier, or csc_none if none. */ enum c_storage_class storage_class; /* Any type specifier keyword used such as "int", not reflecting modifiers such as "short", or cts_none if none. */ ENUM_BITFIELD (c_typespec_keyword) typespec_word : 8; /* The kind of type specifier if one has been seen, ctsk_none otherwise. */ ENUM_BITFIELD (c_typespec_kind) typespec_kind : 4; ENUM_BITFIELD (c_declspec_il) declspec_il : 3; /* Whether any expressions in typeof specifiers may appear in constant expressions. */ BOOL_BITFIELD expr_const_operands : 1; /* Whether any declaration specifiers have been seen at all. */ BOOL_BITFIELD declspecs_seen_p : 1; /* Whether any declaration specifiers other than standard attributes have been seen at all. If only standard attributes have been seen, this is an attribute-declaration. */ BOOL_BITFIELD non_std_attrs_seen_p : 1; /* Whether something other than a storage class specifier or attribute has been seen. This is used to warn for the obsolescent usage of storage class specifiers other than at the start of the list. (Doing this properly would require function specifiers to be handled separately from storage class specifiers.) */ BOOL_BITFIELD non_sc_seen_p : 1; /* Whether the type is specified by a typedef or typeof name. */ BOOL_BITFIELD typedef_p : 1; /* Whether the type is explicitly "signed" or specified by a typedef whose type is explicitly "signed". */ BOOL_BITFIELD explicit_signed_p : 1; /* Whether the specifiers include a deprecated typedef. */ BOOL_BITFIELD deprecated_p : 1; /* Whether the type defaulted to "int" because there were no type specifiers. */ BOOL_BITFIELD default_int_p : 1; /* Whether "long" was specified. */ BOOL_BITFIELD long_p : 1; /* Whether "long" was specified more than once. */ BOOL_BITFIELD long_long_p : 1; /* Whether "short" was specified. */ BOOL_BITFIELD short_p : 1; /* Whether "signed" was specified. */ BOOL_BITFIELD signed_p : 1; /* Whether "unsigned" was specified. */ BOOL_BITFIELD unsigned_p : 1; /* Whether "complex" was specified. */ BOOL_BITFIELD complex_p : 1; /* Whether "inline" was specified. */ BOOL_BITFIELD inline_p : 1; /* Whether "_Noreturn" was speciied. */ BOOL_BITFIELD noreturn_p : 1; /* Whether "__thread" or "_Thread_local" was specified. */ BOOL_BITFIELD thread_p : 1; /* Whether "__thread" rather than "_Thread_local" was specified. */ BOOL_BITFIELD thread_gnu_p : 1; /* Whether "const" was specified. */ BOOL_BITFIELD const_p : 1; /* Whether "volatile" was specified. */ BOOL_BITFIELD volatile_p : 1; /* Whether "restrict" was specified. */ BOOL_BITFIELD restrict_p : 1; /* Whether "_Atomic" was specified. */ BOOL_BITFIELD atomic_p : 1; /* Whether "_Sat" was specified. */ BOOL_BITFIELD saturating_p : 1; /* Whether any alignment specifier (even with zero alignment) was specified. */ BOOL_BITFIELD alignas_p : 1; /* The address space that the declaration belongs to. */ addr_space_t address_space; }; /* The various kinds of declarators in C. */ enum c_declarator_kind { /* An identifier. */ cdk_id, /* A function. */ cdk_function, /* An array. */ cdk_array, /* A pointer. */ cdk_pointer, /* Parenthesized declarator with nested attributes. */ cdk_attrs }; struct c_arg_tag { /* The argument name. */ tree id; /* The type of the argument. */ tree type; }; /* Information about the parameters in a function declarator. */ struct c_arg_info { /* A list of parameter decls. */ tree parms; /* A list of structure, union and enum tags defined. */ vec<c_arg_tag, va_gc> *tags; /* A list of argument types to go in the FUNCTION_TYPE. */ tree types; /* A list of non-parameter decls (notably enumeration constants) defined with the parameters. */ tree others; /* A compound expression of VLA sizes from the parameters, or NULL. In a function definition, these are used to ensure that side-effects in sizes of arrays converted to pointers (such as a parameter int i[n++]) take place; otherwise, they are ignored. */ tree pending_sizes; /* True when these arguments had [*]. */ BOOL_BITFIELD had_vla_unspec : 1; }; /* A declarator. */ struct c_declarator { /* The kind of declarator. */ enum c_declarator_kind kind; location_t id_loc; /* Currently only set for cdk_id, cdk_array. */ /* Except for cdk_id, the contained declarator. For cdk_id, NULL. */ struct c_declarator *declarator; union { /* For identifiers. */ struct { /* An IDENTIFIER_NODE, or NULL_TREE if an abstract declarator. */ tree id; /* Any attributes (which apply to the declaration rather than to the type described by the outer declarators). */ tree attrs; } id; /* For functions. */ struct c_arg_info *arg_info; /* For arrays. */ struct { /* The array dimension, or NULL for [] and [*]. */ tree dimen; /* The qualifiers inside []. */ int quals; /* The attributes (currently ignored) inside []. */ tree attrs; /* Whether [static] was used. */ BOOL_BITFIELD static_p : 1; /* Whether [*] was used. */ BOOL_BITFIELD vla_unspec_p : 1; } array; /* For pointers, the qualifiers on the pointer type. */ int pointer_quals; /* For attributes. */ tree attrs; } u; }; /* A type name. */ struct c_type_name { /* The declaration specifiers. */ struct c_declspecs *specs; /* The declarator. */ struct c_declarator *declarator; }; /* A parameter. */ struct c_parm { /* The declaration specifiers, minus any prefix attributes. */ struct c_declspecs *specs; /* The attributes. */ tree attrs; /* The declarator. */ struct c_declarator *declarator; /* The location of the parameter. */ location_t loc; }; /* Used when parsing an enum. Initialized by start_enum. */ struct c_enum_contents { /* While defining an enum type, this is 1 plus the last enumerator constant value. */ tree enum_next_value; /* Nonzero means that there was overflow computing enum_next_value. */ int enum_overflow; }; /* A type of reference to a static identifier in an inline function. */ enum c_inline_static_type { /* Identifier with internal linkage used in function that may be an inline definition (i.e., file-scope static). */ csi_internal, /* Modifiable object with static storage duration defined in function that may be an inline definition (i.e., local static). */ csi_modifiable }; /* in c-parser.c */ extern void c_parse_init (void); extern bool c_keyword_starts_typename (enum rid keyword); /* in c-aux-info.c */ extern void gen_aux_info_record (tree, int, int, int); /* in c-decl.c */ struct c_spot_bindings; class c_struct_parse_info; extern struct obstack parser_obstack; /* Set to IN_ITERATION_STMT if parsing an iteration-statement, to IN_OMP_BLOCK if parsing OpenMP structured block and IN_OMP_FOR if parsing OpenMP loop. If parsing a switch statement, this is bitwise ORed with IN_SWITCH_STMT, unless parsing an iteration-statement, OpenMP block or loop within that switch. */ #define IN_SWITCH_STMT 1 #define IN_ITERATION_STMT 2 #define IN_OMP_BLOCK 4 #define IN_OMP_FOR 8 #define IN_OBJC_FOREACH 16 extern unsigned char in_statement; extern bool switch_statement_break_seen_p; extern bool global_bindings_p (void); extern tree pushdecl (tree); extern void push_scope (void); extern tree pop_scope (void); extern void c_bindings_start_stmt_expr (struct c_spot_bindings *); extern void c_bindings_end_stmt_expr (struct c_spot_bindings *); extern void record_inline_static (location_t, tree, tree, enum c_inline_static_type); extern void c_init_decl_processing (void); extern void c_print_identifier (FILE *, tree, int); extern int quals_from_declspecs (const struct c_declspecs *); extern struct c_declarator *build_array_declarator (location_t, tree, struct c_declspecs *, bool, bool); extern tree build_enumerator (location_t, location_t, struct c_enum_contents *, tree, tree); extern tree check_for_loop_decls (location_t, bool); extern void mark_forward_parm_decls (void); extern void declare_parm_level (void); extern void undeclared_variable (location_t, tree); extern tree lookup_label_for_goto (location_t, tree); extern tree declare_label (tree); extern tree define_label (location_t, tree); extern struct c_spot_bindings *c_get_switch_bindings (void); extern void c_release_switch_bindings (struct c_spot_bindings *); extern bool c_check_switch_jump_warnings (struct c_spot_bindings *, location_t, location_t); extern void finish_decl (tree, location_t, tree, tree, tree); extern tree finish_enum (tree, tree, tree); extern void finish_function (location_t = input_location); extern tree finish_struct (location_t, tree, tree, tree, class c_struct_parse_info *); extern tree c_simulate_enum_decl (location_t, const char *, vec<string_int_pair>); extern struct c_arg_info *build_arg_info (void); extern struct c_arg_info *get_parm_info (bool, tree); extern tree grokfield (location_t, struct c_declarator *, struct c_declspecs *, tree, tree *); extern tree groktypename (struct c_type_name *, tree *, bool *); extern tree grokparm (const struct c_parm *, tree *); extern tree implicitly_declare (location_t, tree); extern void keep_next_level (void); extern void pending_xref_error (void); extern void c_push_function_context (void); extern void c_pop_function_context (void); extern void push_parm_decl (const struct c_parm *, tree *); extern struct c_declarator *set_array_declarator_inner (struct c_declarator *, struct c_declarator *); extern tree c_builtin_function (tree); extern tree c_builtin_function_ext_scope (tree); extern tree c_simulate_builtin_function_decl (tree); extern void c_warn_unused_attributes (tree); extern tree c_warn_type_attributes (tree); extern void shadow_tag (const struct c_declspecs *); extern void shadow_tag_warned (const struct c_declspecs *, int); extern tree start_enum (location_t, struct c_enum_contents *, tree); extern bool start_function (struct c_declspecs *, struct c_declarator *, tree); extern tree start_decl (struct c_declarator *, struct c_declspecs *, bool, tree, location_t * = NULL); extern tree start_struct (location_t, enum tree_code, tree, class c_struct_parse_info **); extern void store_parm_decls (void); extern void store_parm_decls_from (struct c_arg_info *); extern void temp_store_parm_decls (tree, tree); extern void temp_pop_parm_decls (void); extern tree xref_tag (enum tree_code, tree); extern struct c_typespec parser_xref_tag (location_t, enum tree_code, tree, bool, tree); extern struct c_parm *build_c_parm (struct c_declspecs *, tree, struct c_declarator *, location_t); extern struct c_declarator *build_attrs_declarator (tree, struct c_declarator *); extern struct c_declarator *build_function_declarator (struct c_arg_info *, struct c_declarator *); extern struct c_declarator *build_id_declarator (tree); extern struct c_declarator *make_pointer_declarator (struct c_declspecs *, struct c_declarator *); extern struct c_declspecs *build_null_declspecs (void); extern struct c_declspecs *declspecs_add_qual (location_t, struct c_declspecs *, tree); extern struct c_declspecs *declspecs_add_type (location_t, struct c_declspecs *, struct c_typespec); extern struct c_declspecs *declspecs_add_scspec (location_t, struct c_declspecs *, tree); extern struct c_declspecs *declspecs_add_attrs (location_t, struct c_declspecs *, tree); extern struct c_declspecs *declspecs_add_addrspace (location_t, struct c_declspecs *, addr_space_t); extern struct c_declspecs *declspecs_add_alignas (location_t, struct c_declspecs *, tree); extern struct c_declspecs *finish_declspecs (struct c_declspecs *); /* in c-objc-common.c */ extern bool c_objc_common_init (void); extern bool c_missing_noreturn_ok_p (tree); extern bool c_warn_unused_global_decl (const_tree); extern void c_initialize_diagnostics (diagnostic_context *); extern bool c_vla_unspec_p (tree x, tree fn); extern alias_set_type c_get_alias_set (tree); /* in c-typeck.c */ extern int in_alignof; extern int in_sizeof; extern int in_typeof; extern bool c_in_omp_for; extern tree c_last_sizeof_arg; extern location_t c_last_sizeof_loc; extern struct c_switch *c_switch_stack; extern bool char_type_p (tree); extern tree c_objc_common_truthvalue_conversion (location_t, tree); extern tree require_complete_type (location_t, tree); extern bool same_translation_unit_p (const_tree, const_tree); extern int comptypes (tree, tree); extern int comptypes_check_different_types (tree, tree, bool *); extern bool c_vla_type_p (const_tree); extern bool c_mark_addressable (tree, bool = false); extern void c_incomplete_type_error (location_t, const_tree, const_tree); extern tree c_type_promotes_to (tree); extern struct c_expr default_function_array_conversion (location_t, struct c_expr); extern struct c_expr default_function_array_read_conversion (location_t, struct c_expr); extern struct c_expr convert_lvalue_to_rvalue (location_t, struct c_expr, bool, bool); extern tree decl_constant_value_1 (tree, bool); extern void mark_exp_read (tree); extern tree composite_type (tree, tree); extern tree build_component_ref (location_t, tree, tree, location_t); extern tree build_array_ref (location_t, tree, tree); extern tree build_external_ref (location_t, tree, bool, tree *); extern void pop_maybe_used (bool); extern struct c_expr c_expr_sizeof_expr (location_t, struct c_expr); extern struct c_expr c_expr_sizeof_type (location_t, struct c_type_name *); extern struct c_expr parser_build_unary_op (location_t, enum tree_code, struct c_expr); extern struct c_expr parser_build_binary_op (location_t, enum tree_code, struct c_expr, struct c_expr); extern tree build_conditional_expr (location_t, tree, bool, tree, tree, location_t, tree, tree, location_t); extern tree build_compound_expr (location_t, tree, tree); extern tree c_cast_expr (location_t, struct c_type_name *, tree); extern tree build_c_cast (location_t, tree, tree); extern void store_init_value (location_t, tree, tree, tree); extern void maybe_warn_string_init (location_t, tree, struct c_expr); extern void start_init (tree, tree, int, rich_location *); extern void finish_init (void); extern void really_start_incremental_init (tree); extern void finish_implicit_inits (location_t, struct obstack *); extern void push_init_level (location_t, int, struct obstack *); extern struct c_expr pop_init_level (location_t, int, struct obstack *, location_t); extern void set_init_index (location_t, tree, tree, struct obstack *); extern void set_init_label (location_t, tree, location_t, struct obstack *); extern void process_init_element (location_t, struct c_expr, bool, struct obstack *); extern tree build_compound_literal (location_t, tree, tree, bool, unsigned int); extern void check_compound_literal_type (location_t, struct c_type_name *); extern tree c_start_switch (location_t, location_t, tree, bool); extern void c_finish_switch (tree, tree); extern tree build_asm_expr (location_t, tree, tree, tree, tree, tree, bool, bool); extern tree build_asm_stmt (bool, tree); extern int c_types_compatible_p (tree, tree); extern tree c_begin_compound_stmt (bool); extern tree c_end_compound_stmt (location_t, tree, bool); extern void c_finish_if_stmt (location_t, tree, tree, tree); extern void c_finish_loop (location_t, location_t, tree, location_t, tree, tree, tree, tree, bool); extern tree c_begin_stmt_expr (void); extern tree c_finish_stmt_expr (location_t, tree); extern tree c_process_expr_stmt (location_t, tree); extern tree c_finish_expr_stmt (location_t, tree); extern tree c_finish_return (location_t, tree, tree); extern tree c_finish_bc_stmt (location_t, tree, bool); extern tree c_finish_goto_label (location_t, tree); extern tree c_finish_goto_ptr (location_t, tree); extern tree c_expr_to_decl (tree, bool *, bool *); extern tree c_finish_omp_construct (location_t, enum tree_code, tree, tree); extern tree c_finish_oacc_data (location_t, tree, tree); extern tree c_finish_oacc_host_data (location_t, tree, tree); extern tree c_begin_omp_parallel (void); extern tree c_finish_omp_parallel (location_t, tree, tree); extern tree c_begin_omp_task (void); extern tree c_finish_omp_task (location_t, tree, tree); extern void c_finish_omp_cancel (location_t, tree); extern void c_finish_omp_cancellation_point (location_t, tree); extern tree c_finish_omp_clauses (tree, enum c_omp_region_type); extern tree c_build_va_arg (location_t, tree, location_t, tree); extern tree c_finish_transaction (location_t, tree, int); extern bool c_tree_equal (tree, tree); extern tree c_build_function_call_vec (location_t, vec<location_t>, tree, vec<tree, va_gc> *, vec<tree, va_gc> *); extern tree c_omp_clause_copy_ctor (tree, tree, tree); /* Set to 0 at beginning of a function definition, set to 1 if a return statement that specifies a return value is seen. */ extern int current_function_returns_value; /* Set to 0 at beginning of a function definition, set to 1 if a return statement with no argument is seen. */ extern int current_function_returns_null; /* Set to 0 at beginning of a function definition, set to 1 if a call to a noreturn function is seen. */ extern int current_function_returns_abnormally; /* In c-decl.c */ /* Tell the binding oracle what kind of binding we are looking for. */ enum c_oracle_request { C_ORACLE_SYMBOL, C_ORACLE_TAG, C_ORACLE_LABEL }; /* If this is non-NULL, then it is a "binding oracle" which can lazily create bindings when needed by the C compiler. The oracle is told the name and type of the binding to create. It can call pushdecl or the like to ensure the binding is visible; or do nothing, leaving the binding untouched. c-decl.c takes note of when the oracle has been called and will not call it again if it fails to create a given binding. */ typedef void c_binding_oracle_function (enum c_oracle_request, tree identifier); extern c_binding_oracle_function *c_binding_oracle; extern void c_finish_incomplete_decl (tree); extern tree c_omp_reduction_id (enum tree_code, tree); extern tree c_omp_reduction_decl (tree); extern tree c_omp_reduction_lookup (tree, tree); extern tree c_check_omp_declare_reduction_r (tree *, int *, void *); extern bool c_check_in_current_scope (tree); extern void c_pushtag (location_t, tree, tree); extern void c_bind (location_t, tree, bool); extern bool tag_exists_p (enum tree_code, tree); /* In c-errors.c */ extern bool pedwarn_c90 (location_t, int opt, const char *, ...) ATTRIBUTE_GCC_DIAG(3,4); extern bool pedwarn_c99 (location_t, int opt, const char *, ...) ATTRIBUTE_GCC_DIAG(3,4); extern bool pedwarn_c11 (location_t, int opt, const char *, ...) ATTRIBUTE_GCC_DIAG(3,4); extern void set_c_expr_source_range (c_expr *expr, location_t start, location_t finish); extern void set_c_expr_source_range (c_expr *expr, source_range src_range); /* In c-fold.c */ extern vec<tree> incomplete_record_decls; #if CHECKING_P namespace selftest { extern void run_c_tests (void); } // namespace selftest #endif /* #if CHECKING_P */ #endif /* ! GCC_C_TREE_H */
cv_basic.h
// Copyright (c) 2019 PaddlePaddle 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. #pragma once <<<<<<< HEAD #include "lite/utils/cv/cv_enum.h" typedef paddle::lite::utils::cv::ImageFormat ImageFormat; typedef paddle::lite::utils::cv::FlipParam FlipParam; typedef paddle::lite::utils::cv::LayOut LayOut; typedef paddle::lite::Tensor Tensor; ======= #include "lite/utils/cv/paddle_image_preprocess.h" typedef paddle::lite::utils::cv::ImageFormat ImageFormat; typedef paddle::lite::utils::cv::FlipParam FlipParam; typedef paddle::lite::Tensor Tensor; typedef paddle::lite_api::DataLayoutType LayoutType; >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf void nv2bgr(const uint8_t* in_data, uint8_t* out_data, int srcw, int srch, int v_num, int u_num) { int size = srch * srcw; const uint8_t* y_ptr = in_data; const uint8_t* uv_ptr = in_data + size; for (int i = 0; i < srch; i++) { int j = 0; const uint8_t* ptr_y1 = y_ptr + i * srcw; const uint8_t* ptr_vu = uv_ptr + (i / 2) * srcw; uint8_t* ptr_bgr1 = out_data + i * 3 * srcw; for (; j < srcw; j += 2) { uint8_t _y0 = ptr_y1[0]; uint8_t _y1 = ptr_y1[1]; uint8_t _v = ptr_vu[v_num]; uint8_t _u = ptr_vu[u_num]; int ra = floor((179 * (_v - 128)) >> 7); int ga = floor((44 * (_u - 128) + 91 * (_v - 128)) >> 7); int ba = floor((227 * (_u - 128)) >> 7); int r = _y0 + ra; int g = _y0 - ga; int b = _y0 + ba; int r1 = _y1 + ra; int g1 = _y1 - ga; int b1 = _y1 + ba; r = r < 0 ? 0 : (r > 255) ? 255 : r; g = g < 0 ? 0 : (g > 255) ? 255 : g; b = b < 0 ? 0 : (b > 255) ? 255 : b; r1 = r1 < 0 ? 0 : (r1 > 255) ? 255 : r1; g1 = g1 < 0 ? 0 : (g1 > 255) ? 255 : g1; b1 = b1 < 0 ? 0 : (b1 > 255) ? 255 : b1; *ptr_bgr1++ = b; *ptr_bgr1++ = g; *ptr_bgr1++ = r; *ptr_bgr1++ = b1; *ptr_bgr1++ = g1; *ptr_bgr1++ = r1; ptr_y1 += 2; ptr_vu += 2; } if (j < srcw) { uint8_t _y = ptr_y1[0]; uint8_t _v = ptr_vu[v_num]; uint8_t _u = ptr_vu[u_num]; int r = _y + ((179 * (_v - 128)) >> 7); int g = _y - ((44 * (_u - 128) - 91 * (_v - 128)) >> 7); int b = _y + ((227 * (_u - 128)) >> 7); r = r < 0 ? 0 : (r > 255) ? 255 : r; g = g < 0 ? 0 : (g > 255) ? 255 : g; b = b < 0 ? 0 : (b > 255) ? 255 : b; ptr_bgr1[0] = b; ptr_bgr1[1] = g; ptr_bgr1[2] = r; } } } void nv2bgra(const uint8_t* in_data, uint8_t* out_data, int srcw, int srch, int v_num, int u_num) { int size = srch * srcw; const uint8_t* y_ptr = in_data; const uint8_t* uv_ptr = in_data + size; for (int i = 0; i < srch; i++) { int j = 0; const uint8_t* ptr_y1 = y_ptr + i * srcw; const uint8_t* ptr_vu = uv_ptr + (i / 2) * srcw; uint8_t* ptr_bgr1 = out_data + i * 4 * srcw; for (; j < srcw; j += 2) { uint8_t _y0 = ptr_y1[0]; uint8_t _y1 = ptr_y1[1]; uint8_t _v = ptr_vu[v_num]; uint8_t _u = ptr_vu[u_num]; int ra = floor((179 * (_v - 128)) >> 7); int ga = floor((44 * (_u - 128) + 91 * (_v - 128)) >> 7); int ba = floor((227 * (_u - 128)) >> 7); int r = _y0 + ra; int g = _y0 - ga; int b = _y0 + ba; int r1 = _y1 + ra; int g1 = _y1 - ga; int b1 = _y1 + ba; r = r < 0 ? 0 : (r > 255) ? 255 : r; g = g < 0 ? 0 : (g > 255) ? 255 : g; b = b < 0 ? 0 : (b > 255) ? 255 : b; r1 = r1 < 0 ? 0 : (r1 > 255) ? 255 : r1; g1 = g1 < 0 ? 0 : (g1 > 255) ? 255 : g1; b1 = b1 < 0 ? 0 : (b1 > 255) ? 255 : b1; *ptr_bgr1++ = b; *ptr_bgr1++ = g; *ptr_bgr1++ = r; *ptr_bgr1++ = 255; *ptr_bgr1++ = b1; *ptr_bgr1++ = g1; *ptr_bgr1++ = r1; *ptr_bgr1++ = 255; ptr_y1 += 2; ptr_vu += 2; } if (j < srcw) { uint8_t _y = ptr_y1[0]; uint8_t _v = ptr_vu[v_num]; uint8_t _u = ptr_vu[u_num]; int r = _y + ((179 * (_v - 128)) >> 7); int g = _y - ((44 * (_u - 128) - 91 * (_v - 128)) >> 7); int b = _y + ((227 * (_u - 128)) >> 7); r = r < 0 ? 0 : (r > 255) ? 255 : r; g = g < 0 ? 0 : (g > 255) ? 255 : g; b = b < 0 ? 0 : (b > 255) ? 255 : b; ptr_bgr1[0] = b; ptr_bgr1[1] = g; ptr_bgr1[2] = r; ptr_bgr1[3] = 255; } } } void nv12_bgr_basic(const uint8_t* in_data, uint8_t* out_data, int srcw, int srch) { nv2bgr(in_data, out_data, srcw, srch, 1, 0); } void nv21_bgr_basic(const uint8_t* in_data, uint8_t* out_data, int srcw, int srch) { nv2bgr(in_data, out_data, srcw, srch, 0, 1); } void nv12_bgra_basic(const uint8_t* in_data, uint8_t* out_data, int srcw, int srch) { nv2bgra(in_data, out_data, srcw, srch, 1, 0); } void nv21_bgra_basic(const uint8_t* in_data, uint8_t* out_data, int srcw, int srch) { nv2bgra(in_data, out_data, srcw, srch, 0, 1); } /* <<<<<<< HEAD /* ======= >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf 采用CV_BGR2GRAY,转换公式Gray = 0.1140*B + 0.5870*G + 0.2989*R 采用CV_RGB2GRAY,转换公式Gray = 0.1140*R + 0.5870*G + 0.2989*B b = 0.114 *128 = 14.529 = 15 g = 0.587 * 128 = 75.136 = 75 r = 0.2989 * 128 = 38.2592 = 38 Gray = (15*B + 75*G + 38*R)/128 bgr2gray, rgb2gray */ void bgr_gray_basic(const uint8_t* in_data, uint8_t* out_data, int srcw, int srch) { for (int i = 0; i < srch; i++) { const uint8_t* din_ptr = in_data + i * 3 * srcw; uint8_t* dout_ptr = out_data + i * srcw; for (int j = 0; j < srcw; j++) { int sum = din_ptr[0] * 15 + din_ptr[1] * 75 + din_ptr[2] * 38; sum = sum >> 7; *dout_ptr++ = sum; din_ptr += 3; } } } <<<<<<< HEAD ======= void bgra_gray_basic(const uint8_t* in_data, uint8_t* out_data, int srcw, int srch) { for (int i = 0; i < srch; i++) { const uint8_t* din_ptr = in_data + i * 4 * srcw; uint8_t* dout_ptr = out_data + i * srcw; for (int j = 0; j < srcw; j++) { int sum = din_ptr[0] * 15 + din_ptr[1] * 75 + din_ptr[2] * 38; sum = sum >> 7; *dout_ptr++ = sum; din_ptr += 4; } } } >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf void gray_bgr_basic(const uint8_t* src, uint8_t* dst, int srcw, int srch) { for (int i = 0; i < srch; i++) { for (int j = 0; j < srcw; j++) { *dst++ = *src; *dst++ = *src; *dst++ = *src; src++; } } } <<<<<<< HEAD ======= void gray_bgra_basic(const uint8_t* src, uint8_t* dst, int srcw, int srch) { for (int i = 0; i < srch; i++) { for (int j = 0; j < srcw; j++) { *dst++ = *src; *dst++ = *src; *dst++ = *src; *dst++ = 255; src++; } } } >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf // bgr2bgra, rgb2rgba void hwc3_to_hwc4_basic(const uint8_t* src, uint8_t* dst, int srcw, int srch) { for (int i = 0; i < srch; i++) { for (int j = 0; j < srcw; j++) { *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = 255; } } } // bgra2bgr, rgba2rgb void hwc4_to_hwc3_basic(const uint8_t* src, uint8_t* dst, int srcw, int srch) { for (int i = 0; i < srch; i++) { for (int j = 0; j < srcw; j++) { *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; src++; } } } // bgr2rgb, rgb2bgr void hwc3_trans_basic(const uint8_t* src, uint8_t* dst, int srcw, int srch) { for (int i = 0; i < srch; i++) { for (int j = 0; j < srcw; j++) { *dst++ = src[2]; // r *dst++ = src[1]; // g *dst++ = src[0]; // b src += 3; } } } // bgra2rgba, rgba2bgra void hwc4_trans_basic(const uint8_t* src, uint8_t* dst, int srcw, int srch) { for (int i = 0; i < srch; i++) { for (int j = 0; j < srcw; j++) { *dst++ = src[2]; // r *dst++ = src[1]; // g *dst++ = src[0]; // b *dst++ = src[3]; // a src += 4; } } } // bgra2rgb, rgba2bgr void hwc4_trans_hwc3_basic(const uint8_t* src, uint8_t* dst, int srcw, int srch) { for (int i = 0; i < srch; i++) { for (int j = 0; j < srcw; j++) { *dst++ = src[2]; // r *dst++ = src[1]; // g *dst++ = src[0]; // b // *dst++ = src[4];//a src += 4; } } } // bgr2rgba, rgb2bga void hwc3_trans_hwc4_basic(const uint8_t* src, uint8_t* dst, int srcw, int srch) { for (int i = 0; i < srch; i++) { for (int j = 0; j < srcw; j++) { *dst++ = src[2]; // r *dst++ = src[1]; // g *dst++ = src[0]; // b *dst++ = 255; // a src += 3; } } } void image_convert_basic(const uint8_t* in_data, uint8_t* out_data, ImageFormat srcFormat, ImageFormat dstFormat, int srcw, int srch, int out_size) { if (srcFormat == dstFormat) { // copy memcpy(out_data, in_data, sizeof(uint8_t) * out_size); return; } else { if (srcFormat == ImageFormat::NV12 && (dstFormat == ImageFormat::BGR || dstFormat == ImageFormat::RGB)) { nv12_bgr_basic(in_data, out_data, srcw, srch); } else if (srcFormat == ImageFormat::NV21 && (dstFormat == ImageFormat::BGR || dstFormat == ImageFormat::RGB)) { nv21_bgr_basic(in_data, out_data, srcw, srch); } else if (srcFormat == ImageFormat::NV12 && (dstFormat == ImageFormat::BGRA || dstFormat == ImageFormat::RGBA)) { nv12_bgra_basic(in_data, out_data, srcw, srch); } else if (srcFormat == ImageFormat::NV21 && (dstFormat == ImageFormat::BGRA || dstFormat == ImageFormat::RGBA)) { nv21_bgra_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::RGB && dstFormat == ImageFormat::GRAY) || (srcFormat == ImageFormat::BGR && dstFormat == ImageFormat::GRAY)) { bgr_gray_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::GRAY && dstFormat == ImageFormat::RGB) || (srcFormat == ImageFormat::GRAY && dstFormat == ImageFormat::BGR)) { gray_bgr_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::RGBA && <<<<<<< HEAD ======= dstFormat == ImageFormat::GRAY) || (srcFormat == ImageFormat::BGRA && dstFormat == ImageFormat::GRAY)) { bgra_gray_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::GRAY && dstFormat == ImageFormat::RGBA) || (srcFormat == ImageFormat::GRAY && dstFormat == ImageFormat::BGRA)) { gray_bgra_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::RGBA && >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf dstFormat == ImageFormat::RGB) || (srcFormat == ImageFormat::BGRA && dstFormat == ImageFormat::BGR)) { hwc4_to_hwc3_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::RGB && dstFormat == ImageFormat::RGBA) || (srcFormat == ImageFormat::BGR && dstFormat == ImageFormat::BGRA)) { hwc3_to_hwc4_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::RGB && dstFormat == ImageFormat::BGR) || (srcFormat == ImageFormat::BGR && dstFormat == ImageFormat::RGB)) { hwc3_trans_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::RGBA && dstFormat == ImageFormat::BGRA) || (srcFormat == ImageFormat::BGRA && dstFormat == ImageFormat::RGBA)) { hwc4_trans_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::RGBA && dstFormat == ImageFormat::BGR) || (srcFormat == ImageFormat::BGRA && dstFormat == ImageFormat::RGB)) { hwc4_trans_hwc3_basic(in_data, out_data, srcw, srch); } else if ((srcFormat == ImageFormat::RGB && dstFormat == ImageFormat::BGRA) || (srcFormat == ImageFormat::BGR && dstFormat == ImageFormat::RGBA)) { hwc3_trans_hwc4_basic(in_data, out_data, srcw, srch); } else { printf("srcFormat: %d, dstFormat: %d does not support! \n", srcFormat, dstFormat); } // for (int i = 0; i < out_size; i++){ // printf("%d ", *out_data++); // if ((i+1) % 10 == 0){ // printf("\n"); // } // } } } void compute_xy(int srcw, int srch, int dstw, int dsth, double scale_x, double scale_y, int* xofs, int* yofs, float* ialpha, float* ibeta) { float fy = 0.f; float fx = 0.f; int sy = 0; int sx = 0; const int resize_coef_bits = 11; const int resize_coef_scale = 1 << resize_coef_bits; for (int dx = 0; dx < dstw; dx++) { fx = static_cast<float>((dx + 0.5) * scale_x - 0.5); sx = floor(fx); fx -= sx; if (sx < 0) { sx = 0; fx = 0.f; } if (sx >= srcw - 1) { sx = srcw - 2; fx = 1.f; } xofs[dx] = sx; float a0 = (1.f - fx); float a1 = fx; ialpha[dx * 2] = a0; ialpha[dx * 2 + 1] = a1; } for (int dy = 0; dy < dsth; dy++) { fy = static_cast<float>((dy + 0.5) * scale_y - 0.5); sy = floor(fy); fy -= sy; if (sy < 0) { sy = 0; fy = 0.f; } if (sy >= srch - 1) { sy = srch - 2; fy = 1.f; } yofs[dy] = sy; float b0 = (1.f - fy); float b1 = fy; ibeta[dy * 2] = b0; ibeta[dy * 2 + 1] = b1; } } void image_resize_basic(const uint8_t* in_data, uint8_t* out_data, ImageFormat srcFormat, int srcw, int srch, int dstw, int dsth) { int size = srcw * srch; if (srcw == dstw && srch == dsth) { if (srcFormat == ImageFormat::NV12 || srcFormat == ImageFormat::NV21) { <<<<<<< HEAD size = srcw * (ceil(1.5 * srch)); ======= size = srcw * (static_cast<int>(1.5 * srch)); >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf } else if (srcFormat == ImageFormat::BGR || srcFormat == ImageFormat::RGB) { size = 3 * srcw * srch; } else if (srcFormat == ImageFormat::BGRA || srcFormat == ImageFormat::RGBA) { size = 4 * srcw * srch; } memcpy(out_data, in_data, sizeof(uint8_t) * size); return; } <<<<<<< HEAD double scale_x = static_cast<double>(srcw / dstw); double scale_y = static_cast<double>(srch / dsth); ======= double scale_x = static_cast<double>(srcw) / dstw; double scale_y = static_cast<double>(srch) / dsth; >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf int* buf = new int[dstw + dsth]; int* xofs = buf; int* yofs = buf + dstw; float* ialpha = new float[dstw * 2]; <<<<<<< HEAD float* ibeta = new float[dsth * 2]; ======= float* ibeta = new float[dsth * 3]; >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf int w_in = srcw; int w_out = dstw; int num = 1; int orih = dsth; <<<<<<< HEAD compute_xy( srcw, srch, dstw, dsth, scale_x, scale_y, xofs, yofs, ialpha, ibeta); ======= compute_xy( srcw, srch, dstw, dsth, scale_x, scale_y, xofs, yofs, ialpha, ibeta); >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf if (srcFormat == ImageFormat::GRAY) { num = 1; } else if (srcFormat == ImageFormat::NV12 || srcFormat == ImageFormat::NV21) { int hout = static_cast<int>(0.5 * dsth); // uv todo w_out = dstw; num = 1; dsth += hout; } else if (srcFormat == ImageFormat::BGR || srcFormat == ImageFormat::RGB) { w_in = srcw * 3; w_out = dstw * 3; num = 3; } else if (srcFormat == ImageFormat::BGRA || srcFormat == ImageFormat::RGBA) { w_in = srcw * 4; w_out = dstw * 4; num = 4; } float* ialpha1 = nullptr; int* xofs1 = nullptr; int* yofs1 = nullptr; if (orih < dsth) { int tmp = dsth - orih; <<<<<<< HEAD float* ialpha1 = new float[dstw]; int* xofs1 = new int[srcw]; int* yofs1 = new int[tmp]; compute_xy(srcw / 2, ======= ialpha1 = new float[dstw]; xofs1 = new int[dstw]; yofs1 = new int[tmp]; compute_xy(srcw, >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf srch / 2, dstw / 2, tmp, scale_x, scale_y, xofs1, yofs1, ialpha1, <<<<<<< HEAD ibeta + dsth); ======= ibeta + orih * 2); >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf } #pragma omp parallel for for (int dy = 0; dy < dsth; dy++) { uint8_t* out_ptr = out_data + dy * w_out; int y_in_start = yofs[dy]; <<<<<<< HEAD int y_in_end = y_in_start + 1; int y_flag = 0; // only one line if (y_in_start < 0) { y_flag = 1; } ======= int y_flag = 0; >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf float b0 = ibeta[dy * 2]; float b1 = ibeta[dy * 2 + 1]; if (dy >= orih) { num = 2; // uv ialpha = ialpha1; xofs = xofs1; yofs = yofs1; <<<<<<< HEAD ======= y_in_start = yofs[dy - orih] + srch; } int y_in_end = y_in_start + 1; if (y_in_start < 0) { y_flag = 1; y_in_end = 0; >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf } for (int dx = 0; dx < w_out; dx += num) { int tmp = dx / num; int x_in_start = xofs[tmp] * num; // 0 int x_in_end = x_in_start + num; // 2 int x_flag = 0; if (x_in_start < 0) { x_flag = 1; x_in_end = 0; } <<<<<<< HEAD // printf("x_in: %d, y_in: %d \n", x_in_start, y_in_start); ======= >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf float a0 = ialpha[tmp * 2]; float a1 = ialpha[tmp * 2 + 1]; int tl_index = y_in_start * w_in + x_in_start; // 0 int tr_index = y_in_start * w_in + x_in_end; // 2 int bl_index = y_in_end * w_in + x_in_start; int br_index = y_in_end * w_in + x_in_end; int ind = dx; for (int i = 0; i < num; i++) { int tl = in_data[tl_index]; int tr = in_data[tr_index]; int bl = in_data[bl_index]; int br = in_data[br_index]; if (y_flag == 1) { tl = 0; tr = 0; } if (x_flag == 1) { tl = 0; bl = 0; } tl_index++; tr_index++; bl_index++; br_index++; float outval = (tl * a0 + tr * a1) * b0 + (bl * a0 + br * a1) * b1; <<<<<<< HEAD // printf("tl: %d, tr: %d, bl: %d, br: %d \n", tl, tr, bl, br); // printf("br_index: %d, a0: %f, b1: %f, out: %f \n", br_index, a0, b1, // outval); ======= >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf out_ptr[ind++] = ceil(outval); } } } } void rotate90_basic(const uint8_t* in_data, int h_in, int w_in, uint8_t* out_data, int h_out, int w_out, int num) { int win = w_in * num; int wout = w_out * num; for (int x = 0; x < h_in; x++) { for (int y = 0; y < w_in; y++) { int tmpy = y * num; int tmpx = (w_out - 1 - x) * num; // x for (int i = 0; i < num; i++) { out_data[y * wout + tmpx] = in_data[x * win + tmpy]; tmpx++; tmpy++; } } } } void rotate180_basic(const uint8_t* in_data, int h_in, int w_in, uint8_t* out_data, int h_out, int w_out, int num) { int win = w_in * num; int h = h_in - 1; int w = win - 1; for (int x = 0; x < h_in; x++) { for (int y = 0; y < w_in; y++) { int tmpy = y * num; int tmp = tmpy + (num - 1); for (int i = 0; i < num; i++) { out_data[(h - x) * win + w - tmp] = in_data[x * win + tmpy]; tmpy++; tmp--; } } } } void rotate270_basic(const uint8_t* in_data, int h_in, int w_in, uint8_t* out_data, int h_out, int w_out, int num) { int win = w_in * num; int wout = w_out * num; int h = h_out - 1; for (int x = 0; x < h_in; x++) { for (int y = 0; y < w_in; y++) { int tmpy = y * num; int tmpx = x * num; for (int i = 0; i < num; i++) { out_data[(h - y) * wout + tmpx] = in_data[x * win + tmpy]; // (y,x) = in(x,y) tmpx++; tmpy++; } } } } void image_rotate_basic(const uint8_t* in_data, uint8_t* out_data, ImageFormat srcFormat, int srcw, int srch, float rotate) { int num = 1; if (srcFormat == ImageFormat::GRAY) { num = 1; } else if (srcFormat == ImageFormat::NV12 || srcFormat == ImageFormat::NV21) { num = 1; // todo return; } else if (srcFormat == ImageFormat::BGR || srcFormat == ImageFormat::RGB) { num = 3; } else if (srcFormat == ImageFormat::BGRA || srcFormat == ImageFormat::RGBA) { num = 4; } if (rotate == 90) { rotate90_basic(in_data, srch, srcw, out_data, srcw, srch, num); } else if (rotate == 180) { rotate180_basic(in_data, srch, srcw, out_data, srch, srcw, num); } else if (rotate == 270) { rotate270_basic(in_data, srch, srcw, out_data, srcw, srch, num); } } void flipx_basic( const uint8_t* in_data, int h_in, int w_in, uint8_t* out_data, int num) { int h = h_in - 1; int w = w_in * num; for (int x = 0; x < h_in; x++) { for (int y = 0; y < w_in; y++) { int tmpy = y * num; for (int i = 0; i < num; i++) { out_data[(h - x) * w + tmpy] = in_data[x * w + tmpy]; // (y,x) = in(x,y) tmpy++; } } } } void flipy_basic( const uint8_t* in_data, int h_in, int w_in, uint8_t* out_data, int num) { int w = w_in * num - 1; for (int x = 0; x < h_in; x++) { for (int y = 0; y < w_in; y++) { int tmpy = y * num; int tmp = tmpy + (num - 1); for (int i = 0; i < num; i++) { out_data[x * w_in * num + w - tmp] = in_data[x * w_in * num + tmpy]; // (y,x) = in(x,y) tmpy++; tmp--; } } } } void flipxy_basic( const uint8_t* in_data, int h_in, int w_in, uint8_t* out_data, int num) { int win = w_in * num; int h = h_in - 1; int w = win - 1; for (int x = 0; x < h_in; x++) { for (int y = 0; y < w_in; y++) { int tmpy = y * num; int tmp = tmpy + (num - 1); for (int i = 0; i < num; i++) { out_data[(h - x) * win + w - tmp] = in_data[x * win + tmpy]; // (h-y,w-x) = in(x,y) tmpy++; tmp--; } } } } void image_flip_basic(const uint8_t* in_data, uint8_t* out_data, ImageFormat srcFormat, int srcw, int srch, FlipParam flip) { int num = 1; if (srcFormat == ImageFormat::GRAY) { num = 1; } else if (srcFormat == ImageFormat::NV12 || srcFormat == ImageFormat::NV21) { num = 1; // todo return; } else if (srcFormat == ImageFormat::BGR || srcFormat == ImageFormat::RGB) { num = 3; } else if (srcFormat == ImageFormat::BGRA || srcFormat == ImageFormat::RGBA) { num = 4; } // printf("image_flip_basic: %d \n", flip); if (flip == FlipParam::X) { flipx_basic(in_data, srch, srcw, out_data, num); } else if (flip == FlipParam::Y) { flipy_basic(in_data, srch, srcw, out_data, num); } else if (flip == FlipParam::XY) { flipxy_basic(in_data, srch, srcw, out_data, num); } } <<<<<<< HEAD ======= void gray_to_tensor_basic(const uint8_t* bgr, float* output, int width, int height, float* means, float* scales, int num) { int size = width * height; float mean_val = means[0]; float scale_val = scales[0]; for (int h = 0; h < height; h++) { const uint8_t* ptr_bgr = bgr + h * width * num; float* ptr_h = output + h * width; for (int i = 0; i < width; i++) { *ptr_h++ = (ptr_bgr[0] - mean_val) * scale_val; ptr_bgr += num; } } } >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf void bgr_to_tensor_chw_basic(const uint8_t* bgr, float* output, int width, int height, float* means, float* scales, int num) { int size = width * height; float r_means = means[0]; float g_means = means[1]; float b_means = means[2]; float r_scales = scales[0]; float g_scales = scales[1]; float b_scales = scales[2]; for (int h = 0; h < height; h++) { const uint8_t* ptr_bgr = bgr + h * width * num; float* ptr_b = output + h * width; float* ptr_g = ptr_b + size; float* ptr_r = ptr_g + size; for (int i = 0; i < width; i++) { *ptr_b++ = (ptr_bgr[0] - b_means) * b_scales; *ptr_g++ = (ptr_bgr[1] - g_means) * g_scales; *ptr_r++ = (ptr_bgr[2] - r_means) * r_scales; ptr_bgr += num; } } } void bgr_to_tensor_hwc_basic(const uint8_t* bgr, float* output, int width, int height, float* means, float* scales, int num) { int size = width * height; float r_means = means[0]; float g_means = means[1]; float b_means = means[2]; float r_scales = scales[0]; float g_scales = scales[1]; float b_scales = scales[2]; for (int h = 0; h < height; h++) { const uint8_t* ptr_bgr = bgr + h * width * num; float* out_bgr = output + h * width * num; for (int i = 0; i < width; i++) { *out_bgr++ = (ptr_bgr[0] - b_means) * b_scales; *out_bgr++ = (ptr_bgr[1] - g_means) * g_scales; *out_bgr++ = (ptr_bgr[2] - r_means) * r_scales; ptr_bgr += num; } } } void image_to_tensor_basic(const uint8_t* in_data, Tensor* dst, ImageFormat srcFormat, <<<<<<< HEAD LayOut layout, ======= LayoutType layout, >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf int srcw, int srch, float* means, float* scales) { float* output = dst->mutable_data<float>(); <<<<<<< HEAD if (layout == LayOut::CHW && (srcFormat == ImageFormat::BGR || srcFormat == ImageFormat::RGB)) { bgr_to_tensor_chw_basic(in_data, output, srcw, srch, means, scales, 3); } else if (layout == LayOut::HWC && (srcFormat == ImageFormat::BGR || srcFormat == ImageFormat::RGB)) { bgr_to_tensor_hwc_basic(in_data, output, srcw, srch, means, scales, 3); } else if (layout == LayOut::CHW && (srcFormat == ImageFormat::BGRA || srcFormat == ImageFormat::RGBA)) { bgr_to_tensor_chw_basic(in_data, output, srcw, srch, means, scales, 4); } else if (layout == LayOut::HWC && (srcFormat == ImageFormat::BGRA || srcFormat == ImageFormat::RGBA)) { bgr_to_tensor_hwc_basic(in_data, output, srcw, srch, means, scales, 4); ======= if (layout == LayoutType::kNCHW && (srcFormat == ImageFormat::BGR || srcFormat == ImageFormat::RGB)) { bgr_to_tensor_chw_basic(in_data, output, srcw, srch, means, scales, 3); } else if (layout == LayoutType::kNHWC && (srcFormat == ImageFormat::BGR || srcFormat == ImageFormat::RGB)) { bgr_to_tensor_hwc_basic(in_data, output, srcw, srch, means, scales, 3); } else if (layout == LayoutType::kNCHW && (srcFormat == ImageFormat::BGRA || srcFormat == ImageFormat::RGBA)) { bgr_to_tensor_chw_basic(in_data, output, srcw, srch, means, scales, 4); } else if (layout == LayoutType::kNHWC && (srcFormat == ImageFormat::BGRA || srcFormat == ImageFormat::RGBA)) { bgr_to_tensor_hwc_basic(in_data, output, srcw, srch, means, scales, 4); } else if (srcFormat == ImageFormat::GRAY && (layout == LayoutType::kNHWC || layout == LayoutType::kNCHW)) { gray_to_tensor_basic(in_data, output, srcw, srch, means, scales, 1); >>>>>>> d5b08275c46b2517790d170a469006246f59b6bf } }
core_zttmlq.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> c d s * **/ #include "core_blas.h" #include "plasma_types.h" #include "plasma_internal.h" #include "core_lapack.h" #include <omp.h> /***************************************************************************//** * * @ingroup core_ttmlq * * Overwrites the general complex m1-by-n1 tile A1 and * m2-by-n2 tile A2 with * * side = PlasmaLeft side = PlasmaRight * trans = PlasmaNoTrans Q * | A1 | | A1 A2 | * Q * | A2 | * * trans = Plasma_ConjTrans Q^H * | A1 | | A1 A2 | * Q^H * | A2 | * * where Q is a complex unitary matrix defined as the product of k * elementary reflectors * * Q = H(k)^H . . . H(2)^H H(1)^H * * as returned by core_zttlqt. * ******************************************************************************* * * @param[in] side * - PlasmaLeft : apply Q or Q^H from the Left; * - PlasmaRight : apply Q or Q^H from the Right. * * @param[in] trans * - PlasmaNoTrans : Apply Q; * - Plasma_ConjTrans : Apply Q^H. * * @param[in] m1 * The number of rows of the tile A1. m1 >= 0. * * @param[in] n1 * The number of columns of the tile A1. n1 >= 0. * * @param[in] m2 * The number of rows of the tile A2. m2 >= 0. * * @param[in] n2 * The number of columns of the tile A2. n2 >= 0. * * @param[in] k * The number of elementary reflectors whose product defines * the matrix Q. * * @param[in] ib * The inner-blocking size. ib >= 0. * * @param[in,out] A1 * On entry, the m1-by-n1 tile A1. * On exit, A1 is overwritten by the application of Q. * * @param[in] lda1 * The leading dimension of the array A1. lda1 >= max(1,m1). * * @param[in,out] A2 * On entry, the m2-by-n2 tile A2. * On exit, A2 is overwritten by the application of Q. * * @param[in] lda2 * The leading dimension of the tile A2. lda2 >= max(1,m2). * * @param[in] V * The i-th row must contain the vector which defines the * elementary reflector H(i), for i = 1,2,...,k, as returned by * core_zttlqt in the first k rows of its array argument V. * * @param[in] ldv * The leading dimension of the array V. ldv >= max(1,k). * * @param[out] T * The ib-by-k triangular factor T of the block reflector. * T is upper triangular by block (economic storage); * The rest of the array is not referenced. * * @param[in] ldt * The leading dimension of the array T. ldt >= ib. * * @param work * Auxiliary workspace array of length * ldwork-by-m1 if side == PlasmaLeft * ldwork-by-ib if side == PlasmaRight * * @param[in] ldwork * The leading dimension of the array work. * ldwork >= max(1,ib) if side == PlasmaLeft * ldwork >= max(1,n1) if side == PlasmaRight * ******************************************************************************* * * @retval PlasmaSuccess successful exit * @retval < 0 if -i, the i-th argument had an illegal value * ******************************************************************************/ int core_zttmlq(plasma_enum_t side, plasma_enum_t trans, int m1, int n1, int m2, int n2, int k, int ib, plasma_complex64_t *A1, int lda1, plasma_complex64_t *A2, int lda2, const plasma_complex64_t *V, int ldv, const plasma_complex64_t *T, int ldt, plasma_complex64_t *work, int ldwork) { // Check input arguments. if (side != PlasmaLeft && side != PlasmaRight) { coreblas_error("illegal value of side"); return -1; } if (trans != PlasmaNoTrans && trans != Plasma_ConjTrans) { coreblas_error("illegal value of trans"); return -2; } if (m1 < 0) { coreblas_error("illegal value of m1"); return -3; } if (n1 < 0) { coreblas_error("illegal value of n1"); return -4; } if (m2 < 0 || (m2 != m1 && side == PlasmaRight)) { coreblas_error("illegal value of m2"); return -5; } if (n2 < 0 || (n2 != n1 && side == PlasmaLeft)) { coreblas_error("illegal value of n2"); return -6; } if (k < 0 || (side == PlasmaLeft && k > m1 ) || (side == PlasmaRight && k > n1)) { coreblas_error("illegal value of k"); return -7; } if (ib < 0) { coreblas_error("illegal value of ib"); return -8; } if (A1 == NULL) { coreblas_error("NULL A1"); return -9; } if (lda1 < imax(1, m1)) { coreblas_error("illegal value of lda1"); return -10; } if (A2 == NULL) { coreblas_error("NULL A2"); return -11; } if (lda2 < imax(1, m2)) { coreblas_error("illegal value of lda2"); return -12; } if (V == NULL) { coreblas_error("NULL V"); return -13; } if (ldv < imax(1, k)) { coreblas_error("illegal value of ldv"); return -14; } if (T == NULL) { coreblas_error("NULL T"); return -15; } if (ldt < imax(1, ib)) { coreblas_error("illegal value of ldt"); return -16; } if (work == NULL) { coreblas_error("NULL work"); return -17; } if (ldwork < imax(1, side == PlasmaLeft ? ib : n1)) { coreblas_error("illegal value of ldwork"); return -18; } // quick return if (m1 == 0 || n1 == 0 || m2 == 0 || n2 == 0 || k == 0 || ib == 0) return PlasmaSuccess; int i1, i3; if (((side == PlasmaLeft) && (trans == PlasmaNoTrans)) || ((side == PlasmaRight) && (trans != PlasmaNoTrans))) { i1 = 0; i3 = ib; } else { i1 = ((k-1)/ib)*ib; i3 = -ib; } if (trans == PlasmaNoTrans) trans = Plasma_ConjTrans; else trans = PlasmaNoTrans; for (int i = i1; (i > -1) && (i < k); i += i3) { int kb = imin(ib, k-i); int ic = 0; int jc = 0; int mi = m1; int mi2 = m2; int ni = n1; int ni2 = n2; int l; if (side == PlasmaLeft) { mi = kb; // m1 - i; mi2 = imin(i+kb, m2); l = imin(kb, imax(0, m2-i)); ic = i; } else { ni = kb; ni2 = imin(i+kb, n2); l = imin(kb, imax(0, n2-i)); jc = i; } // Apply H or H^H. core_zparfb( side, trans, PlasmaForward, PlasmaRowwise, mi, ni, mi2, ni2, kb, l, &A1[lda1*jc+ic], lda1, A2, lda2, &V[i], ldv, &T[ldt*i], ldt, work, ldwork); } return PlasmaSuccess; } /******************************************************************************/ void core_omp_zttmlq(plasma_enum_t side, plasma_enum_t trans, int m1, int n1, int m2, int n2, int k, int ib, plasma_complex64_t *A1, int lda1, plasma_complex64_t *A2, int lda2, const plasma_complex64_t *V, int ldv, const plasma_complex64_t *T, int ldt, plasma_workspace_t work, plasma_sequence_t *sequence, plasma_request_t *request) { #pragma omp task depend(inout:A1[0:lda1*n1]) \ depend(inout:A2[0:lda2*n2]) \ depend(in:V[0:ldv*n2]) \ depend(in:T[0:ib*k]) { if (sequence->status == PlasmaSuccess) { // Prepare workspaces. int tid = omp_get_thread_num(); plasma_complex64_t *W = (plasma_complex64_t*)work.spaces[tid]; int ldwork = side == PlasmaLeft ? ib : n1; // TODO: double check // Call the kernel. int info = core_zttmlq(side, trans, m1, n1, m2, n2, k, ib, A1, lda1, A2, lda2, V, ldv, T, ldt, W, ldwork); if (info != PlasmaSuccess) { plasma_error("core_zttmlq() failed"); plasma_request_fail(sequence, request, PlasmaErrorInternal); } } } }
libperf_int.h
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2015. ALL RIGHTS RESERVED. * Copyright (C) The University of Tennessee and The University * of Tennessee Research Foundation. 2016. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #ifndef LIBPERF_INT_H_ #define LIBPERF_INT_H_ #include <tools/perf/api/libperf.h> BEGIN_C_DECLS /** @file libperf_int.h */ #include <ucs/async/async.h> #include <ucs/time/time.h> #include <ucs/sys/math.h> #if _OPENMP #include <omp.h> #endif #define TIMING_QUEUE_SIZE 2048 #define UCT_PERF_TEST_AM_ID 5 #define ADDR_BUF_SIZE 2048 #define EXTRA_INFO_SIZE 256 #define UCX_PERF_TEST_FOREACH(perf) \ while (!ucx_perf_context_done(perf)) #define rte_call(_perf, _func, ...) \ ((_perf)->params.rte->_func((_perf)->params.rte_group, ## __VA_ARGS__)) typedef struct ucx_perf_context ucx_perf_context_t; typedef struct uct_peer uct_peer_t; typedef struct ucp_perf_request ucp_perf_request_t; typedef struct ucx_perf_thread_context ucx_perf_thread_context_t; struct ucx_perf_allocator { ucs_memory_type_t mem_type; ucs_status_t (*init)(ucx_perf_context_t *perf); ucs_status_t (*uct_alloc)(const ucx_perf_context_t *perf, size_t length, unsigned flags, uct_allocated_memory_t *alloc_mem); void (*uct_free)(const ucx_perf_context_t *perf, uct_allocated_memory_t *alloc_mem); void (*memcpy)(void *dst, ucs_memory_type_t dst_mem_type, const void *src, ucs_memory_type_t src_mem_type, size_t count); void* (*memset)(void *dst, int value, size_t count); }; struct ucx_perf_context { ucx_perf_params_t params; /* Buffers */ void *send_buffer; void *recv_buffer; /* Measurements */ double start_time_acc; /* accurate start time */ ucs_time_t end_time; /* inaccurate end time (upper bound) */ ucs_time_t prev_time; /* time of previous iteration */ ucs_time_t report_interval; /* interval of showing report */ ucx_perf_counter_t max_iter; /* Measurements of current/previous **report** */ struct { ucx_perf_counter_t msgs; /* number of messages */ ucx_perf_counter_t bytes; /* number of bytes */ ucx_perf_counter_t iters; /* number of iterations */ ucs_time_t time; /* inaccurate time (for median and report interval) */ double time_acc; /* accurate time (for avg latency/bw/msgrate) */ } current, prev; ucs_time_t timing_queue[TIMING_QUEUE_SIZE]; unsigned timing_queue_head; const ucx_perf_allocator_t *send_allocator; const ucx_perf_allocator_t *recv_allocator; char extra_info[EXTRA_INFO_SIZE]; union { struct { ucs_async_context_t async; uct_component_h cmpt; uct_md_h md; uct_worker_h worker; uct_iface_h iface; uct_peer_t *peers; uct_allocated_memory_t send_mem; uct_allocated_memory_t recv_mem; uct_iov_t *iov; } uct; struct { ucp_context_h context; ucx_perf_thread_context_t* tctx; ucp_worker_h worker; ucp_ep_h ep; ucp_rkey_h rkey; unsigned long remote_addr; ucp_mem_h send_memh; ucp_mem_h recv_memh; ucp_dt_iov_t *send_iov; ucp_dt_iov_t *recv_iov; void *am_hdr; } ucp; }; }; struct ucx_perf_thread_context { pthread_t pt; int tid; ucs_status_t status; ucx_perf_context_t perf; ucx_perf_result_t result; }; struct uct_peer { uct_ep_h ep; unsigned long remote_addr; uct_rkey_bundle_t rkey; }; struct ucp_perf_request { void *context; }; typedef struct { ucs_status_t (*setup)(ucx_perf_context_t *perf); void (*cleanup)(ucx_perf_context_t *perf); ucs_status_t (*run)(ucx_perf_context_t *perf); void (*barrier)(ucx_perf_context_t *perf); } ucx_perf_funcs_t; extern ucx_perf_funcs_t ucx_perf_funcs[]; unsigned rte_peer_index(unsigned group_size, unsigned group_index); void ucx_perf_test_start_clock(ucx_perf_context_t *perf); void uct_perf_ep_flush_b(ucx_perf_context_t *perf, int peer_index); void uct_perf_iface_flush_b(ucx_perf_context_t *perf); ucs_status_t uct_perf_test_dispatch(ucx_perf_context_t *perf); ucs_status_t ucp_perf_test_dispatch(ucx_perf_context_t *perf); void ucx_perf_calc_result(ucx_perf_context_t *perf, ucx_perf_result_t *result); void uct_perf_barrier(ucx_perf_context_t *perf); void ucp_perf_thread_barrier(ucx_perf_context_t *perf); void ucp_perf_barrier(ucx_perf_context_t *perf); ucs_status_t ucp_perf_test_alloc_mem(ucx_perf_context_t *perf); void ucp_perf_test_free_mem(ucx_perf_context_t *perf); ucs_status_t uct_perf_test_alloc_mem(ucx_perf_context_t *perf); void uct_perf_test_free_mem(ucx_perf_context_t *perf); ucs_status_t ucx_perf_thread_spawn(ucx_perf_context_t *perf, ucx_perf_result_t* result); void ucx_perf_test_prepare_new_run(ucx_perf_context_t *perf, const ucx_perf_params_t *params); ucs_status_t ucx_perf_do_warmup(ucx_perf_context_t *perf, const ucx_perf_params_t *params); /** * Get the total length of the message size given by parameters */ size_t ucx_perf_get_message_size(const ucx_perf_params_t *params); void ucx_perf_report(ucx_perf_context_t *perf); static UCS_F_ALWAYS_INLINE int ucx_perf_context_done(ucx_perf_context_t *perf) { return ucs_unlikely((perf->current.iters >= perf->max_iter) || (perf->current.time > perf->end_time)); } static inline void ucx_perf_get_time(ucx_perf_context_t *perf) { perf->current.time_acc = ucs_get_accurate_time(); } static inline void ucx_perf_omp_barrier(ucx_perf_context_t *perf) { #if _OPENMP if (perf->params.thread_count > 1) { #pragma omp barrier } #endif } static UCS_F_ALWAYS_INLINE void ucx_perf_update(ucx_perf_context_t *perf, ucx_perf_counter_t iters, size_t bytes) { perf->current.time = ucs_get_time(); perf->current.iters += iters; perf->current.bytes += bytes; perf->current.msgs += 1; perf->timing_queue[perf->timing_queue_head] = perf->current.time - perf->prev_time; ++perf->timing_queue_head; if (perf->timing_queue_head == TIMING_QUEUE_SIZE) { perf->timing_queue_head = 0; } perf->prev_time = perf->current.time; if (ucs_unlikely((perf->current.time - perf->prev.time) >= perf->report_interval)) { ucx_perf_report(perf); } } END_C_DECLS #endif
CT_IMPL.c
/* * _CT_IMPL_C_ * * Copyright (C) 2017-2019 Tactical Computing Laboratories, LLC * All Rights Reserved * contact@tactcomplabs.com * * See LICENSE in the top level directory for licensing details */ #include <omp.h> #include <stdint.h> /* OpenMP Benchmark Implementations * * Benchmark implementations are in the form: * * void BENCHTYPE_ATOMTYPE( uint64_t *ARRAY, uint64_t *IDX, * unsigned long long iters, * unsigned long long pes ) * */ void RAND_ADD( uint64_t *restrict ARRAY, uint64_t *restrict IDX, uint64_t iters, uint64_t pes ){ uint64_t i = 0; uint64_t start = 0; #pragma omp parallel private(start,i) { start = (uint64_t)(omp_get_thread_num()) * iters; #pragma omp for for( i=start; i<(start+iters); i++ ){ __atomic_fetch_add( &ARRAY[IDX[i]], (uint64_t)(0x1), __ATOMIC_RELAXED ); } } } void RAND_CAS( uint64_t *restrict ARRAY, uint64_t *restrict IDX, uint64_t iters, uint64_t pes ){ uint64_t i = 0; uint64_t start = 0; #pragma omp parallel private(start,i) { start = (uint64_t)(omp_get_thread_num()) * iters; #pragma omp for for( i=start; i<(start+iters); i++ ){ __atomic_compare_exchange_n( &ARRAY[IDX[i]], &ARRAY[IDX[i]], ARRAY[IDX[i]], 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED ); } } } void STRIDE1_ADD( uint64_t *restrict ARRAY, uint64_t *restrict IDX, uint64_t iters, uint64_t pes ){ uint64_t i = 0; uint64_t start = 0; #pragma omp parallel private(start,i) { start = (uint64_t)(omp_get_thread_num()) * iters; #pragma omp for for( i=start; i<(start+iters); i++ ){ __atomic_fetch_add( &ARRAY[i], (uint64_t)(0xF), __ATOMIC_RELAXED ); } } } void STRIDE1_CAS( uint64_t *restrict ARRAY, uint64_t *restrict IDX, uint64_t iters, uint64_t pes ){ uint64_t i = 0; uint64_t start = 0; #pragma omp parallel private(start,i) { start = (uint64_t)(omp_get_thread_num()) * iters; #pragma omp for for( i=start; i<(start+iters); i++ ){ __atomic_compare_exchange_n( &ARRAY[i], &ARRAY[i], ARRAY[i], 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED ); } } } void STRIDEN_ADD( uint64_t *ARRAY, uint64_t *IDX, uint64_t iters, uint64_t pes, uint64_t stride ){ uint64_t i = 0; uint64_t start = 0; #pragma omp parallel private(start,i) { start = (uint64_t)(omp_get_thread_num()) * iters; #pragma omp for for( i=start; i<(start+iters); i+=stride ){ __atomic_fetch_add( &ARRAY[i], (uint64_t)(0xF), __ATOMIC_RELAXED ); } } } void STRIDEN_CAS( uint64_t *ARRAY, uint64_t *IDX, uint64_t iters, uint64_t pes, uint64_t stride ){ uint64_t i = 0; uint64_t start = 0; #pragma omp parallel private(start,i) { start = (uint64_t)(omp_get_thread_num()) * iters; #pragma omp for for( i=start; i<(start+iters); i+=stride ){ __atomic_compare_exchange_n( &ARRAY[i], &ARRAY[i], ARRAY[i], 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED ); } } } void PTRCHASE_ADD( uint64_t *ARRAY, uint64_t *IDX, uint64_t iters, uint64_t pes ){ uint64_t i = 0; uint64_t start = 0; #pragma omp parallel private(start,i) { start = (uint64_t)(omp_get_thread_num()) * iters; #pragma omp for for( i=0; i<iters; i++ ){ start = __atomic_fetch_add( &IDX[start], (uint64_t)(0x00ull), __ATOMIC_RELAXED ); } } } void PTRCHASE_CAS( uint64_t *ARRAY, uint64_t *IDX, uint64_t iters, uint64_t pes ){ uint64_t i = 0; uint64_t start = 0; #pragma omp parallel private(start,i) { start = (uint64_t)(omp_get_thread_num()) * iters; #pragma omp for for( i=0; i<iters; i++ ){ __atomic_compare_exchange_n( &IDX[start], &start, IDX[start], 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED ); } } } void SG_ADD( uint64_t *ARRAY, uint64_t *IDX, uint64_t iters, uint64_t pes ){ uint64_t i = 0; uint64_t start = 0; uint64_t src = 0; uint64_t dest = 0; uint64_t val = 0; #pragma omp parallel private(start,i,src,dest,val) { start = (uint64_t)(omp_get_thread_num()) * iters; #pragma omp for for( i=start; i<(start+iters); i++ ){ src = __atomic_fetch_add( &IDX[i], (uint64_t)(0x00ull), __ATOMIC_RELAXED ); dest = __atomic_fetch_add( &IDX[i+1], (uint64_t)(0x00ull), __ATOMIC_RELAXED ); val = __atomic_fetch_add( &ARRAY[src], (uint64_t)(0x01ull), __ATOMIC_RELAXED ); __atomic_fetch_add( &ARRAY[dest], val, __ATOMIC_RELAXED ); } } } void SG_CAS( uint64_t *ARRAY, uint64_t *IDX, uint64_t iters, uint64_t pes ){ uint64_t i = 0; uint64_t start = 0; uint64_t src = 0; uint64_t dest = 0; uint64_t val = 0; #pragma omp parallel private(start,i,src,dest,val) { start = (uint64_t)(omp_get_thread_num()) * iters; val = 0x00ull; src = 0x00ull; dest = 0x00ull; #pragma omp for for( i=start; i<(start+iters); i++ ){ __atomic_compare_exchange_n( &IDX[i], &src, IDX[i], 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED ); __atomic_compare_exchange_n( &IDX[i+1], &dest, IDX[i+1], 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED ); __atomic_compare_exchange_n( &ARRAY[src], &val, ARRAY[src], 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED ); __atomic_compare_exchange_n( &ARRAY[dest], &ARRAY[dest], val, 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED ); } } } void CENTRAL_ADD( uint64_t *ARRAY, uint64_t *IDX, uint64_t iters, uint64_t pes ){ uint64_t i = 0; #pragma omp parallel private(i) { #pragma omp for for( i=0; i<iters; i++ ){ __atomic_fetch_add( &ARRAY[0], (uint64_t)(0x1), __ATOMIC_RELAXED ); } } } void CENTRAL_CAS( uint64_t *ARRAY, uint64_t *IDX, uint64_t iters, uint64_t pes ){ uint64_t i = 0; #pragma omp parallel private(i) { #pragma omp for for( i=0; i<iters; i++ ){ __atomic_compare_exchange_n( &ARRAY[0], &ARRAY[0], ARRAY[0], 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED ); } } } void SCATTER_ADD( uint64_t *ARRAY, uint64_t *IDX, uint64_t iters, uint64_t pes ){ uint64_t i = 0; uint64_t start = 0; uint64_t dest = 0; uint64_t val = 0; #pragma omp parallel private(start,i,dest,val) { start = (uint64_t)(omp_get_thread_num()) * iters; #pragma omp for for( i=start; i<(start+iters); i++ ){ dest = __atomic_fetch_add( &IDX[i+1], (uint64_t)(0x00ull), __ATOMIC_RELAXED ); val = __atomic_fetch_add( &ARRAY[i], (uint64_t)(0x01ull), __ATOMIC_RELAXED ); __atomic_fetch_add( &ARRAY[dest], val, __ATOMIC_RELAXED ); } } } void SCATTER_CAS( uint64_t *ARRAY, uint64_t *IDX, uint64_t iters, uint64_t pes ){ uint64_t i = 0; uint64_t start = 0; uint64_t dest = 0; uint64_t val = 0; #pragma omp parallel private(start,i,dest,val) { start = (uint64_t)(omp_get_thread_num()) * iters; dest = 0x00ull; val = 0x00ull; #pragma omp for for( i=start; i<(start+iters); i++ ){ __atomic_compare_exchange_n( &IDX[i+1], &dest, IDX[i+1], 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED ); __atomic_compare_exchange_n( &ARRAY[i], &val, ARRAY[i], 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED ); __atomic_compare_exchange_n( &ARRAY[dest], &ARRAY[dest], val, 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED ); } } } void GATHER_ADD( uint64_t *ARRAY, uint64_t *IDX, uint64_t iters, uint64_t pes ){ uint64_t i = 0; uint64_t start = 0; uint64_t dest = 0; uint64_t val = 0; #pragma omp parallel private(start,i,dest,val) { start = (uint64_t)(omp_get_thread_num()) * iters; #pragma omp for for( i=start; i<(start+iters); i++ ){ dest = __atomic_fetch_add( &IDX[i+1], (uint64_t)(0x00ull), __ATOMIC_RELAXED ); val = __atomic_fetch_add( &ARRAY[dest], (uint64_t)(0x01ull), __ATOMIC_RELAXED ); __atomic_fetch_add( &ARRAY[i], val, __ATOMIC_RELAXED ); } } } void GATHER_CAS( uint64_t *ARRAY, uint64_t *IDX, uint64_t iters, uint64_t pes ){ uint64_t i = 0; uint64_t start = 0; uint64_t dest = 0; uint64_t val = 0; #pragma omp parallel private(start,i,dest,val) { start = (uint64_t)(omp_get_thread_num()) * iters; dest = 0x00ull; val = 0x00ull; #pragma omp for for( i=start; i<(start+iters); i++ ){ __atomic_compare_exchange_n( &IDX[i+1], &dest, IDX[i+1], 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED ); __atomic_compare_exchange_n( &ARRAY[dest], &val, ARRAY[dest], 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED ); __atomic_compare_exchange_n( &ARRAY[i], &ARRAY[i], val, 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED ); } } } /* EOF */
GB_unop__ainv_fp32_fp32.c
//------------------------------------------------------------------------------ // GB_unop: 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_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__ainv_fp32_fp32 // op(A') function: GB_unop_tran__ainv_fp32_fp32 // C type: float // A type: float // cast: float cij = aij // unaryop: cij = -aij #define GB_ATYPE \ float #define GB_CTYPE \ float // 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) \ float z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = aij ; \ Cx [pC] = -z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__ainv_fp32_fp32 ( float *Cx, // Cx and Ax may be aliased const float *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++) { float aij = Ax [p] ; float 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__ainv_fp32_fp32 ( 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_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
DCSCTile.h
/****************************************************************************** * ** Copyright (c) 2016, Intel Corporation ** * ** 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. ** * ** 3. 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 ** * ** HOLDER 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. * * ******************************************************************************/ /* Michael Anderson (Intel Corp.) * * ******************************************************************************/ #ifndef SRC_DCSCTILE_H_ #define SRC_DCSCTILE_H_ #include <string> #include <algorithm> #include <vector> template <typename T> bool compare_dcsc(const tedge_t<T> &a, const tedge_t<T> &b) { if (a.tile_id < b.tile_id) return true; else if (a.tile_id > b.tile_id) return false; if (a.dst < b.dst) return true; else if (a.dst > b.dst) return false; if (a.src < b.src) return true; else if (a.src > b.src) return false; return false; } template <typename T> class DCSCTile { public: std::string name; int m; int n; int nnz; int num_cols; int *row_inds; // row_inds is nnz int *col_ptrs; // col_ptrs is ncols int *col_indices; T *vals; int num_partitions; int *row_pointers; int *edge_pointers; int *col_starts; // col_indices is ncols // vals is nnz // row_pointers is the partitioning info (num_partitions+1) // edge_pointers is the partitioning info (num_partitions+1) // col_starts is the partitioning info (num_partitions+1) DCSCTile() : name("TEMP"), m(0), n(0), nnz(0), num_partitions(0) {} DCSCTile(int _m, int _n) : name("TEMP"), m(_m), n(_n), nnz(0), num_partitions(0) {} static void static_partition(int *&row_pointers, int m, int num_partitions, int round) { row_pointers = reinterpret_cast<int *>( _mm_malloc((num_partitions + 1) * sizeof(int), 64)); if (round == 1) { int rows_per_partition = m / num_partitions; int rows_leftover = m % num_partitions; row_pointers[0] = 0; int current_row = row_pointers[0] + rows_per_partition; for (int p = 1; p < num_partitions + 1; p++) { if (rows_leftover > 0) { current_row += 1; row_pointers[p] = current_row; current_row += rows_per_partition; rows_leftover--; } else { row_pointers[p] = current_row; current_row += rows_per_partition; } } } else { int n512 = std::max((m / round) / num_partitions, 1); int n_round = std::max(0, m / round - n512 * num_partitions); assert(n_round < num_partitions); row_pointers[0] = 0; for (int p = 1; p < num_partitions; p++) { row_pointers[p] = row_pointers[p - 1] + ((n_round > 0) ? ((n512 + 1) * round) : (n512 * round)); row_pointers[p] = std::min(row_pointers[p], m); if (n_round > 0) n_round--; } row_pointers[num_partitions] = m; } } static void set_edge_pointers(tedge_t<T> *edges, int *row_pointers, int **edge_pointers, int nnz, int num_partitions) { // Figure out edge pointers (*edge_pointers) = reinterpret_cast<int *>( _mm_malloc((num_partitions + 1) * sizeof(int), 64)); int p = 0; for (int edge_id = 0; edge_id < nnz; edge_id++) { while (edges[edge_id].src >= row_pointers[p]) { (*edge_pointers)[p] = edge_id; p++; } } (*edge_pointers)[p] = nnz; for (p = p + 1; p < num_partitions + 1; p++) { (*edge_pointers)[p] = nnz; } } DCSCTile(edge_t<T> *edges, int _m, int _n, int _nnz, int row_start, int col_start) : name("TEMP"), m(_m), n(_n), nnz(_nnz) { double _start_time = MPI_Wtime(); if (nnz > 0) { num_partitions = omp_get_max_threads() * 16; // Partition DCSCTile<T>::static_partition(row_pointers, this->m, num_partitions, 32); // Set partition IDs for each edge tedge_t<T> *p_edges = reinterpret_cast<tedge_t<T> *>( _mm_malloc((uint64_t)nnz * (uint64_t)sizeof(tedge_t<T>), 64)); std::cout << "num partitions: " << num_partitions << std::endl; double _ep_start = MPI_Wtime(); #pragma omp parallel for for (int i = 0; i < nnz; i++) { p_edges[i].src = edges[i].src - 1 - row_start; p_edges[i].dst = edges[i].dst - 1 - col_start; p_edges[i].val = edges[i].val; p_edges[i].tile_id = -1; int p_start = 0; int p_end = num_partitions-1; while(1) { int p_half = p_start + (p_end - p_start); // Check p_half if (p_edges[i].src >= row_pointers[p_half] && p_edges[i].src < row_pointers[p_half + 1]) { p_edges[i].tile_id = p_half; break; } if(p_edges[i].src < row_pointers[p_half]) p_end = p_half - 1; if(p_edges[i].src >= row_pointers[p_half+1]) p_start = p_half + 1; } #ifdef CHECK_BINARY_SEARCH for (int p = 0; p < num_partitions; p++) { if (p_edges[i].src >= row_pointers[p] && p_edges[i].src < row_pointers[p + 1]) { //p_edges[i].tile_id = p; //break; assert(p_edges[i].tile_id == p); } #endif assert(p_edges[i].tile_id >= 0); } double _ep_end = MPI_Wtime(); std::cout << "set_edge_pointers time: " << _ep_end - _ep_start << std::endl; // Sort // std::cout << "Sorting: " << (uint64_t)nnz << std::endl; // std::cout << "allocated : " << (uint64_t)nnz * (uint64_t)sizeof(tedge_t<T>) << std::endl; #pragma omp parallel for for(int i =0 ; i < nnz ; i++) { assert(p_edges[i].src >= 0); assert(p_edges[i].dst >= 0); assert(p_edges[i].src < _m); assert(p_edges[i].dst < _n); } __gnu_parallel::sort(p_edges, p_edges + nnz, compare_dcsc<T>); // Find edge pointers DCSCTile<T>::set_edge_pointers(p_edges, row_pointers, &edge_pointers, nnz, num_partitions); // Count columns int *ncols = reinterpret_cast<int *>(_mm_malloc(num_partitions * sizeof(int), 64)); col_starts = reinterpret_cast<int *>( _mm_malloc((num_partitions + 1) * sizeof(int), 64)); #pragma omp parallel for for (int p = 0; p < num_partitions; p++) { int current_column = -1; int num_columns = 0; for (int edge_id = edge_pointers[p]; edge_id < edge_pointers[p + 1]; edge_id++) { if (current_column < p_edges[edge_id].dst) { num_columns++; current_column = p_edges[edge_id].dst; } } ncols[p] = num_columns; } int total_cols = 0; for (int p = 0; p < num_partitions; p++) { col_starts[p] = total_cols; total_cols += ncols[p] + 1; } col_starts[num_partitions] = total_cols; num_cols = total_cols; // Build DCSC std::cout << "Allocating nnz vals: " << nnz << std::endl; vals = reinterpret_cast<T *>( _mm_malloc((uint64_t)nnz * (uint64_t)sizeof(T), 64)); row_inds = reinterpret_cast<int *>( _mm_malloc((uint64_t)nnz * (uint64_t)sizeof(int), 64)); col_indices = reinterpret_cast<int *>( _mm_malloc(col_starts[num_partitions] * sizeof(int), 64)); col_ptrs = reinterpret_cast<int *>( _mm_malloc(col_starts[num_partitions] * sizeof(int), 64)); #pragma omp parallel for for (int p = 0; p < num_partitions; p++) { T *val = vals + edge_pointers[p]; int *row_ind = row_inds + edge_pointers[p]; int *col_index = col_indices + col_starts[p]; int *col_ptr = col_ptrs + col_starts[p]; int current_column = -1; int current_column_num = -1; for (int edge_id = edge_pointers[p]; edge_id < edge_pointers[p + 1]; edge_id++) { val[edge_id - edge_pointers[p]] = p_edges[edge_id].val; row_ind[edge_id - edge_pointers[p]] = p_edges[edge_id].src; if (current_column < p_edges[edge_id].dst) { current_column_num++; current_column = p_edges[edge_id].dst; col_index[current_column_num] = current_column; col_ptr[current_column_num] = edge_id - edge_pointers[p]; } } int num_columns = col_starts[p + 1] - col_starts[p] - 1; col_ptr[num_columns] = edge_pointers[p + 1] - edge_pointers[p]; col_index[num_columns] = n + 1; } _mm_free(p_edges); _mm_free(ncols); } else { num_partitions = 0; } double _end_time = MPI_Wtime(); std::cout << "fn time: " << _end_time - _start_time << std::endl; } void get_edges(edge_t<T> *edges, int row_start, int col_start) { int nnzcnt = 0; for (int p = 0; p < num_partitions; p++) { for (int j = 0; j < (col_starts[p + 1] - col_starts[p]) - 1; j++) { int col_index = col_indices[col_starts[p] + j]; for (int nz_idx = col_ptrs[col_starts[p] + j]; nz_idx < col_ptrs[col_starts[p] + j + 1]; nz_idx++) { int row_ind = row_inds[edge_pointers[p] + nz_idx]; edges[nnzcnt].src = row_start + row_ind + 1; edges[nnzcnt].dst = col_start + col_index + 1; edges[nnzcnt].val = vals[edge_pointers[p] + nz_idx]; nnzcnt++; } } } assert(nnzcnt == this->nnz); } bool isEmpty() const { return nnz <= 0; } void clear() { if (!(isEmpty())) { } nnz = 0; } ~DCSCTile() {} void send_tile_metadata(int myrank, int dst_rank, int output_rank) { if (myrank == output_rank) std::cout << "Rank: " << myrank << " sending " << name << " to rank " << dst_rank << std::endl; MPI_Send(&(nnz), 1, MPI_INT, dst_rank, 0, MPI_COMM_WORLD); MPI_Send(&(m), 1, MPI_INT, dst_rank, 0, MPI_COMM_WORLD); MPI_Send(&(n), 1, MPI_INT, dst_rank, 0, MPI_COMM_WORLD); MPI_Send(&(num_partitions), 1, MPI_INT, dst_rank, 0, MPI_COMM_WORLD); MPI_Send(&(num_cols), 1, MPI_INT, dst_rank, 0, MPI_COMM_WORLD); } void recv_tile_metadata(int myrank, int src_rank, int output_rank) { if (!isEmpty()) { clear(); } MPI_Recv(&(nnz), 1, MPI_INT, src_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&(m), 1, MPI_INT, src_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&(n), 1, MPI_INT, src_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&(num_partitions), 1, MPI_INT, src_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&(num_cols), 1, MPI_INT, src_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } void send_tile(int myrank, int dst_rank, int output_rank, bool block, std::vector<MPI_Request> *reqs) { if (!isEmpty()) { if (block) { MPI_Send(row_inds, (uint64_t)(nnz * sizeof(int)), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD); MPI_Send(col_ptrs, num_cols * sizeof(int), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD); MPI_Send(col_indices, num_cols * sizeof(int), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD); MPI_Send(vals, (uint64_t)(nnz * sizeof(T)), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD); MPI_Send(row_pointers, (num_partitions + 1) * sizeof(int), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD); MPI_Send(edge_pointers, (num_partitions + 1) * sizeof(int), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD); MPI_Send(col_starts, (num_partitions + 1) * sizeof(int), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD); } else { MPI_Request r1, r2, r3, r4, r5, r6, r7, r8; MPI_Isend(row_inds, (uint64_t)(nnz * sizeof(int)), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD, &r1); MPI_Isend(col_ptrs, num_cols * sizeof(int), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD, &r2); MPI_Isend(col_indices, num_cols * sizeof(int), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD, &r3); MPI_Isend(vals, (uint64_t)(nnz * sizeof(T)), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD, &r4); MPI_Isend(row_pointers, (num_partitions + 1) * sizeof(int), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD, &r5); MPI_Isend(edge_pointers, (num_partitions + 1) * sizeof(int), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD, &r6); MPI_Isend(col_starts, (num_partitions + 1) * sizeof(int), MPI_BYTE, dst_rank, 0, MPI_COMM_WORLD, &r7); (*reqs).push_back(r1); (*reqs).push_back(r2); (*reqs).push_back(r3); (*reqs).push_back(r4); (*reqs).push_back(r5); (*reqs).push_back(r6); (*reqs).push_back(r7); } } } void recv_tile(int myrank, int src_rank, int output_rank, bool block, std::vector<MPI_Request> *reqs) { if (!(isEmpty())) { row_inds = reinterpret_cast<int *>( _mm_malloc((uint64_t)nnz * (uint64_t)sizeof(int), 64)); col_ptrs = reinterpret_cast<int *>(_mm_malloc(num_cols * sizeof(int), 64)); col_indices = reinterpret_cast<int *>(_mm_malloc(num_cols * sizeof(int), 64)); vals = reinterpret_cast<T *>( _mm_malloc((uint64_t)nnz * (uint64_t)sizeof(T), 64)); row_pointers = reinterpret_cast<int *>( _mm_malloc((num_partitions + 1) * sizeof(int), 64)); edge_pointers = reinterpret_cast<int *>( _mm_malloc((num_partitions + 1) * sizeof(int), 64)); col_starts = reinterpret_cast<int *>( _mm_malloc((num_partitions + 1) * sizeof(int), 64)); if (block) { MPI_Recv(row_inds, (uint64_t)(nnz * sizeof(int)), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(col_ptrs, num_cols * sizeof(int), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(col_indices, num_cols * sizeof(int), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(vals, (uint64_t)(nnz * sizeof(T)), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(row_pointers, (num_partitions + 1) * sizeof(int), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(edge_pointers, (num_partitions + 1) * sizeof(int), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(col_starts, (num_partitions + 1) * sizeof(int), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } else { MPI_Request r1, r2, r3, r4, r5, r6, r7, r8; MPI_Irecv(row_inds, (uint64_t)(nnz * sizeof(int)), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, &r1); MPI_Irecv(col_ptrs, num_cols * sizeof(int), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, &r2); MPI_Irecv(col_indices, num_cols * sizeof(int), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, &r3); MPI_Irecv(vals, (uint64_t)(nnz * sizeof(T)), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, &r4); MPI_Irecv(row_pointers, (num_partitions + 1) * sizeof(int), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, &r5); MPI_Irecv(edge_pointers, (num_partitions + 1) * sizeof(int), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, &r6); MPI_Irecv(col_starts, (num_partitions + 1) * sizeof(int), MPI_BYTE, src_rank, 0, MPI_COMM_WORLD, &r7); (*reqs).push_back(r1); (*reqs).push_back(r2); (*reqs).push_back(r3); (*reqs).push_back(r4); (*reqs).push_back(r5); (*reqs).push_back(r6); (*reqs).push_back(r7); } } } }; #endif // SRC_DCSCTILE_H_
rawSHA256_ng_fmt_plug.c
/* * Copyright 2013, epixoip. * AVX2 support, Copyright (c) 2015 magnum * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that redistribution of source * retains the above copyright. */ #include "arch.h" #if SIMD_COEF_32 && ARCH_LITTLE_ENDIAN==1 #if FMT_EXTERNS_H extern struct fmt_main fmt_rawSHA256_ng; #elif FMT_REGISTERS_H john_register_one(&fmt_rawSHA256_ng); #else #if !FAST_FORMATS_OMP #undef _OPENMP #endif #if _OPENMP #include <omp.h> #if __XOP__ #ifndef OMP_SCALE #define OMP_SCALE 512 /* AMD */ #endif #else #ifndef OMP_SCALE #define OMP_SCALE 512 /* Intel */ #endif #endif #endif #include "misc.h" #if !defined(DEBUG) && !defined(WITH_ASAN) // These compilers claim to be __GNUC__ but warn on gcc pragmas. #if __GNUC__ && !__INTEL_COMPILER && !__clang__ && !__llvm__ && !_MSC_VER #pragma GCC optimize 3 #endif #endif #include <string.h> #include <stdint.h> #include "pseudo_intrinsics.h" #include "common.h" #include "formats.h" #include "aligned.h" #include "memdbg.h" #if __MIC__ #define SIMD_TYPE "512/512 MIC 16x" #elif __AVX512F__ #define SIMD_TYPE "512/512 AVX512 16x" #elif __AVX2__ #define SIMD_TYPE "256/256 AVX2 8x" #elif __ALTIVEC__ #define SIMD_TYPE "128/128 AltiVec 4x" #elif __ARM_NEON #define SIMD_TYPE "128/128 NEON 4x" #elif __XOP__ #define SIMD_TYPE "128/128 XOP 4x" #elif __SSE4_1__ #define SIMD_TYPE "128/128 SSE4.1 4x" #elif __SSSE3__ #define SIMD_TYPE "128/128 SSSE3 4x" #else #define SIMD_TYPE "128/128 SSE2 4x" #endif #define BINARY_SIZE 4 #define FORMAT_LABEL "Raw-SHA256-ng" #define FORMAT_NAME "" #define ALGORITHM_NAME "SHA256 " SIMD_TYPE #define VWIDTH SIMD_COEF_32 #define MAXLEN 55 #define PLAINTEXT_LENGTH MAXLEN #define CIPHERTEXT_LENGTH 64 #define DIGEST_SIZE 32 #define _RAWSHA256_H #include "rawSHA256_common.h" #undef _RAWSHA256_H #define SALT_SIZE 0 #define SALT_ALIGN 1 #define MIN_KEYS_PER_CRYPT VWIDTH #define MAX_KEYS_PER_CRYPT VWIDTH #if __SSE4_1__ && !__AVX2__ #undef GATHER #define GATHER(x, y, z) \ { \ x = _mm_cvtsi32_si128( y[index][z] ); \ x = _mm_insert_epi32(x, y[index + 1][z], 1); \ x = _mm_insert_epi32(x, y[index + 2][z], 2); \ x = _mm_insert_epi32(x, y[index + 3][z], 3); \ } #endif #define S0(x) \ ( \ vxor( \ vroti_epi32(x, -22), \ vxor( \ vroti_epi32(x, -2), \ vroti_epi32(x, -13) \ ) \ ) \ ) #define S1(x) \ ( \ vxor( \ vroti_epi32(x, -25), \ vxor( \ vroti_epi32(x, -6), \ vroti_epi32(x, -11) \ ) \ ) \ ) #define s0(x) \ ( \ vxor( \ vsrli_epi32(x, 3), \ vxor( \ vroti_epi32(x, -7), \ vroti_epi32(x, -18) \ ) \ ) \ ) #define s1(x) \ ( \ vxor( \ vsrli_epi32(x, 10), \ vxor( \ vroti_epi32(x, -17), \ vroti_epi32(x, -19) \ ) \ ) \ ) #if !VCMOV_EMULATED #define Maj(x,y,z) vcmov(x, y, vxor(z, y)) #else #define Maj(x,y,z) vor(vand(x, y), vand(vor(x, y), z)) #endif #define Ch(x,y,z) vcmov(y, z, x) #define R(t) \ { \ w[t] = vadd_epi32(s1(w[t - 2]), w[t - 7]); \ w[t] = vadd_epi32(s0(w[t - 15]), w[t]); \ w[t] = vadd_epi32( w[t - 16], w[t]); \ } #define SHA256_STEP(a,b,c,d,e,f,g,h,x,K) \ { \ if (x > 15) R(x); \ tmp1 = vadd_epi32(h, S1(e)); \ tmp1 = vadd_epi32(tmp1, Ch(e,f,g)); \ tmp1 = vadd_epi32(tmp1, vset1_epi32(K)); \ tmp1 = vadd_epi32(tmp1, w[x]); \ tmp2 = vadd_epi32(S0(a),Maj(a,b,c)); \ d = vadd_epi32(tmp1, d); \ h = vadd_epi32(tmp1, tmp2); \ } static uint32_t (*saved_key)[64]; static uint32_t *crypt_key[ 8]; static void init(struct fmt_main *self) { int i; #ifdef _OPENMP int omp_t; 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 saved_key = mem_calloc_align(self->params.max_keys_per_crypt, sizeof(*saved_key), VWIDTH * 4); for (i = 0; i < 8; i++) crypt_key[i] = mem_calloc_align(self->params.max_keys_per_crypt, sizeof(uint32_t), VWIDTH * 4); } static void done(void) { int i; for (i = 0; i < 8; i++) MEM_FREE(crypt_key[i]); MEM_FREE(saved_key); } static int get_hash_0(int index) { return crypt_key[0][index] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_key[0][index] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_key[0][index] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_key[0][index] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_key[0][index] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_key[0][index] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_key[0][index] & PH_MASK_6; } static void set_key(char *key, int index) { uint32_t *buf32 = (uint32_t*) &saved_key[index]; uint8_t *buf8 = (uint8_t*) buf32; int len = 0; while (*key) buf8[len++] = *key++; buf32[15] = len << 3; buf8[len++] = 0x80; while (buf8[len] && len <= MAXLEN) buf8[len++] = 0; } static char *get_key(int index) { uint32_t *buf = (uint32_t*) &saved_key[index]; static char out[MAXLEN + 1]; int len = buf[15] >> 3; memset(out, 0, MAXLEN + 1); memcpy(out, buf, len); return (char*) out; } static int crypt_all(int *pcount, struct db_salt *salt) { int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index += VWIDTH) #endif { vtype a, b, c, d, e, f, g, h; vtype w[64], tmp1, tmp2; int i; #if __SSE4_1__ && !__AVX2__ for (i=0; i < 16; i++) GATHER(w[i], saved_key, i); for (i=0; i < 15; i++) vswap32(w[i]); #else JTR_ALIGN(VWIDTH * 4) uint32_t __w[16][VWIDTH]; int j; for (i=0; i < VWIDTH; i++) for (j=0; j < 16; j++) __w[j][i] = saved_key[index + i][j]; for (i=0; i < 15; i++) { w[i] = vload((vtype*) __w[i]); vswap32(w[i]); } w[15] = vload((vtype*) __w[15]); #endif a = vset1_epi32(0x6a09e667); b = vset1_epi32(0xbb67ae85); c = vset1_epi32(0x3c6ef372); d = vset1_epi32(0xa54ff53a); e = vset1_epi32(0x510e527f); f = vset1_epi32(0x9b05688c); g = vset1_epi32(0x1f83d9ab); h = vset1_epi32(0x5be0cd19); SHA256_STEP(a, b, c, d, e, f, g, h, 0, 0x428a2f98); SHA256_STEP(h, a, b, c, d, e, f, g, 1, 0x71374491); SHA256_STEP(g, h, a, b, c, d, e, f, 2, 0xb5c0fbcf); SHA256_STEP(f, g, h, a, b, c, d, e, 3, 0xe9b5dba5); SHA256_STEP(e, f, g, h, a, b, c, d, 4, 0x3956c25b); SHA256_STEP(d, e, f, g, h, a, b, c, 5, 0x59f111f1); SHA256_STEP(c, d, e, f, g, h, a, b, 6, 0x923f82a4); SHA256_STEP(b, c, d, e, f, g, h, a, 7, 0xab1c5ed5); SHA256_STEP(a, b, c, d, e, f, g, h, 8, 0xd807aa98); SHA256_STEP(h, a, b, c, d, e, f, g, 9, 0x12835b01); SHA256_STEP(g, h, a, b, c, d, e, f, 10, 0x243185be); SHA256_STEP(f, g, h, a, b, c, d, e, 11, 0x550c7dc3); SHA256_STEP(e, f, g, h, a, b, c, d, 12, 0x72be5d74); SHA256_STEP(d, e, f, g, h, a, b, c, 13, 0x80deb1fe); SHA256_STEP(c, d, e, f, g, h, a, b, 14, 0x9bdc06a7); SHA256_STEP(b, c, d, e, f, g, h, a, 15, 0xc19bf174); SHA256_STEP(a, b, c, d, e, f, g, h, 16, 0xe49b69c1); SHA256_STEP(h, a, b, c, d, e, f, g, 17, 0xefbe4786); SHA256_STEP(g, h, a, b, c, d, e, f, 18, 0x0fc19dc6); SHA256_STEP(f, g, h, a, b, c, d, e, 19, 0x240ca1cc); SHA256_STEP(e, f, g, h, a, b, c, d, 20, 0x2de92c6f); SHA256_STEP(d, e, f, g, h, a, b, c, 21, 0x4a7484aa); SHA256_STEP(c, d, e, f, g, h, a, b, 22, 0x5cb0a9dc); SHA256_STEP(b, c, d, e, f, g, h, a, 23, 0x76f988da); SHA256_STEP(a, b, c, d, e, f, g, h, 24, 0x983e5152); SHA256_STEP(h, a, b, c, d, e, f, g, 25, 0xa831c66d); SHA256_STEP(g, h, a, b, c, d, e, f, 26, 0xb00327c8); SHA256_STEP(f, g, h, a, b, c, d, e, 27, 0xbf597fc7); SHA256_STEP(e, f, g, h, a, b, c, d, 28, 0xc6e00bf3); SHA256_STEP(d, e, f, g, h, a, b, c, 29, 0xd5a79147); SHA256_STEP(c, d, e, f, g, h, a, b, 30, 0x06ca6351); SHA256_STEP(b, c, d, e, f, g, h, a, 31, 0x14292967); SHA256_STEP(a, b, c, d, e, f, g, h, 32, 0x27b70a85); SHA256_STEP(h, a, b, c, d, e, f, g, 33, 0x2e1b2138); SHA256_STEP(g, h, a, b, c, d, e, f, 34, 0x4d2c6dfc); SHA256_STEP(f, g, h, a, b, c, d, e, 35, 0x53380d13); SHA256_STEP(e, f, g, h, a, b, c, d, 36, 0x650a7354); SHA256_STEP(d, e, f, g, h, a, b, c, 37, 0x766a0abb); SHA256_STEP(c, d, e, f, g, h, a, b, 38, 0x81c2c92e); SHA256_STEP(b, c, d, e, f, g, h, a, 39, 0x92722c85); SHA256_STEP(a, b, c, d, e, f, g, h, 40, 0xa2bfe8a1); SHA256_STEP(h, a, b, c, d, e, f, g, 41, 0xa81a664b); SHA256_STEP(g, h, a, b, c, d, e, f, 42, 0xc24b8b70); SHA256_STEP(f, g, h, a, b, c, d, e, 43, 0xc76c51a3); SHA256_STEP(e, f, g, h, a, b, c, d, 44, 0xd192e819); SHA256_STEP(d, e, f, g, h, a, b, c, 45, 0xd6990624); SHA256_STEP(c, d, e, f, g, h, a, b, 46, 0xf40e3585); SHA256_STEP(b, c, d, e, f, g, h, a, 47, 0x106aa070); SHA256_STEP(a, b, c, d, e, f, g, h, 48, 0x19a4c116); SHA256_STEP(h, a, b, c, d, e, f, g, 49, 0x1e376c08); SHA256_STEP(g, h, a, b, c, d, e, f, 50, 0x2748774c); SHA256_STEP(f, g, h, a, b, c, d, e, 51, 0x34b0bcb5); SHA256_STEP(e, f, g, h, a, b, c, d, 52, 0x391c0cb3); SHA256_STEP(d, e, f, g, h, a, b, c, 53, 0x4ed8aa4a); SHA256_STEP(c, d, e, f, g, h, a, b, 54, 0x5b9cca4f); SHA256_STEP(b, c, d, e, f, g, h, a, 55, 0x682e6ff3); SHA256_STEP(a, b, c, d, e, f, g, h, 56, 0x748f82ee); SHA256_STEP(h, a, b, c, d, e, f, g, 57, 0x78a5636f); SHA256_STEP(g, h, a, b, c, d, e, f, 58, 0x84c87814); SHA256_STEP(f, g, h, a, b, c, d, e, 59, 0x8cc70208); SHA256_STEP(e, f, g, h, a, b, c, d, 60, 0x90befffa); SHA256_STEP(d, e, f, g, h, a, b, c, 61, 0xa4506ceb); SHA256_STEP(c, d, e, f, g, h, a, b, 62, 0xbef9a3f7); SHA256_STEP(b, c, d, e, f, g, h, a, 63, 0xc67178f2); a = vadd_epi32(a, vset1_epi32(0x6a09e667)); b = vadd_epi32(b, vset1_epi32(0xbb67ae85)); c = vadd_epi32(c, vset1_epi32(0x3c6ef372)); d = vadd_epi32(d, vset1_epi32(0xa54ff53a)); e = vadd_epi32(e, vset1_epi32(0x510e527f)); f = vadd_epi32(f, vset1_epi32(0x9b05688c)); g = vadd_epi32(g, vset1_epi32(0x1f83d9ab)); h = vadd_epi32(h, vset1_epi32(0x5be0cd19)); vstore((vtype*) &crypt_key[0][index], a); vstore((vtype*) &crypt_key[1][index], b); vstore((vtype*) &crypt_key[2][index], c); vstore((vtype*) &crypt_key[3][index], d); vstore((vtype*) &crypt_key[4][index], e); vstore((vtype*) &crypt_key[5][index], f); vstore((vtype*) &crypt_key[6][index], g); vstore((vtype*) &crypt_key[7][index], h); } return count; } static int cmp_all(void *binary, int count) { vtype bin; vtype digest; int i = 0; #ifdef _OPENMP for (i = 0; i < count; i += VWIDTH) #endif { digest = vload((vtype*) &crypt_key[0][i]); bin = vset1_epi32(((uint32_t*) binary)[0]); if (vanyeq_epi32(bin, digest)) return 1; } return 0; } static int cmp_one(void *binary, int index) { return ((uint32_t*) binary)[0] == crypt_key[0][index]; } static int cmp_exact(char *source, int index) { uint32_t *binary = sha256_common_binary(source); int i; for (i = 0; i < 8; i++) if (((uint32_t*) binary)[i] != crypt_key[i][index]) return 0; return 1; } struct fmt_main fmt_rawSHA256_ng = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, MAXLEN, 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 | FMT_SPLIT_UNIFIES_CASE, { NULL }, { HEX_TAG, CISCO_TAG }, sha256_common_tests }, { init, done, fmt_default_reset, sha256_common_prepare, sha256_common_valid, sha256_common_split, sha256_common_binary, fmt_default_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, fmt_default_set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */ #endif /* SIMD_COEF_32 */
file.c
#include <stdio.h> int main(){ #pragma omp parallel { printf("hello openmp!\n"); } return 0; }
collapse-3.c
/* { dg-do run } */ /* { dg-options "-O2 -std=gnu99" } */ #include <string.h> #include <stdlib.h> int main (void) { int i2, l = 0; int a[3][3][3]; memset (a, '\0', sizeof (a)); #pragma omp parallel for collapse(4 - 1) schedule(static, 4) for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) a[i][j][k] = i + j * 4 + k * 16; #pragma omp parallel { #pragma omp for collapse(2) reduction(|:l) for (i2 = 0; i2 < 2; i2++) for (int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) if (a[i2][j][k] != i2 + j * 4 + k * 16) l = 1; } if (l) abort (); return 0; }
clang-313307.c
#include <stdio.h> #include <omp.h> #define SIMPLE_SPMD 0 int main(){ int nthreads_a[3]; int a1_a[4]; #pragma omp target parallel map(tofrom: a1_a, nthreads_a) { a1_a[0] = 1; nthreads_a[0] = 4; } printf("hello %d %d\n", a1_a[0], nthreads_a[0]); if (a1_a[0] != 1 || nthreads_a[0] != 4) return 1; return 0; }
convolution_1x1_fp16s.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2020 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 conv1x1s1_sgemm_transform_kernel_fp16sa_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch) { const float* kernel = _kernel; // interleave kernel_tm.create(8 * 8, inch / 8 + inch % 8, outch / 8 + outch % 8, (size_t)2u, 1); int p = 0; for (; p + 7 < outch; p += 8) { const float* kernel0 = kernel + (p + 0) * inch; const float* kernel1 = kernel + (p + 1) * inch; const float* kernel2 = kernel + (p + 2) * inch; const float* kernel3 = kernel + (p + 3) * inch; const float* kernel4 = kernel + (p + 4) * inch; const float* kernel5 = kernel + (p + 5) * inch; const float* kernel6 = kernel + (p + 6) * inch; const float* kernel7 = kernel + (p + 7) * inch; __fp16* ktmp = kernel_tm.channel(p / 8); for (int q = 0; q < inch; q++) { // kernel0...7 0 ktmp[0] = (__fp16)kernel0[0]; ktmp[1] = (__fp16)kernel1[0]; ktmp[2] = (__fp16)kernel2[0]; ktmp[3] = (__fp16)kernel3[0]; ktmp[4] = (__fp16)kernel4[0]; ktmp[5] = (__fp16)kernel5[0]; ktmp[6] = (__fp16)kernel6[0]; ktmp[7] = (__fp16)kernel7[0]; ktmp += 8; kernel0 += 1; kernel1 += 1; kernel2 += 1; kernel3 += 1; kernel4 += 1; kernel5 += 1; kernel6 += 1; kernel7 += 1; } } for (; p < outch; p++) { const float* kernel0 = kernel + p * inch; __fp16* ktmp = kernel_tm.channel(p / 8 + p % 8); for (int q = 0; q < inch; q++) { ktmp[0] = (__fp16)kernel0[0]; ktmp++; kernel0++; } } } static void conv1x1s1_sgemm_fp16sa_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outch = top_blob.c; const int size = w * h; const __fp16* bias = _bias; // interleave Mat tmp(8 * 8, inch / 8 + inch % 8, size / 8 + size % 8, 2u, opt.workspace_allocator); { int nn_size = size >> 3; int remain_size_start = nn_size << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = ii * 8; const __fp16* img0 = bottom_blob.channel(0); img0 += i; __fp16* tmpptr = tmp.channel(i / 8); for (int q = 0; q < inch; q++) { vst1q_f16(tmpptr, vld1q_f16(img0)); tmpptr += 8; img0 += bottom_blob.cstep; } } #pragma omp parallel for num_threads(opt.num_threads) for (int i = remain_size_start; i < size; i++) { const __fp16* img0 = bottom_blob.channel(0); img0 += i; __fp16* tmpptr = tmp.channel(i / 8 + i % 8); for (int q = 0; q < inch; q++) { tmpptr[0] = img0[0]; tmpptr++; img0 += bottom_blob.cstep; } } } int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 3; remain_outch_start = nn_outch << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 8; __fp16* outptr0 = top_blob.channel(p); __fp16* outptr1 = top_blob.channel(p + 1); __fp16* outptr2 = top_blob.channel(p + 2); __fp16* outptr3 = top_blob.channel(p + 3); __fp16* outptr4 = top_blob.channel(p + 4); __fp16* outptr5 = top_blob.channel(p + 5); __fp16* outptr6 = top_blob.channel(p + 6); __fp16* outptr7 = top_blob.channel(p + 7); const __fp16 zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; const __fp16* biasptr = bias ? bias + p : zeros; float16x8_t _bias0 = vld1q_f16(biasptr); int i = 0; for (; i + 7 < size; i += 8) { const __fp16* tmpptr = tmp.channel(i / 8); const __fp16* kptr = kernel.channel(p / 8); int q = 0; float16x8_t _sum0 = vdupq_laneq_f16(_bias0, 0); float16x8_t _sum1 = vdupq_laneq_f16(_bias0, 1); float16x8_t _sum2 = vdupq_laneq_f16(_bias0, 2); float16x8_t _sum3 = vdupq_laneq_f16(_bias0, 3); float16x8_t _sum4 = vdupq_laneq_f16(_bias0, 4); float16x8_t _sum5 = vdupq_laneq_f16(_bias0, 5); float16x8_t _sum6 = vdupq_laneq_f16(_bias0, 6); float16x8_t _sum7 = vdupq_laneq_f16(_bias0, 7); for (; q + 7 < inch; q += 8) { float16x8_t _p0 = vld1q_f16(tmpptr); float16x8_t _p1 = vld1q_f16(tmpptr + 8); float16x8_t _p2 = vld1q_f16(tmpptr + 16); float16x8_t _p3 = vld1q_f16(tmpptr + 24); float16x8_t _p4 = vld1q_f16(tmpptr + 32); float16x8_t _p5 = vld1q_f16(tmpptr + 40); float16x8_t _p6 = vld1q_f16(tmpptr + 48); float16x8_t _p7 = vld1q_f16(tmpptr + 56); float16x8_t _k0 = vld1q_f16(kptr); float16x8_t _k1 = vld1q_f16(kptr + 8); float16x8_t _k2 = vld1q_f16(kptr + 16); float16x8_t _k3 = vld1q_f16(kptr + 24); float16x8_t _k4 = vld1q_f16(kptr + 32); float16x8_t _k5 = vld1q_f16(kptr + 40); float16x8_t _k6 = vld1q_f16(kptr + 48); float16x8_t _k7 = vld1q_f16(kptr + 56); _sum0 = vfmaq_laneq_f16(_sum0, _p0, _k0, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p0, _k0, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p0, _k0, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p0, _k0, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p0, _k0, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p0, _k0, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p0, _k0, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p0, _k0, 7); _sum0 = vfmaq_laneq_f16(_sum0, _p1, _k1, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p1, _k1, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p1, _k1, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p1, _k1, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p1, _k1, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p1, _k1, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p1, _k1, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p1, _k1, 7); _sum0 = vfmaq_laneq_f16(_sum0, _p2, _k2, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p2, _k2, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p2, _k2, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p2, _k2, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p2, _k2, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p2, _k2, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p2, _k2, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p2, _k2, 7); _sum0 = vfmaq_laneq_f16(_sum0, _p3, _k3, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p3, _k3, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p3, _k3, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p3, _k3, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p3, _k3, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p3, _k3, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p3, _k3, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p3, _k3, 7); _sum0 = vfmaq_laneq_f16(_sum0, _p4, _k4, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p4, _k4, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p4, _k4, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p4, _k4, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p4, _k4, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p4, _k4, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p4, _k4, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p4, _k4, 7); _sum0 = vfmaq_laneq_f16(_sum0, _p5, _k5, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p5, _k5, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p5, _k5, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p5, _k5, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p5, _k5, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p5, _k5, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p5, _k5, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p5, _k5, 7); _sum0 = vfmaq_laneq_f16(_sum0, _p6, _k6, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p6, _k6, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p6, _k6, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p6, _k6, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p6, _k6, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p6, _k6, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p6, _k6, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p6, _k6, 7); _sum0 = vfmaq_laneq_f16(_sum0, _p7, _k7, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p7, _k7, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p7, _k7, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p7, _k7, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p7, _k7, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p7, _k7, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p7, _k7, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p7, _k7, 7); tmpptr += 64; kptr += 64; } for (; q < inch; q++) { float16x8_t _p0 = vld1q_f16(tmpptr); float16x8_t _k0 = vld1q_f16(kptr); _sum0 = vfmaq_laneq_f16(_sum0, _p0, _k0, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p0, _k0, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p0, _k0, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p0, _k0, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p0, _k0, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p0, _k0, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p0, _k0, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p0, _k0, 7); tmpptr += 8; kptr += 8; } vst1q_f16(outptr0, _sum0); vst1q_f16(outptr1, _sum1); vst1q_f16(outptr2, _sum2); vst1q_f16(outptr3, _sum3); vst1q_f16(outptr4, _sum4); vst1q_f16(outptr5, _sum5); vst1q_f16(outptr6, _sum6); vst1q_f16(outptr7, _sum7); outptr0 += 8; outptr1 += 8; outptr2 += 8; outptr3 += 8; outptr4 += 8; outptr5 += 8; outptr6 += 8; outptr7 += 8; } for (; i < size; i++) { const __fp16* tmpptr = tmp.channel(i / 8 + i % 8); const __fp16* kptr = kernel.channel(p / 8); int q = 0; float16x8_t _sum0 = _bias0; for (; q + 7 < inch; q += 8) { float16x8_t _p0 = vld1q_f16(tmpptr); float16x8_t _k0 = vld1q_f16(kptr); float16x8_t _k1 = vld1q_f16(kptr + 8); float16x8_t _k2 = vld1q_f16(kptr + 16); float16x8_t _k3 = vld1q_f16(kptr + 24); float16x8_t _k4 = vld1q_f16(kptr + 32); float16x8_t _k5 = vld1q_f16(kptr + 40); float16x8_t _k6 = vld1q_f16(kptr + 48); float16x8_t _k7 = vld1q_f16(kptr + 56); _sum0 = vfmaq_laneq_f16(_sum0, _k0, _p0, 0); _sum0 = vfmaq_laneq_f16(_sum0, _k1, _p0, 1); _sum0 = vfmaq_laneq_f16(_sum0, _k2, _p0, 2); _sum0 = vfmaq_laneq_f16(_sum0, _k3, _p0, 3); _sum0 = vfmaq_laneq_f16(_sum0, _k4, _p0, 4); _sum0 = vfmaq_laneq_f16(_sum0, _k5, _p0, 5); _sum0 = vfmaq_laneq_f16(_sum0, _k6, _p0, 6); _sum0 = vfmaq_laneq_f16(_sum0, _k7, _p0, 7); tmpptr += 8; kptr += 64; } for (; q < inch; q++) { float16x8_t _p0 = vld1q_dup_f16(tmpptr); float16x8_t _k0 = vld1q_f16(kptr); _sum0 = vfmaq_f16(_sum0, _k0, _p0); tmpptr += 1; kptr += 8; } vst1q_lane_f16(outptr0, _sum0, 0); vst1q_lane_f16(outptr1, _sum0, 1); vst1q_lane_f16(outptr2, _sum0, 2); vst1q_lane_f16(outptr3, _sum0, 3); vst1q_lane_f16(outptr4, _sum0, 4); vst1q_lane_f16(outptr5, _sum0, 5); vst1q_lane_f16(outptr6, _sum0, 6); vst1q_lane_f16(outptr7, _sum0, 7); outptr0++; outptr1++; outptr2++; outptr3++; outptr4++; outptr5++; outptr6++; outptr7++; } } #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 __fp16 bias0 = bias ? bias[p] : 0.f; __fp16* outptr0 = out0; int i = 0; for (; i + 7 < size; i += 8) { const __fp16* tmpptr = tmp.channel(i / 8); const __fp16* kptr = kernel.channel(p / 8 + p % 8); int q = 0; float16x8_t _sum0 = vdupq_n_f16(bias0); for (; q + 7 < inch; q += 8) { float16x8_t _p0 = vld1q_f16(tmpptr); float16x8_t _p1 = vld1q_f16(tmpptr + 8); float16x8_t _p2 = vld1q_f16(tmpptr + 16); float16x8_t _p3 = vld1q_f16(tmpptr + 24); float16x8_t _p4 = vld1q_f16(tmpptr + 32); float16x8_t _p5 = vld1q_f16(tmpptr + 40); float16x8_t _p6 = vld1q_f16(tmpptr + 48); float16x8_t _p7 = vld1q_f16(tmpptr + 56); float16x8_t _k0 = vld1q_f16(kptr); _sum0 = vfmaq_laneq_f16(_sum0, _p0, _k0, 0); _sum0 = vfmaq_laneq_f16(_sum0, _p1, _k0, 1); _sum0 = vfmaq_laneq_f16(_sum0, _p2, _k0, 2); _sum0 = vfmaq_laneq_f16(_sum0, _p3, _k0, 3); _sum0 = vfmaq_laneq_f16(_sum0, _p4, _k0, 4); _sum0 = vfmaq_laneq_f16(_sum0, _p5, _k0, 5); _sum0 = vfmaq_laneq_f16(_sum0, _p6, _k0, 6); _sum0 = vfmaq_laneq_f16(_sum0, _p7, _k0, 7); tmpptr += 64; kptr += 8; } for (; q < inch; q++) { float16x8_t _p0 = vld1q_f16(tmpptr); float16x8_t _k0 = vld1q_dup_f16(kptr); _sum0 = vfmaq_f16(_sum0, _p0, _k0); tmpptr += 8; kptr += 1; } vst1q_f16(outptr0, _sum0); outptr0 += 8; } for (; i < size; i++) { const __fp16* tmpptr = tmp.channel(i / 8 + i % 8); const __fp16* kptr = kernel.channel(p / 8 + p % 8); int q = 0; float16x8_t _sum0 = vdupq_n_f16(0.f); for (; q + 7 < inch; q += 8) { float16x8_t _p0 = vld1q_f16(tmpptr); float16x8_t _k0 = vld1q_f16(kptr); _sum0 = vfmaq_f16(_sum0, _p0, _k0); tmpptr += 8; kptr += 8; } __fp16 sum0 = bias0 + vaddvq_f32(vcvt_f32_f16(vadd_f16(vget_low_f16(_sum0), vget_high_f16(_sum0)))); for (; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = sum0; outptr0++; } } // // NOTE sgemm // for (; p<outch; p++) // { // Mat out0 = top_blob.channel(p); // // const __fp16 bias0 = bias ? bias[p] : 0.f; // // __fp16* outptr0 = out0; // // for (int i=0; i<size; i++) // { // __fp16 sum = bias0; // // const __fp16* kptr = _kernel.channel(p/8 + p%8); // // for (int q=0; q<inch; q++) // { // const __fp16* img0 = bottom_blob.channel(q); // // sum += img0[i] * kptr[0]; // kptr ++; // } // // outptr0[i] = sum; // } // } }
taskdep_if0.c
// RUN: %libomp-compile-and-run // REQUIRES: !abt #include <stdio.h> #include <stdlib.h> #include <omp.h> #include "omp_my_sleep.h" int a = 0; void task1() { my_sleep(0.5); a = 10; } void task2() { a++; } int main(int argc, char** argv) { #pragma omp parallel shared(argc) num_threads(2) { #pragma omp single { #pragma omp task depend(out: a) task1(); #pragma omp task if(0) depend(inout: a) task2(); } } if (a != 11) { fprintf(stderr, "fail: expected 11, but a is %d\n", a); exit(1); } else { printf("pass\n"); } return 0; }
test2.c
#pragma wave trace(enable) int a[100][100]; void foo() { int i,j; int hypre__nx,hypre__ny; #define HYPRE_BOX_SMP_PRIVATE i,j #define HYPRE_SMP_PRIVATE \ HYPRE_BOX_SMP_PRIVATE,hypre__nx,hypre__ny #pragma omp parallel for private (HYPRE_SMP_PRIVATE) for (i=0;i<100; i++) for (j=0;j<100; j++) { hypre__nx =i; hypre__ny=j; a[i][j]=hypre__nx+hypre__ny; } }
hermv_c_csc_u_lo_trans.c
#include "alphasparse/kernel.h" #ifdef _OPENMP #include <omp.h> #endif #include "alphasparse/util.h" #include <memory.h> static alphasparse_status_t hermv_csc_u_lo_trans_unroll(const ALPHA_Number alpha, const ALPHA_SPMAT_CSC *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { // m==n 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 < n; ++i) { ALPHA_INT tid = alpha_get_thread_id(); ALPHA_INT ais = A->cols_start[i]; ALPHA_INT aie = A->cols_end[i]; ALPHA_INT ail = aie - ais; ALPHA_INT start = alpha_lower_bound(&A->row_indx[ais], &A->row_indx[aie], i) - A->row_indx; if(start < aie && A->row_indx[start] == i) start += 1; const ALPHA_INT* A_row = &A->row_indx[ais]; const ALPHA_Number* A_val = &A->values[ais]; ALPHA_INT ai = start - ais ; 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_2c(y_local[tid][ar0], av0, alpha_xi); alpha_madde_2c(y_local[tid][ar1], av1, alpha_xi); alpha_madde_2c(y_local[tid][ar2], av2, alpha_xi); alpha_madde_2c(y_local[tid][ar3], av3, alpha_xi); alpha_mul(tmp, alpha, av0); alpha_madde(y_local[tid][i], tmp, x[ar0]); alpha_mul(tmp, alpha, av1); alpha_madde(y_local[tid][i], tmp, x[ar1]); alpha_mul(tmp, alpha, av2); alpha_madde(y_local[tid][i], tmp, x[ar2]); alpha_mul(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_2c(y_local[tid][ar], av, alpha_xi); alpha_mul(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_lo_trans_unroll(alpha, A, x, beta, y); }
tinyexr.h
/* Copyright (c) 2014 - 2019, 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 ------------------------------------------------- #ifndef TINYEXR_H_ #define TINYEXR_H_ // // // 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 (0) #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 int tiled; // tile format image int long_name; // long name attribute int non_image; // deep image(EXR 2.0) 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 _EXRHeader { float pixel_aspect_ratio; int line_order; int data_window[4]; int display_window[4]; 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; 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) } 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. 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 specifing 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(wll 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); // Initialize EXRHeader struct extern void InitEXRHeader(EXRHeader *exr_header); // Initialize EXRImage struct extern void InitEXRImage(EXRImage *exr_image); // Free's internal data of EXRHeader struct extern int FreeEXRHeader(EXRHeader *exr_header); // Free's internal data of EXRImage struct extern int FreeEXRImage(EXRImage *exr_image); // Free's 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); // 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_DEIFNED #define TINYEXR_IMPLEMENTATION_DEIFNED #include <algorithm> #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <sstream> // #include <iostream> // debug #include <limits> #include <string> #include <vector> #if __cplusplus > 199711L // 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 "source/common/helpers/miniz.h" #endif #if TINYEXR_USE_ZFP #include "zfp.h" #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 occured 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(__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 } #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(reinterpret_cast<unsigned int *>(&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 _ChannelInfo { 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 _HeaderInfo { std::vector<ChannelInfo> channels; std::vector<EXRAttribute> attributes; int data_window[4]; int line_order; int display_window[4]; float screen_window_center[2]; float screen_window_width; float pixel_aspect_ratio; int chunk_count; // Tiled format int tile_size_x; int tile_size_y; int tile_level_mode; int tile_rounding_mode; unsigned int header_len; int compression_type; void clear() { channels.clear(); attributes.clear(); data_window[0] = 0; data_window[1] = 0; data_window[2] = 0; data_window[3] = 0; line_order = 0; display_window[0] = 0; display_window[1] = 0; display_window[2] = 0; display_window[3] = 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 tile_size_x = 0; tile_size_y = 0; tile_level_mode = 0; tile_rounding_mode = 0; header_len = 0; compression_type = 0; } } HeaderInfo; 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(reinterpret_cast<unsigned int *>(&info.pixel_type)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.x_sampling)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&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(reinterpret_cast<unsigned int *>(&pixel_type)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&x_sampling)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&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) { // // Compressable 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) // // Hierachical 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 //------------------------------- int len : 8; // code length 0 int lit : 24; // lit p size 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++ = (unsigned char)(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 == (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 >= (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) { int *p = pl->p; pl->p = new int[pl->lit]; for (int i = 0; i < pl->lit - 1; ++i) pl->p[i] = p[i]; delete[] p; } else { pl->p = new 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) | *(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)) & (((long long)(1) << 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 = (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 = (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; int precision; double tolerance; int type; // TINYEXR_ZFP_COMPRESSIONTYPE_* ZFPCompressionParam() { type = TINYEXR_ZFP_COMPRESSIONTYPE_RATE; rate = 2.0; precision = 0; tolerance = 0.0f; } }; bool FindZFPCompressionParam(ZFPCompressionParam *param, const EXRAttribute *attributes, int num_attributes) { bool foundType = false; for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionType") == 0) && (attributes[i].size == 1)) { param->type = static_cast<int>(attributes[i].value[0]); foundType = true; } } if (!foundType) { 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; } } } 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; } } } 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; } } } else { assert(0); } return false; } // Assume pixel format is FLOAT for all channels. static bool DecompressZfp(float *dst, int dst_width, int dst_num_lines, int num_channels, const unsigned char *src, unsigned long src_size, const ZFPCompressionParam &param) { size_t uncompressed_size = dst_width * 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 ((dst_width & 3U) || (dst_num_lines & 3U)) { return false; } field = zfp_field_2d(reinterpret_cast<void *>(const_cast<unsigned char *>(src)), zfp_type_float, dst_width, dst_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, /* dimention */ 2, /* write random access */ 0); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { zfp_stream_set_precision(zfp, param.precision, zfp_type_float); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float); } 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 = dst_width * dst_num_lines; for (int c = 0; c < num_channels; c++) { // decompress 4x4 pixel block. for (int y = 0; y < dst_num_lines; y += 4) { for (int x = 0; x < dst_width; x += 4) { float fblock[16]; zfp_decode_block_float_2(zfp, fblock); for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { dst[c * image_size + ((y + j) * 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. 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 ((width & 3U) || (num_lines & 3U)) { return false; } // create input array. field = zfp_field_2d(reinterpret_cast<void *>(const_cast<float *>(inPtr)), zfp_type_float, width, 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, zfp_type_float); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float); } 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 = width * num_lines; for (int c = 0; c < num_channels; c++) { // compress 4x4 pixel block. for (int y = 0; y < num_lines; y += 4) { for (int x = 0; x < width; x += 4) { float fblock[16]; for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { fblock[j * 4 + i] = inPtr[c * image_size + ((y + j) * width + (x + i))]; } } zfp_encode_block_float_2(zfp, fblock); } } } zfp_stream_flush(zfp); (*outSize) = zfp_stream_compressed_size(zfp); zfp_stream_close(zfp); return true; } #endif // // ----------------------------------------------------------------- // // 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; if (!FindZFPCompressionParam(&zfp_compression_param, attributes, num_attributes)) { 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) { assert(tile_offset_x * tile_size_x < data_width); assert(tile_offset_y * tile_size_y < data_height); // 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; } 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; info->data_window[0] = 0; info->data_window[1] = 0; info->data_window[2] = 0; info->data_window[3] = 0; info->line_order = 0; // @fixme info->display_window[0] = 0; info->display_window[1] = 0; info->display_window[2] = 0; info->display_window[3] = 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->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; if (version->tiled && 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); 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; } 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[0], &data.at(0), sizeof(int)); memcpy(&info->data_window[1], &data.at(4), sizeof(int)); memcpy(&info->data_window[2], &data.at(8), sizeof(int)); memcpy(&info->data_window[3], &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[3])); has_data_window = true; } } else if (attr_name.compare("displayWindow") == 0) { if (data.size() >= 16) { memcpy(&info->display_window[0], &data.at(0), sizeof(int)); memcpy(&info->display_window[1], &data.at(4), sizeof(int)); memcpy(&info->display_window[2], &data.at(8), sizeof(int)); memcpy(&info->display_window[3], &data.at(12), sizeof(int)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[1])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[2])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[3])); 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( reinterpret_cast<unsigned int *>(&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( reinterpret_cast<unsigned int *>(&info->screen_window_center[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&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( reinterpret_cast<unsigned int *>(&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(reinterpret_cast<unsigned int *>(&info->chunk_count)); } } 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 (!(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[0] = info.display_window[0]; exr_header->display_window[1] = info.display_window[1]; exr_header->display_window[2] = info.display_window[2]; exr_header->display_window[3] = info.display_window[3]; exr_header->data_window[0] = info.data_window[0]; exr_header->data_window[1] = info.data_window[1]; exr_header->data_window[2] = info.data_window[2]; exr_header->data_window[3] = info.data_window[3]; exr_header->line_order = info.line_order; exr_header->compression_type = info.compression_type; 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; 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 poiner exr_header->custom_attributes[i].value = info.attributes[i].value; } } else { exr_header->custom_attributes = NULL; } exr_header->header_len = info.header_len; } static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header, const std::vector<tinyexr::tinyexr_uint64> &offsets, 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; } int data_width = exr_header->data_window[2] - exr_header->data_window[0] + 1; int data_height = exr_header->data_window[3] - exr_header->data_window[1] + 1; if ((data_width < 0) || (data_height < 0)) { if (err) { std::stringstream ss; ss << "Invalid data width or data height: " << data_width << ", " << data_height << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } // Do not allow too large data_width and data_height. header invalid? { const int threshold = 1024 * 8192; // heuristics if ((data_width > threshold) || (data_height > 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; } } 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; } bool invalid_data = false; // TODO(LTE): Use atomic lock for MT safety. 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; } size_t num_tiles = offsets.size(); // = # of blocks exr_image->tiles = static_cast<EXRTile *>( calloc(sizeof(EXRTile), static_cast<size_t>(num_tiles))); int err_code = TINYEXR_SUCCESS; #if (__cplusplus > 199711L) && (TINYEXR_USE_THREAD > 0) std::vector<std::thread> workers; std::atomic<size_t> 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([&]() { size_t tile_idx = 0; while ((tile_idx = tile_count++) < num_tiles) { #else for (size_t 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); // 16 byte: tile coordinates // 4 byte : data size // ~ : data(uncompressed or compressed) if (offsets[tile_idx] + sizeof(int) * 5 > size) { // TODO(LTE): atomic if (err) { (*err) += "Insufficient data size.\n"; } err_code = TINYEXR_ERROR_INVALID_DATA; break; } size_t data_size = size_t(size - (offsets[tile_idx] + sizeof(int) * 5)); const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[tile_idx]); int tile_coordinates[4]; memcpy(tile_coordinates, data_ptr, sizeof(int) * 4); tinyexr::swap4( reinterpret_cast<unsigned int *>(&tile_coordinates[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&tile_coordinates[1])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&tile_coordinates[2])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&tile_coordinates[3])); // @todo{ LoD } if (tile_coordinates[2] != 0) { err_code = TINYEXR_ERROR_UNSUPPORTED_FEATURE; break; } if (tile_coordinates[3] != 0) { err_code = TINYEXR_ERROR_UNSUPPORTED_FEATURE; break; } int data_len; memcpy(&data_len, data_ptr + 16, sizeof(int)); // 16 = sizeof(tile_coordinates) tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (data_len < 4 || size_t(data_len) > data_size) { // TODO(LTE): atomic if (err) { (*err) += "Insufficient data length.\n"; } err_code = TINYEXR_ERROR_INVALID_DATA; break; } // 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, data_width, data_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) { // TODO(LTE): atomic if (err) { (*err) += "Failed to decode tile data.\n"; } err_code = TINYEXR_ERROR_INVALID_DATA; } 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 (__cplusplus > 199711L) && (TINYEXR_USE_THREAD > 0) } })); } // num_thread loop for (auto &t : workers) { t.join(); } #else } #endif if (err_code != TINYEXR_SUCCESS) { return err_code; } exr_image->num_tiles = static_cast<int>(num_tiles); } 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 (__cplusplus > 199711L) && (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(reinterpret_cast<unsigned int *>(&line_no)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&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[3] + 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[1]); 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[1]; } 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 (__cplusplus > 199711L) && (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(reinterpret_cast<unsigned int *>(&y)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); (*offsets)[i] = offset; marker += data_len + 8; // 8 = 4 bytes(y) + 4 bytes(data_len) } return true; } 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; } int data_width = exr_header->data_window[2] - exr_header->data_window[0]; if (data_width >= std::numeric_limits<int>::max()) { // Issue 63 tinyexr::SetErrorMessage("Invalid data width value", err); return TINYEXR_ERROR_INVALID_DATA; } data_width++; int data_height = exr_header->data_window[3] - exr_header->data_window[1]; if (data_height >= std::numeric_limits<int>::max()) { tinyexr::SetErrorMessage("Invalid data height value", err); return TINYEXR_ERROR_INVALID_DATA; } data_height++; if ((data_width < 0) || (data_height < 0)) { tinyexr::SetErrorMessage("data width or data height is negative.", err); return TINYEXR_ERROR_INVALID_DATA; } // Do not allow too large data_width and data_height. header invalid? { const int threshold = 1024 * 8192; // heuristics if (data_width > threshold) { tinyexr::SetErrorMessage("data width too large.", err); return TINYEXR_ERROR_INVALID_DATA; } if (data_height > threshold) { tinyexr::SetErrorMessage("data height too large.", err); return TINYEXR_ERROR_INVALID_DATA; } } // Read offset tables. size_t num_blocks = 0; if (exr_header->chunk_count > 0) { // Use `chunkCount` attribute. num_blocks = static_cast<size_t>(exr_header->chunk_count); } else if (exr_header->tiled) { // @todo { LoD } size_t num_x_tiles = static_cast<size_t>(data_width) / static_cast<size_t>(exr_header->tile_size_x); if (num_x_tiles * static_cast<size_t>(exr_header->tile_size_x) < static_cast<size_t>(data_width)) { num_x_tiles++; } size_t num_y_tiles = static_cast<size_t>(data_height) / static_cast<size_t>(exr_header->tile_size_y); if (num_y_tiles * static_cast<size_t>(exr_header->tile_size_y) < static_cast<size_t>(data_height)) { num_y_tiles++; } num_blocks = num_x_tiles * num_y_tiles; } 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++; } } std::vector<tinyexr::tinyexr_uint64> offsets(num_blocks); 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, offsets, 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 * 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)[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); // transfoer `tiled` from version. exr_header->tiled = version->tiled; 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; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *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); } size_t SaveEXRImageToMemory(const EXRImage *exr_image, const EXRHeader *exr_header, unsigned char **memory_out, const char **err) { if (exr_image == NULL || memory_out == NULL || exr_header->compression_type < 0) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToMemory", err); return 0; } #if !TINYEXR_USE_PIZ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { tinyexr::SetErrorMessage("PIZ compression is not supported in this build", err); return 0; } #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 0; } #endif #if TINYEXR_USE_ZFP for (size_t i = 0; i < static_cast<size_t>(exr_header->num_channels); i++) { if (exr_header->requested_pixel_types[i] != TINYEXR_PIXELTYPE_FLOAT) { tinyexr::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, scanline. { char marker[] = {2, 0, 0, 0}; /* @todo if (exr_header->tiled) { marker[1] |= 0x2; } if (exr_header->long_name) { marker[1] |= 0x4; } if (exr_header->non_image) { marker[1] |= 0x8; } if (exr_header->multipart) { marker[1] |= 0x10; } */ memory.insert(memory.end(), marker, marker + 4); } int num_scanlines = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanlines = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanlines = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanlines = 16; } // Write attributes. std::vector<tinyexr::ChannelInfo> channels; { std::vector<unsigned char> data; for (int c = 0; c < exr_header->num_channels; c++) { tinyexr::ChannelInfo info; info.p_linear = 0; info.pixel_type = exr_header->requested_pixel_types[c]; info.x_sampling = 1; info.y_sampling = 1; info.name = std::string(exr_header->channels[c].name); channels.push_back(info); } tinyexr::WriteChannelInfo(data, channels); tinyexr::WriteAttributeToMemory(&memory, "channels", "chlist", &data.at(0), static_cast<int>(data.size())); } { int comp = exr_header->compression_type; tinyexr::swap4(reinterpret_cast<unsigned int *>(&comp)); tinyexr::WriteAttributeToMemory( &memory, "compression", "compression", reinterpret_cast<const unsigned char *>(&comp), 1); } { int data[4] = {0, 0, exr_image->width - 1, exr_image->height - 1}; tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[3])); tinyexr::WriteAttributeToMemory( &memory, "dataWindow", "box2i", reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4); tinyexr::WriteAttributeToMemory( &memory, "displayWindow", "box2i", reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4); } { unsigned char line_order = 0; // @fixme { read line_order from EXRHeader } tinyexr::WriteAttributeToMemory(&memory, "lineOrder", "lineOrder", &line_order, 1); } { float aspectRatio = 1.0f; tinyexr::swap4(reinterpret_cast<unsigned int *>(&aspectRatio)); tinyexr::WriteAttributeToMemory( &memory, "pixelAspectRatio", "float", reinterpret_cast<const unsigned char *>(&aspectRatio), sizeof(float)); } { float center[2] = {0.0f, 0.0f}; tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[1])); tinyexr::WriteAttributeToMemory( &memory, "screenWindowCenter", "v2f", reinterpret_cast<const unsigned char *>(center), 2 * sizeof(float)); } { float w = static_cast<float>(exr_image->width); tinyexr::swap4(reinterpret_cast<unsigned int *>(&w)); tinyexr::WriteAttributeToMemory(&memory, "screenWindowWidth", "float", reinterpret_cast<const unsigned char *>(&w), sizeof(float)); } // Custom attributes if (exr_header->num_custom_attributes > 0) { for (int i = 0; i < exr_header->num_custom_attributes; i++) { tinyexr::WriteAttributeToMemory( &memory, exr_header->custom_attributes[i].name, exr_header->custom_attributes[i].type, reinterpret_cast<const unsigned char *>( exr_header->custom_attributes[i].value), exr_header->custom_attributes[i].size); } } { // end of header unsigned char e = 0; memory.push_back(e); } int num_blocks = exr_image->height / num_scanlines; if (num_blocks * num_scanlines < exr_image->height) { num_blocks++; } std::vector<tinyexr::tinyexr_uint64> offsets(static_cast<size_t>(num_blocks)); size_t headerSize = memory.size(); tinyexr::tinyexr_uint64 offset = headerSize + static_cast<size_t>(num_blocks) * sizeof( tinyexr::tinyexr_int64); // sizeof(header) + sizeof(offsetTable) std::vector<std::vector<unsigned char> > data_list( static_cast<size_t>(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); } } #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; // Use ZFP compression parameter from custom attributes(if such a parameter // exists) { bool ret = tinyexr::FindZFPCompressionParam( &zfp_compression_param, exr_header->custom_attributes, exr_header->num_custom_attributes); if (!ret) { // Use predefined compression parameter. zfp_compression_param.type = 0; zfp_compression_param.rate = 2; } } #endif // TOOD(LTE): C++11 thread // 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_blocks; i++) { size_t ii = static_cast<size_t>(i); int start_y = num_scanlines * i; int endY = (std::min)(num_scanlines * (i + 1), exr_image->height); int h = endY - start_y; std::vector<unsigned char> buf( static_cast<size_t>(exr_image->width * h * pixel_data_size)); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < h; y++) { // Assume increasing Y float *line_ptr = reinterpret_cast<float *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { tinyexr::FP16 h16; h16.u = reinterpret_cast<unsigned short **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::FP32 f32 = half_to_float(h16); tinyexr::swap4(reinterpret_cast<unsigned int *>(&f32.f)); // line_ptr[x] = f32.f; tinyexr::cpy4(line_ptr + x, &(f32.f)); } } } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < h; y++) { // Assume increasing Y unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &buf.at(static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { unsigned short val = reinterpret_cast<unsigned short **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap2(&val); // line_ptr[x] = val; tinyexr::cpy2(line_ptr + x, &val); } } } else { assert(0); } } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < h; y++) { // Assume increasing Y unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &buf.at(static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { tinyexr::FP32 f32; f32.f = reinterpret_cast<float **>( exr_image->images)[c][(y + start_y) * exr_image->width + 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 (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < h; y++) { // Assume increasing Y float *line_ptr = reinterpret_cast<float *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { float val = reinterpret_cast<float **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); // line_ptr[x] = val; tinyexr::cpy4(line_ptr + x, &val); } } } else { assert(0); } } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_UINT) { for (int y = 0; y < h; y++) { // Assume increasing Y unsigned int *line_ptr = reinterpret_cast<unsigned int *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { unsigned int val = reinterpret_cast<unsigned int **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap4(&val); // line_ptr[x] = val; tinyexr::cpy4(line_ptr + x, &val); } } } } if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_NONE) { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(buf.size()); memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), buf.begin(), buf.begin() + data_len); } else if ((exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (exr_header->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) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(outSize); // truncate memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); } else if (exr_header->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) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(outSize); // truncate memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); } else if (exr_header->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, exr_image->width, h); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = outSize; memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP std::vector<unsigned char> block; unsigned int outSize; tinyexr::CompressZfp( &block, &outSize, reinterpret_cast<const float *>(&buf.at(0)), exr_image->width, h, exr_header->num_channels, zfp_compression_param); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = outSize; memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else { assert(0); } } // omp parallel 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(); } size_t totalSize = static_cast<size_t>(offset); { memory.insert( memory.end(), reinterpret_cast<unsigned char *>(&offsets.at(0)), reinterpret_cast<unsigned char *>(&offsets.at(0)) + sizeof(tinyexr::tinyexr_uint64) * static_cast<size_t>(num_blocks)); } if (memory.size() == 0) { tinyexr::SetErrorMessage("Output memory size is zero", err); return 0; } (*memory_out) = static_cast<unsigned char *>(malloc(totalSize)); memcpy((*memory_out), &memory.at(0), memory.size()); unsigned char *memory_ptr = *memory_out + memory.size(); for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) { memcpy(memory_ptr, &data_list[i].at(0), data_list[i].size()); memory_ptr += data_list[i].size(); } return totalSize; // OK } 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 #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "wb"); #else FILE *fp = fopen(filename, "wb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot write a file", 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; } 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 _MSC_VER FILE *fp = NULL; errno_t errcode = fopen_s(&fp, filename, "rb"); if ((0 != errcode) || (!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(reinterpret_cast<unsigned int *>(&dx)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dy)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dw)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&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(reinterpret_cast<unsigned int *>(&x)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&y)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&w)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&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(reinterpret_cast<unsigned int *>(&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->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); } return TINYEXR_SUCCESS; } int FreeEXRImage(EXRImage *exr_image) { if (exr_image == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } 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; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *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))); ConvertHeader(exr_header, infos[i]); // transfoer `tiled` from version. exr_header->tiled = exr_version->tiled; (*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; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *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; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *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<std::vector<tinyexr::tinyexr_uint64> > chunk_offset_table_list; for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) { std::vector<tinyexr::tinyexr_uint64> offset_table( static_cast<size_t>(exr_headers[i]->chunk_count)); 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; } chunk_offset_table_list.push_back(offset_table); } // Decode image. for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) { std::vector<tinyexr::tinyexr_uint64> &offset_table = chunk_offset_table_list[i]; // First check 'part number' is identitical to 'i' for (size_t c = 0; c < offset_table.size(); c++) { const unsigned char *part_number_addr = memory + offset_table[c] - 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_table, 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; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *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_DEIFNED #endif // TINYEXR_IMPLEMENTATION
mapper_utilities.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Philipp Bucher, Jordi Cotela // // See Master-Thesis P.Bucher // "Development and Implementation of a Parallel // Framework for Non-Matching Grid Mapping" #if !defined(KRATOS_MAPPER_UTILITIES_H_INCLUDED) #define KRATOS_MAPPER_UTILITIES_H_INCLUDED // System includes // External includes // Project includes #include "includes/model_part.h" #include "custom_utilities/mapper_flags.h" #include "custom_utilities/mapper_local_system.h" namespace Kratos { namespace MapperUtilities { typedef std::size_t SizeType; typedef std::size_t IndexType; typedef Node<3> NodeType; typedef Kratos::unique_ptr<MapperInterfaceInfo> MapperInterfaceInfoUniquePointerType; typedef Kratos::shared_ptr<MapperInterfaceInfo> MapperInterfaceInfoPointerType; typedef std::vector<std::vector<MapperInterfaceInfoPointerType>> MapperInterfaceInfoPointerVectorType; typedef Kratos::unique_ptr<MapperLocalSystem> MapperLocalSystemPointer; typedef std::vector<MapperLocalSystemPointer> MapperLocalSystemPointerVector; typedef Kratos::shared_ptr<MapperLocalSystemPointerVector> MapperLocalSystemPointerVectorPointer; template< class TVarType > static void FillFunction(const NodeType& rNode, const TVarType& rVariable, double& rValue) { rValue = rNode.FastGetSolutionStepValue(rVariable); } template< class TVarType > static void FillFunctionNonHist(const NodeType& rNode, const TVarType& rVariable, double& rValue) { rValue = rNode.GetValue(rVariable); } template< class TVarType > static std::function<void(const NodeType&, const TVarType&, double&)> GetFillFunction(const Kratos::Flags& rMappingOptions) { if (rMappingOptions.Is(MapperFlags::FROM_NON_HISTORICAL)) return &FillFunctionNonHist<TVarType>; return &FillFunction<TVarType>; } template< class TVarType > static void UpdateFunction(NodeType& rNode, const TVarType& rVariable, const double Value, const double Factor) { rNode.FastGetSolutionStepValue(rVariable) = Value * Factor; } template< class TVarType > static void UpdateFunctionWithAdd(NodeType& rNode, const TVarType& rVariable, const double Value, const double Factor) { rNode.FastGetSolutionStepValue(rVariable) += Value * Factor; } template< class TVarType > static void UpdateFunctionNonHist(NodeType& rNode, const TVarType& rVariable, const double Value, const double Factor) { rNode.GetValue(rVariable) = Value * Factor; } template< class TVarType > static void UpdateFunctionNonHistWithAdd(NodeType& rNode, const TVarType& rVariable, const double Value, const double Factor) { rNode.GetValue(rVariable) += Value * Factor; } template< class TVarType > static std::function<void(NodeType&, const TVarType&, const double, const double)> GetUpdateFunction(const Kratos::Flags& rMappingOptions) { if (rMappingOptions.Is(MapperFlags::ADD_VALUES) && rMappingOptions.Is(MapperFlags::TO_NON_HISTORICAL)) return &UpdateFunctionNonHistWithAdd<TVarType>; if (rMappingOptions.Is(MapperFlags::ADD_VALUES)) return &UpdateFunctionWithAdd<TVarType>; if (rMappingOptions.Is(MapperFlags::TO_NON_HISTORICAL)) return &UpdateFunctionNonHist<TVarType>; return &UpdateFunction<TVarType>; } template< class TVectorType, class TVarType > void UpdateSystemVectorFromModelPart(TVectorType& rVector, ModelPart& rModelPart, const TVarType& rVariable, const Kratos::Flags& rMappingOptions) { // Here we construct a function pointer to not have the if all the time inside the loop const auto fill_fct = MapperUtilities::GetFillFunction<TVarType>(rMappingOptions); const int num_local_nodes = rModelPart.GetCommunicator().LocalMesh().NumberOfNodes(); const auto nodes_begin = rModelPart.GetCommunicator().LocalMesh().NodesBegin(); #pragma omp parallel for for (int i=0; i<num_local_nodes; i++) { fill_fct(*(nodes_begin + i), rVariable, rVector[i]); } } template< class TVectorType, class TVarType > void UpdateModelPartFromSystemVector(const TVectorType& rVector, ModelPart& rModelPart, const TVarType& rVariable, const Kratos::Flags& rMappingOptions) { const double factor = rMappingOptions.Is(MapperFlags::SWAP_SIGN) ? -1.0 : 1.0; // Here we construct a function pointer to not have the if all the time inside the loop const auto update_fct = std::bind(MapperUtilities::GetUpdateFunction<TVarType>(rMappingOptions), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, factor); const int num_local_nodes = rModelPart.GetCommunicator().LocalMesh().NumberOfNodes(); const auto nodes_begin = rModelPart.GetCommunicator().LocalMesh().NodesBegin(); #pragma omp parallel for for (int i=0; i<num_local_nodes; i++) { update_fct(*(nodes_begin + i), rVariable, rVector[i]); } } /** * @brief Assigning INTERFACE_EQUATION_IDs to the nodes, with and without MPI * This function assigns the INTERFACE_EQUATION_IDs to the nodes, which * act as EquationIds for the MappingMatrix. This work with and without MPI, * in MPI a ScanSum is performed with the local number of nodes * @param rModelPartCommunicator The Modelpart-Communicator to be used * @author Philipp Bucher */ void AssignInterfaceEquationIds(Communicator& rModelPartCommunicator); template<class TMapperLocalSystem> void CreateMapperLocalSystemsFromNodes(const Communicator& rModelPartCommunicator, std::vector<Kratos::unique_ptr<MapperLocalSystem>>& rLocalSystems) { const std::size_t num_nodes = rModelPartCommunicator.LocalMesh().NumberOfNodes(); const auto nodes_ptr_begin = rModelPartCommunicator.LocalMesh().Nodes().ptr_begin(); if (rLocalSystems.size() != num_nodes) { rLocalSystems.resize(num_nodes); } #pragma omp parallel for for (int i = 0; i< static_cast<int>(num_nodes); ++i) { auto it_node = nodes_ptr_begin + i; rLocalSystems[i] = Kratos::make_unique<TMapperLocalSystem>((*it_node).get()); } int num_local_systems = rModelPartCommunicator.GetDataCommunicator().SumAll((int)(rLocalSystems.size())); // int bcs of MPI KRATOS_ERROR_IF_NOT(num_local_systems > 0) << "No mapper local systems were created" << std::endl; } inline int ComputeNumberOfNodes(ModelPart& rModelPart) { int num_nodes = rModelPart.GetCommunicator().LocalMesh().NumberOfNodes(); return rModelPart.GetCommunicator().GetDataCommunicator().SumAll(num_nodes); // Compute the sum among the partitions } inline int ComputeNumberOfConditions(ModelPart& rModelPart) { int num_conditions = rModelPart.GetCommunicator().LocalMesh().NumberOfConditions(); return rModelPart.GetCommunicator().GetDataCommunicator().SumAll(num_conditions); // Compute the sum among the partitions } inline int ComputeNumberOfElements(ModelPart& rModelPart) { int num_elements = rModelPart.GetCommunicator().LocalMesh().NumberOfElements(); return rModelPart.GetCommunicator().GetDataCommunicator().SumAll(num_elements); // Compute the sum among the partitions } template <class T1, class T2> inline double ComputeDistance(const T1& rCoords1, const T2& rCoords2) { return std::sqrt( std::pow(rCoords1[0] - rCoords2[0] , 2) + std::pow(rCoords1[1] - rCoords2[1] , 2) + std::pow(rCoords1[2] - rCoords2[2] , 2) ); } template <typename T> inline double ComputeMaxEdgeLengthLocal(const T& rEntityContainer) { double max_element_size = 0.0; // Loop through each edge of a geometrical entity ONCE for (const auto& r_entity : rEntityContainer) { for (std::size_t i = 0; i < (r_entity.GetGeometry().size() - 1); ++i) { for (std::size_t j = i + 1; j < r_entity.GetGeometry().size(); ++j) { double edge_length = ComputeDistance(r_entity.GetGeometry()[i].Coordinates(), r_entity.GetGeometry()[j].Coordinates()); max_element_size = std::max(max_element_size, edge_length); } } } return max_element_size; } inline double ComputeMaxEdgeLengthLocal(const ModelPart::NodesContainerType& rNodes) { double max_element_size = 0.0; // TODO modify loop such that it loop only once over the nodes for (const auto& r_node_1 : rNodes) { for (const auto& r_node_2 : rNodes) { double edge_length = ComputeDistance(r_node_1.Coordinates(), r_node_2.Coordinates()); max_element_size = std::max(max_element_size, edge_length); } } return max_element_size; } double ComputeSearchRadius(ModelPart& rModelPart, int EchoLevel); inline double ComputeSearchRadius(ModelPart& rModelPart1, ModelPart& rModelPart2, const int EchoLevel) { double search_radius = std::max(ComputeSearchRadius(rModelPart1, EchoLevel), ComputeSearchRadius(rModelPart2, EchoLevel)); KRATOS_INFO_IF("Mapper", EchoLevel > 0) << "Computed search-radius: " << search_radius << std::endl; return search_radius; } void CheckInterfaceModelParts(const int CommRank); std::vector<double> ComputeLocalBoundingBox(ModelPart& rModelPart); void ComputeBoundingBoxesWithTolerance(const std::vector<double>& rBoundingBoxes, const double Tolerance, std::vector<double>& rBoundingBoxesWithTolerance); std::string BoundingBoxStringStream(const std::vector<double>& rBoundingBox); bool PointIsInsideBoundingBox(const std::vector<double>& rBoundingBox, const array_1d<double, 3>& rCoords); void FillBufferBeforeLocalSearch(const MapperLocalSystemPointerVector& rMapperLocalSystems, const std::vector<double>& rBoundingBoxes, const SizeType BufferSizeEstimate, std::vector<std::vector<double>>& rSendBuffer, std::vector<int>& rSendSizes); void CreateMapperInterfaceInfosFromBuffer(const std::vector<std::vector<double>>& rRecvBuffer, const MapperInterfaceInfoUniquePointerType& rpRefInterfaceInfo, const int CommRank, MapperInterfaceInfoPointerVectorType& rMapperInterfaceInfosContainer); void FillBufferAfterLocalSearch(MapperInterfaceInfoPointerVectorType& rMapperInterfaceInfosContainer, const MapperInterfaceInfoUniquePointerType& rpRefInterfaceInfo, const int CommRank, std::vector<std::vector<char>>& rSendBuffer, std::vector<int>& rSendSizes); void AssignInterfaceInfosAfterRemoteSearch(const MapperInterfaceInfoPointerVectorType& rMapperInterfaceInfosContainer, MapperLocalSystemPointerVectorPointer& rpMapperLocalSystems); void DeserializeMapperInterfaceInfosFromBuffer( const std::vector<std::vector<char>>& rSendBuffer, const MapperInterfaceInfoUniquePointerType& rpRefInterfaceInfo, const int CommRank, MapperInterfaceInfoPointerVectorType& rMapperInterfaceInfosContainer); /** * @class MapperInterfaceInfoSerializer * @ingroup MappingApplication * @brief Helper class to serialize/deserialize a vector containing MapperInterfaceInfos * @details This class serializes the vector containing the MapperInterfaceInfos (Shared Ptrs) * The goal of this class is to have a more efficient/faster implementation than the * one of the Serializer by avoiding the casting that is done in the serializer when pointers * are serialized * @TODO test the performance against the Serializer * @author Philipp Bucher */ class MapperInterfaceInfoSerializer { public: MapperInterfaceInfoSerializer(std::vector<MapperInterfaceInfoPointerType>& rMapperInterfaceInfosContainer, const MapperInterfaceInfoUniquePointerType& rpRefInterfaceInfo) : mrInterfaceInfos(rMapperInterfaceInfosContainer) , mrpRefInterfaceInfo(rpRefInterfaceInfo->Create()) { } private: std::vector<MapperInterfaceInfoPointerType>& mrInterfaceInfos; MapperInterfaceInfoPointerType mrpRefInterfaceInfo; friend class Kratos::Serializer; // Adding "Kratos::" is nedded bcs of the "MapperUtilities"-namespace virtual void save(Kratos::Serializer& rSerializer) const; virtual void load(Kratos::Serializer& rSerializer); }; } // namespace MapperUtilities. } // namespace Kratos. #endif // KRATOS_MAPPER_UTILITIES_H_INCLUDED defined
familytree_par.c
#include "familytree.h" #include <omp.h> int par_traverse(tree *node) { if (node == NULL) return 0; int father_iq, mother_iq; #pragma omp task shared(father_iq) father_iq = par_traverse(node->father); //#pragma omp task shared(mother_iq) mother_iq = par_traverse(node->mother); #pragma omp taskwait node->IQ = compute_IQ(node->data, father_iq, mother_iq); genius[node->id] = node->IQ; return node->IQ; } int traverse(tree *node, int numThreads){ omp_set_num_threads(numThreads); #pragma omp parallel { #pragma omp single par_traverse(node); } return node->IQ; }
hermm_c_dia_n_lo_row_trans.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" #ifdef _OPENMP #include <omp.h> #endif #include <memory.h> #include <stdlib.h> alphasparse_status_t ONAME(const ALPHA_Complex alpha, const ALPHA_SPMAT_DIA *mat, const ALPHA_Complex *x, const ALPHA_INT columns, const ALPHA_INT ldx, const ALPHA_Complex beta, ALPHA_Complex *y, const ALPHA_INT ldy) { ALPHA_INT num_threads = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for (ALPHA_INT r = 0; r < mat->rows; r++) for(ALPHA_INT c = 0; c < columns; c++) alpha_mul(y[index2(r,c,ldy)],y[index2(r,c,ldy)],beta); #ifdef _OPENMP #pragma omp parallel num_threads(num_threads) #endif { ALPHA_INT tid = alpha_get_thread_id(); ALPHA_INT bcl = cross_block_low(tid,num_threads,columns); ALPHA_INT bch = cross_block_high(tid,num_threads,columns); for(ALPHA_INT di = 0; di < mat->ndiag;++di){ ALPHA_INT d = mat->distance[di]; if(d < 0){ ALPHA_INT ars = alpha_max(0,-d); ALPHA_INT acs = alpha_max(0,d); ALPHA_INT an = alpha_min(mat->rows - ars,mat->cols - acs); for(ALPHA_INT i = 0; i < an; ++i){ ALPHA_INT ar = ars + i; ALPHA_INT ac = acs + i; ALPHA_Complex val,val_c; alpha_mul(val,mat->values[index2(di,ar,mat->lval)],alpha); alpha_mul_2c(val_c,mat->values[index2(di,ar,mat->lval)],alpha); for(ALPHA_INT bc = bcl;bc < bch;++bc){ alpha_madde(y[index2(ar,bc,ldy)],val_c,x[index2(ac,bc,ldx)]); alpha_madde(y[index2(ac,bc,ldy)],val,x[index2(ar,bc,ldx)]); } } } if(d == 0){ for(ALPHA_INT r = 0; r < mat->rows; ++r){ ALPHA_Number val; alpha_mul(val,mat->values[index2(di,r,mat->lval)],alpha); for(ALPHA_INT bc = bcl;bc < bch;++bc){ alpha_madde(y[index2(r,bc,ldy)],val,x[index2(r,bc,ldx)]); } } } } } return ALPHA_SPARSE_STATUS_SUCCESS; }
primitives.h
#pragma once #include <vector> #include <cstdint> #include <omp.h> #include "local_buffer.h" #include "../timer.h" using namespace std; #define CACHE_LINE_ENTRY (16) #define LOCAL_BUDGET (8*1024*1024) template<typename T> void MemSetOMP(T *arr, int val, size_t size) { size_t tid = omp_get_thread_num(); size_t max_omp_threads = omp_get_num_threads(); size_t task_num = size; size_t avg = (task_num + max_omp_threads - 1) / max_omp_threads; auto it_beg = avg * tid; auto it_end = min(avg * (tid + 1), task_num); memset(arr + it_beg, val, sizeof(T) * (it_end - it_beg)); #pragma omp barrier } template<typename T> void MemCpyOMP(T *dst, T *src, size_t size) { size_t tid = omp_get_thread_num(); size_t max_omp_threads = omp_get_num_threads(); size_t task_num = size; size_t avg = (task_num + max_omp_threads - 1) / max_omp_threads; auto it_beg = avg * tid; auto it_end = min(avg * (tid + 1), task_num); memcpy(dst + it_beg, src + it_beg, sizeof(T) * (it_end - it_beg)); #pragma omp barrier } /* * InclusivePrefixSumOMP: General Case Inclusive Prefix Sum * histogram: is for cache-aware thread-local histogram purpose * output: should be different from the variables captured in function object f * size: is the original size for the flagged prefix sum * f: requires it as the parameter, f(it) return the histogram value of that it */ template<typename H, typename T, typename F> void InclusivePrefixSumOMP(vector<H> &histogram, T *output, size_t size, F f) { int omp_num_threads = omp_get_num_threads(); #pragma omp single { histogram = vector<H>((omp_num_threads + 1) * CACHE_LINE_ENTRY, 0); } static thread_local int tid = omp_get_thread_num(); // 1st Pass: Histogram. auto avg = size / omp_num_threads; auto it_beg = avg * tid; auto histogram_idx = (tid + 1) * CACHE_LINE_ENTRY; histogram[histogram_idx] = 0; auto it_end = tid == omp_num_threads - 1 ? size : avg * (tid + 1); auto prev = 0u; for (auto it = it_beg; it < it_end; it++) { auto value = f(it); histogram[histogram_idx] += value; prev += value; output[it] = prev; } #pragma omp barrier // 2nd Pass: single-prefix-sum & Add previous sum. #pragma omp single { for (auto local_tid = 0; local_tid < omp_num_threads; local_tid++) { auto local_histogram_idx = (local_tid + 1) * CACHE_LINE_ENTRY; auto prev_histogram_idx = (local_tid) * CACHE_LINE_ENTRY; histogram[local_histogram_idx] += histogram[prev_histogram_idx]; } } { auto prev_sum = histogram[tid * CACHE_LINE_ENTRY]; for (auto it = it_beg; it < it_end; it++) { output[it] += prev_sum; } #pragma omp barrier } } /* * FlagPrefixSumOMP: special case of InclusivePrefixSumOMP */ template<typename H, typename T, typename F> void FlagPrefixSumOMP(vector<H> &histogram, T *output, size_t size, F f) { InclusivePrefixSumOMP(histogram, output, size, [&f](size_t it) { return f(it) ? 1 : 0; }); } /* * SelectNotFOMP: selection primitive * !f(it) returns selected */ template<typename H, typename T, typename OFF, typename F> void SelectNotFOMP(vector<H> &histogram, T *output, T *input, OFF *relative_off, size_t size, F f) { FlagPrefixSumOMP(histogram, relative_off, size, f); #pragma omp for for (size_t i = 0u; i < size; i++) { if (!(f(i))) { auto off = i - relative_off[i]; output[off] = input[i]; } } } template<typename OFF, typename F> void Histogram(size_t size, OFF *&bucket_ptrs, int32_t num_buckets, F f, Timer *timer = nullptr) { // Histogram. auto local_buf = (uint8_t *) calloc(num_buckets, sizeof(uint8_t)); #pragma omp for for (size_t i = 0u; i < size; i++) { auto src = f(i); local_buf[src]++; if (local_buf[src] == 0xff) { __sync_fetch_and_add(&bucket_ptrs[src], 0xff); local_buf[src] = 0; } } #pragma omp single if (timer != nullptr)log_info("[%s]: Local Comp Time: %.9lfs", __FUNCTION__, timer->elapsed()); for (size_t i = 0; i < num_buckets; i++) { if (local_buf[i] != 0) { __sync_fetch_and_add(&bucket_ptrs[i], local_buf[i]); } } #pragma omp barrier free(local_buf); } template<typename OFF, typename F> void HistogramAtomic(size_t size, OFF *&bucket_ptrs, int32_t num_buckets, F f) { // Histogram. #pragma omp for for (size_t i = 0u; i < size; i++) { auto src = f(i); __sync_fetch_and_add(&bucket_ptrs[src], 1); } } /* * Require an output array, * f: is the property for the bucket ID, given an index on the input array * Inefficient when there are lots of contentions because of atomic operations */ template<typename H, typename T, typename OFF, typename F> void BucketSort(vector<H> &histogram, T *&input, T *&output, OFF *&cur_write_off, OFF *&bucket_ptrs, size_t size, int32_t num_buckets, F f, Timer *timer = nullptr) { // Populate. #pragma omp single { bucket_ptrs = (OFF *) malloc(sizeof(OFF) * (num_buckets + 1)); cur_write_off = (OFF *) malloc(sizeof(OFF) * (num_buckets + 1)); cur_write_off[0] = 0; } MemSetOMP(bucket_ptrs, 0, num_buckets + 1); Histogram(size, bucket_ptrs, num_buckets, f, timer); // HistogramAtomic(size, bucket_ptrs, num_buckets, f); #pragma omp single if (timer != nullptr)log_info("[%s]: Histogram, Time: %.9lfs", __FUNCTION__, timer->elapsed()); InclusivePrefixSumOMP(histogram, cur_write_off + 1, num_buckets, [&bucket_ptrs](uint32_t it) { return bucket_ptrs[it]; }); MemCpyOMP(bucket_ptrs, cur_write_off, num_buckets + 1); #pragma omp single { if (timer != nullptr)log_info("[%s]: Before Scatter, Time: %.9lfs", __FUNCTION__, timer->elapsed()); } // Scatter. #pragma omp for for (size_t i = 0u; i < size; i++) { auto element = input[i]; auto bucket_id = f(i); auto old_offset = __sync_fetch_and_add(&(cur_write_off[bucket_id]), 1); output[old_offset] = element; } #pragma omp single { if (timer != nullptr)log_info("[%s]: Before Sort, Time: %.9lfs", __FUNCTION__, timer->elapsed()); } #pragma omp barrier } template<typename H, typename T, typename OFF, typename F> void BucketSortSmallBuckets(vector<H> &histogram, T *&input, T *&output, OFF *&cur_write_off, OFF *&bucket_ptrs, size_t size, int32_t num_buckets, F f, Timer *timer = nullptr) { using BufT= LocalWriteBuffer<T, uint32_t>; auto cap = max<int>(CACHE_LINE_ENTRY, LOCAL_BUDGET / num_buckets / sizeof(T)); auto bucket_write_buffers = (BufT *) malloc(num_buckets * sizeof(BufT)); auto bucket_buffers = (T *) malloc(cap * num_buckets * sizeof(T)); // Populate. #pragma omp single { int max_omp_threads = omp_get_num_threads(); log_info("[%s]: Mem Size Buckets: %zu, Bucket#: %d", __FUNCTION__, cap * num_buckets * sizeof(T) * max_omp_threads, num_buckets); bucket_ptrs = (uint32_t *) malloc(sizeof(OFF) * (num_buckets + 1)); cur_write_off = (uint32_t *) malloc(sizeof(OFF) * (num_buckets + 1)); cur_write_off[0] = 0; } MemSetOMP(bucket_ptrs, 0, num_buckets + 1); Histogram(size, bucket_ptrs, num_buckets, f); #pragma omp barrier InclusivePrefixSumOMP(histogram, cur_write_off + 1, num_buckets, [&bucket_ptrs](uint32_t it) { return bucket_ptrs[it]; }); MemCpyOMP(bucket_ptrs, cur_write_off, num_buckets + 1); #pragma omp single { if (timer != nullptr)log_info("[%s]: Before Scatter, Time: %.9lfs", __FUNCTION__, timer->elapsed()); } for (auto i = 0; i < num_buckets; i++) { bucket_write_buffers[i] = BufT(bucket_buffers + cap * i, cap, output, &cur_write_off[i]); } #pragma omp barrier // Scatter. #pragma omp for for (size_t i = 0u; i < size; i++) { auto element = input[i]; auto bucket_id = f(i); bucket_write_buffers[bucket_id].push(element); } for (auto i = 0; i < num_buckets; i++) { bucket_write_buffers[i].submit_if_possible(); } #pragma omp barrier #pragma omp single { if (timer != nullptr)log_info("[%s]: Before Sort, Time: %.9lfs", __FUNCTION__, timer->elapsed()); } free(bucket_buffers); free(bucket_write_buffers); #pragma omp barrier }
error.c
//-------------------------------------------------------------------------// // // // This benchmark is an OpenMP C version of the NPB LU 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 // //-------------------------------------------------------------------------// #include <stdio.h> #include <math.h> #include "applu.incl" //--------------------------------------------------------------------- // // compute the solution error // //--------------------------------------------------------------------- void error() { //--------------------------------------------------------------------- // local variables //--------------------------------------------------------------------- int i, j, k, m; double tmp; double u000ijk[5]; double errnm_local[5]; for (m = 0; m < 5; m++) { errnm[m] = 0.0; } #pragma omp parallel default(shared) private(i,j,k,m,tmp,u000ijk,errnm_local) { for (m = 0; m < 5; m++) { errnm_local[m] = 0.0; } #pragma omp for nowait for (k = 1; k < nz-1; k++) { for (j = jst; j < jend; j++) { for (i = ist; i < iend; i++) { exact( i, j, k, u000ijk ); for (m = 0; m < 5; m++) { tmp = ( u000ijk[m] - u[k][j][i][m] ); errnm_local[m] = errnm_local[m] + tmp * tmp; } } } } for (m = 0; m < 5; m++) { #pragma omp atomic errnm[m] += errnm_local[m]; } } //end parallel for (m = 0; m < 5; m++) { errnm[m] = sqrt ( errnm[m] / ( (nx0-2)*(ny0-2)*(nz0-2) ) ); } /* printf(" \n RMS-norm of error in soln. to first pde = %12.5E\n" " RMS-norm of error in soln. to second pde = %12.5E\n" " RMS-norm of error in soln. to third pde = %12.5E\n" " RMS-norm of error in soln. to fourth pde = %12.5E\n" " RMS-norm of error in soln. to fifth pde = %12.5E\n", errnm[0], errnm[1], errnm[2], errnm[3], errnm[4]); */ }
level.c
//------------------------------------------------------------------------------------------------------------------------------ // Samuel Williams // SWWilliams@lbl.gov // Lawrence Berkeley National Lab //------------------------------------------------------------------------------------------------------------------------------ #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <math.h> //------------------------------------------------------------------------------------------------------------------------------ #ifdef USE_MPI #include <mpi.h> #endif #ifdef _OPENMP #include <omp.h> #endif //------------------------------------------------------------------------------------------------------------------------------ #include "timers.h" #include "defines.h" #include "level.h" #include "operators.h" //------------------------------------------------------------------------------------------------------------------------------ void print_communicator(int printSendRecv, int rank, int level, communicator_type *comm){ int i; printf("rank=%2d level=%d ",rank,level); if(printSendRecv & 0x1){ printf("num_sends=%2d ",comm->num_sends); printf("send_ranks=[ ");for(i=0;i<comm->num_sends;i++)printf("%2d ",comm->send_ranks[i]);printf("] "); printf("send_sizes=[ ");for(i=0;i<comm->num_sends;i++)printf("%2d ",comm->send_sizes[i]);printf("] "); printf("send_buffers=[ ");for(i=0;i<comm->num_sends;i++)printf("%08lx ",(uint64_t)comm->send_buffers[i]);printf("] "); for(i=0;i<comm->num_blocks[0];i++)printf("[ %dx%dx%d from %d %d %d %d %d to %d %d %d %d %d ] ",comm->blocks[0][i].dim.i,comm->blocks[0][i].dim.j,comm->blocks[0][i].dim.k,comm->blocks[0][i].read.i,comm->blocks[0][i].read.j,comm->blocks[0][i].read.k,comm->blocks[0][i].read.jStride,comm->blocks[0][i].read.kStride,comm->blocks[0][i].write.i,comm->blocks[0][i].write.j,comm->blocks[0][i].write.k,comm->blocks[0][i].write.jStride,comm->blocks[0][i].write.kStride); printf("\n"); } if(printSendRecv & 0x2){ for(i=0;i<comm->num_blocks[1];i++)printf("[ %dx%dx%d from %d %d %d %d %d to %d %d %d %d %d ] ",comm->blocks[1][i].dim.i,comm->blocks[1][i].dim.j,comm->blocks[1][i].dim.k,comm->blocks[1][i].read.i,comm->blocks[1][i].read.j,comm->blocks[1][i].read.k,comm->blocks[1][i].read.jStride,comm->blocks[1][i].read.kStride,comm->blocks[1][i].write.i,comm->blocks[1][i].write.j,comm->blocks[1][i].write.k,comm->blocks[1][i].write.jStride,comm->blocks[1][i].write.kStride); printf("\n"); } if(printSendRecv & 0x4){ printf("num_recvs=%2d ",comm->num_recvs); printf("recv_ranks=[ ");for(i=0;i<comm->num_recvs;i++)printf("%2d ",comm->recv_ranks[i]);printf("] "); printf("recv_sizes=[ ");for(i=0;i<comm->num_recvs;i++)printf("%2d ",comm->recv_sizes[i]);printf("] "); printf("recv_buffers=[ ");for(i=0;i<comm->num_recvs;i++)printf("%08lx ",(uint64_t)comm->recv_buffers[i]);printf("] "); for(i=0;i<comm->num_blocks[2];i++)printf("[ %dx%dx%d from %d %d %d %d %d to %d %d %d %d %d ] ",comm->blocks[2][i].dim.i,comm->blocks[2][i].dim.j,comm->blocks[2][i].dim.k,comm->blocks[2][i].read.i,comm->blocks[2][i].read.j,comm->blocks[2][i].read.k,comm->blocks[2][i].read.jStride,comm->blocks[2][i].read.kStride,comm->blocks[2][i].write.i,comm->blocks[2][i].write.j,comm->blocks[2][i].write.k,comm->blocks[2][i].write.jStride,comm->blocks[2][i].write.kStride); printf("\n"); } fflush(stdout); } //------------------------------------------------------------------------------------------------------------------------------ typedef struct { int sendRank; int sendBoxID; int sendBox; int sendDir; int recvRank; int recvBoxID; int recvBox; } GZ_type; int qsortGZ(const void *a, const void*b){ GZ_type *gza = (GZ_type*)a; GZ_type *gzb = (GZ_type*)b; // by convention, MPI buffers are first sorted by sendRank if(gza->sendRank < gzb->sendRank)return(-1); if(gza->sendRank > gzb->sendRank)return( 1); // then by sendBoxID if(gza->sendBoxID < gzb->sendBoxID)return(-1); if(gza->sendBoxID > gzb->sendBoxID)return( 1); // and finally by the direction sent if(gza->sendDir < gzb->sendDir)return(-1); if(gza->sendDir > gzb->sendDir)return( 1); return(0); } int qsortInt(const void *a, const void *b){ int *ia = (int*)a; int *ib = (int*)b; if(*ia < *ib)return(-1); if(*ia > *ib)return( 1); return( 0); } int qsortBlock(const void *a, const void *b){ blockCopy_type *ba = (blockCopy_type*)a; blockCopy_type *bb = (blockCopy_type*)b; if(ba->write.box >= 0){ // sort by box... if(ba->write.box < bb->write.box)return(-1); if(ba->write.box > bb->write.box)return( 1); // now sort by k if(ba->write.k < bb->write.k )return(-1); if(ba->write.k > bb->write.k )return( 1); // now sort by j if(ba->write.j < bb->write.j )return(-1); if(ba->write.j > bb->write.j )return( 1); // now sort by i if(ba->write.i < bb->write.i )return(-1); if(ba->write.i > bb->write.i )return( 1); }else if(ba->read.box >= 0){ // sort by box... if(ba->read.box < bb->read.box )return(-1); if(ba->read.box > bb->read.box )return( 1); // now sort by k if(ba->read.k < bb->read.k )return(-1); if(ba->read.k > bb->read.k )return( 1); // now sort by j if(ba->read.j < bb->read.j )return(-1); if(ba->read.j > bb->read.j )return( 1); // now sort by i if(ba->read.i < bb->read.i )return(-1); if(ba->read.i > bb->read.i )return( 1); } return( 0); } //------------------------------------------------------------------------------------------------------------------------------ void decompose_level_lex(int *rank_of_box, int idim, int jdim, int kdim, int ranks){ // simple lexicographical decomposition of the domain (i-j-k ordering) // load balancing is easily realized // unfortunately, each process will likely receive one or two long pencils of boxes. // as such, the resultant surface:volum ratio will likely be poor int boxes = idim*jdim*kdim; int i,j,k; for(k=0;k<kdim;k++){ for(j=0;j<jdim;j++){ for(i=0;i<idim;i++){ int b = k*jdim*idim + j*idim + i; rank_of_box[b] = ((uint64_t)ranks*(uint64_t)b)/(uint64_t)boxes; // ranks*b can be as larger than ranks^2... can over flow int }}} } //--------------------------------------------------------------------------------------------------------------------------------------------------- void decompose_level_bisection_special(int *rank_of_box, int jStride, int kStride, int ilo, int jlo, int klo, int idim, int jdim, int kdim, int rank_lo, int ranks){ // if possible, recursively partition the domain by a prime number (e.g. try an parition a 9^3 array into 3 equal pieces instead of 5x9^2 and 4x9^2) // if not, default to simple bisection // this function should ensure that each process receives a compact rectahedral collection of boxes // however, load imbalance can occur // the choice of whether to try and partition with the largest prime or smallest prime first is up to the user #define numPrimes 13 //int primes[numPrimes] = {41,37,31,29,23,19,17,13,11,7,5,3,2}; int primes[numPrimes] = {2,3,5,7,11,13,17,19,23,29,31,37,41}; int i,j,k,p,f,ff; // base case, no further recursion... if( (ranks==1)|| ((idim==1)&&(jdim==1)&&(kdim==1)) ){ for(i=ilo;i<ilo+idim;i++){ for(j=jlo;j<jlo+jdim;j++){ for(k=klo;k<klo+kdim;k++){ int b = i + j*jStride + k*kStride; rank_of_box[b] = rank_lo; }}} return; } // special cases for perfectly matched problem sizes with numbers of processes (but not powers of 2)... for(p=0;p<numPrimes;p++){ f=primes[p]; if( (kdim>=idim)&&(kdim>=jdim) ){if( (kdim%f==0) && (ranks%f==0) ){for(ff=0;ff<f;ff++)decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo,jlo,klo+ff*kdim/f,idim,jdim,kdim/f,rank_lo+ff*ranks/f,ranks/f);return;}} if( (jdim>=idim)&&(jdim>=kdim) ){if( (jdim%f==0) && (ranks%f==0) ){for(ff=0;ff<f;ff++)decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo,jlo+ff*jdim/f,klo,idim,jdim/f,kdim,rank_lo+ff*ranks/f,ranks/f);return;}} if( (idim>=jdim)&&(idim>=kdim) ){if( (idim%f==0) && (ranks%f==0) ){for(ff=0;ff<f;ff++)decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo+ff*idim/f,jlo,klo,idim/f,jdim,kdim,rank_lo+ff*ranks/f,ranks/f);return;}} } // try and bisect the domain in the i-dimension if( (idim>=jdim)&&(idim>=kdim) ){ int dim0 = (int)(0.5*(double)idim + 0.50); int dim1 = idim-dim0; int r0 = (int)( 0.5 + (double)ranks*(double)dim0/(double)idim ); int r1 = ranks-r0; decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo ,jlo,klo,dim0,jdim,kdim,rank_lo ,r0); // lo decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo+dim0,jlo,klo,dim1,jdim,kdim,rank_lo+r0,r1); // hi return; } // try and bisect the domain in the j-dimension if( (jdim>=idim)&&(jdim>=kdim) ){ int dim0 = (int)(0.5*(double)jdim + 0.50); int dim1 = jdim-dim0; int r0 = (int)( 0.5 + (double)ranks*(double)dim0/(double)jdim ); int r1 = ranks-r0; decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo,jlo ,klo,idim,dim0,kdim,rank_lo ,r0); // lo decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo,jlo+dim0,klo,idim,dim1,kdim,rank_lo+r0,r1); // hi return; } // try and bisect the domain in the k-dimension if( (kdim>=idim)&&(kdim>=jdim) ){ int dim0 = (int)(0.5*(double)kdim + 0.50); int dim1 = kdim-dim0; int r0 = (int)( 0.5 + (double)ranks*(double)dim0/(double)kdim ); int r1 = ranks-r0; decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo,jlo,klo ,idim,jdim,dim0,rank_lo ,r0); // lo decompose_level_bisection_special(rank_of_box,jStride,kStride,ilo,jlo,klo+dim0,idim,jdim,dim1,rank_lo+r0,r1); // hi return; } fprintf(stderr,"decompose_level_bisection_special failed !!!\n");exit(0); } //--------------------------------------------------------------------------------------------------------------------------------------------------- void decompose_level_bisection(int *rank_of_box, int jStride, int kStride, int ilo, int jlo, int klo, int idim, int jdim, int kdim, int ranks, int sfc_offset, int sfc_max_length){ // base case... if( (idim==1) && (jdim==1) && (kdim==1) ){ int b = ilo + jlo*jStride + klo*kStride; rank_of_box[b] = ((uint64_t)ranks*(uint64_t)sfc_offset)/(uint64_t)sfc_max_length; // sfc_max_length is the precomputed maximum length return; } // try and bisect the domain in the i-dimension if( (idim>=jdim)&&(idim>=kdim) ){ int dim0 = (int)(0.5*(double)idim + 0.50); int dim1 = idim-dim0; int sfc_delta = dim0*jdim*kdim; decompose_level_bisection(rank_of_box,jStride,kStride,ilo ,jlo,klo,dim0,jdim,kdim,ranks,sfc_offset ,sfc_max_length); // lo decompose_level_bisection(rank_of_box,jStride,kStride,ilo+dim0,jlo,klo,dim1,jdim,kdim,ranks,sfc_offset+sfc_delta,sfc_max_length); // hi return; } // try and bisect the domain in the j-dimension if( (jdim>=idim)&&(jdim>=kdim) ){ int dim0 = (int)(0.5*(double)jdim + 0.50); int dim1 = jdim-dim0; int sfc_delta = idim*dim0*kdim; decompose_level_bisection(rank_of_box,jStride,kStride,ilo,jlo ,klo,idim,dim0,kdim,ranks,sfc_offset ,sfc_max_length); // lo decompose_level_bisection(rank_of_box,jStride,kStride,ilo,jlo+dim0,klo,idim,dim1,kdim,ranks,sfc_offset+sfc_delta,sfc_max_length); // hi return; } // try and bisect the domain in the k-dimension if( (kdim>=idim)&&(kdim>=jdim) ){ int dim0 = (int)(0.5*(double)kdim + 0.50); int dim1 = kdim-dim0; int sfc_delta = idim*jdim*dim0; decompose_level_bisection(rank_of_box,jStride,kStride,ilo,jlo,klo ,idim,jdim,dim0,ranks,sfc_offset ,sfc_max_length); // lo decompose_level_bisection(rank_of_box,jStride,kStride,ilo,jlo,klo+dim0,idim,jdim,dim1,ranks,sfc_offset+sfc_delta,sfc_max_length); // hi return; } // failure... fprintf(stderr,"decompose_level_bisection failed !!!\n");exit(0); } //--------------------------------------------------------------------------------------------------------------------------------------------------- // Given a bounding box (idim,jdim,kdim) use a Z-morton Space Filling Curve (SFC) to assign the boxes within the (boxes_in_i,boxes_in_j,boxes_in_k) valid region domain // sfc_offset is the current offset within the space filling curve (starts with 0) // this function returns the new offset based on how many actual boxes it found within (ilo,jlo,klo) + (idim,jdim,kdim) // sfc_max_length is the maximum length of the SFC. Note, if this length exceeds boxes_in_i*boxes_in_j*boxes_in_k, then some processes with receive no work int decompose_level_zmort(int *rank_of_box, int boxes_in_i, int boxes_in_j, int boxes_in_k, int ilo, int jlo, int klo, int idim, int jdim, int kdim, int ranks, int sfc_offset, int sfc_max_length){ // invalid cases... if(idim<1)return(sfc_offset); if(jdim<1)return(sfc_offset); if(kdim<1)return(sfc_offset); if(ilo <0)return(sfc_offset); if(jlo <0)return(sfc_offset); if(klo <0)return(sfc_offset); // base case... if( (idim==1) && (jdim==1) && (kdim==1) ){ if( (ilo<boxes_in_i) && (jlo<boxes_in_j) && (klo<boxes_in_k) ){ // deemed a valid box (could be augmented for irregular domains) int b = ilo + jlo*boxes_in_i + klo*boxes_in_i*boxes_in_j; rank_of_box[b] = ((uint64_t)ranks*(uint64_t)(sfc_offset))/(uint64_t)sfc_max_length; // sfc_max_length is the precomputed maximum length return(sfc_offset+1); } return(sfc_offset); // region outside valid domain; sfc_offset is unchanged } // bisect in 3D... int imid = ilo + (idim/2); int jmid = jlo + (jdim/2); int kmid = klo + (kdim/2); sfc_offset=decompose_level_zmort(rank_of_box,boxes_in_i,boxes_in_j,boxes_in_k,ilo ,jlo ,klo , idim/2, jdim/2, kdim/2,ranks,sfc_offset,sfc_max_length); sfc_offset=decompose_level_zmort(rank_of_box,boxes_in_i,boxes_in_j,boxes_in_k,imid,jlo ,klo ,idim-idim/2, jdim/2, kdim/2,ranks,sfc_offset,sfc_max_length); sfc_offset=decompose_level_zmort(rank_of_box,boxes_in_i,boxes_in_j,boxes_in_k,ilo ,jmid,klo , idim/2,jdim-jdim/2, kdim/2,ranks,sfc_offset,sfc_max_length); sfc_offset=decompose_level_zmort(rank_of_box,boxes_in_i,boxes_in_j,boxes_in_k,imid,jmid,klo ,idim-idim/2,jdim-jdim/2, kdim/2,ranks,sfc_offset,sfc_max_length); sfc_offset=decompose_level_zmort(rank_of_box,boxes_in_i,boxes_in_j,boxes_in_k,ilo ,jlo ,kmid, idim/2, jdim/2,kdim-kdim/2,ranks,sfc_offset,sfc_max_length); sfc_offset=decompose_level_zmort(rank_of_box,boxes_in_i,boxes_in_j,boxes_in_k,imid,jlo ,kmid,idim-idim/2, jdim/2,kdim-kdim/2,ranks,sfc_offset,sfc_max_length); sfc_offset=decompose_level_zmort(rank_of_box,boxes_in_i,boxes_in_j,boxes_in_k,ilo ,jmid,kmid, idim/2,jdim-jdim/2,kdim-kdim/2,ranks,sfc_offset,sfc_max_length); sfc_offset=decompose_level_zmort(rank_of_box,boxes_in_i,boxes_in_j,boxes_in_k,imid,jmid,kmid,idim-idim/2,jdim-jdim/2,kdim-kdim/2,ranks,sfc_offset,sfc_max_length); return(sfc_offset); } //------------------------------------------------------------------------------------------------------------------------------ //int decompose_level_hilbert(int *rank_of_box, int boxes_in_i, int boxes_in_j, int boxes_in_k, int ilo, int jlo, int klo, int idim, int jdim, int kdim, int ranks, int sfc_offset, int sfc_max_length){ // implements a 3D hilbert curve on the non-power of two domain using a power of two bounding box //} //--------------------------------------------------------------------------------------------------------------------------------------------------- void print_decomposition(level_type *level){ if(level->my_rank!=0)return; printf("\n"); int i,j,k; int jStride = level->boxes_in.i; int kStride = level->boxes_in.i*level->boxes_in.j; for(k=level->boxes_in.k-1;k>=0;k--){ // (i,j,k)=(0,0,0) is bottom left corner for(j=level->boxes_in.j-1;j>=0;j--){ // (i,j)=(0,0) is bottom left corner for(i=0;i<j;i++)printf(" "); for(i=0;i<level->boxes_in.i;i++){ int b = i + j*jStride + k*kStride; printf("%4d ",level->rank_of_box[b]); }printf("\n"); }printf("\n\n"); } fflush(stdout); } //------------------------------------------------------------------------------------------------------------------------------ // append the specified block (logical region) to the current list of blocks // each block may be tiled to... // - create more parallelism across the list of blocks // - limit parallelism within a block // - limit the memory requirements for each block #ifndef BLOCK_LIST_MIN_SIZE #define BLOCK_LIST_MIN_SIZE 1000 #endif void append_block_to_list(blockCopy_type ** blocks, int *allocated_blocks, int *num_blocks, int dim_i, int dim_j, int dim_k, int read_box, double* read_ptr, int read_i, int read_j, int read_k, int read_jStride, int read_kStride, int read_scale, int write_box, double* write_ptr, int write_i, int write_j, int write_k, int write_jStride, int write_kStride, int write_scale, int blockcopy_tile_i, int blockcopy_tile_j, int blockcopy_tile_k, int subtype ){ // Take a dim_j x dim_k iteration space and tile it into smaller faces of size blockcopy_tile_j x blockcopy_tile_k // This increases the number of blockCopies in the ghost zone exchange and thereby increases the thread-level parallelism #if 0 // use recursive (z-mort) ordering of tiles in order to improve locality on deep memory hierarchies... int doRecursion=0; if(dim_i > blockcopy_tile_i)doRecursion=1; if(dim_j > blockcopy_tile_j)doRecursion=1; if(dim_k > blockcopy_tile_k)doRecursion=1; if( read_scale != 1)doRecursion=0; // disable recursion for restriction if(write_scale != 1)doRecursion=0; // disable recursion for interpolation if(doRecursion){ int mid_i = (dim_i + 1)/2; int mid_j = (dim_j + 1)/2; int mid_k = (dim_k + 1)/2; mid_i = blockcopy_tile_i*( (mid_i+blockcopy_tile_i-1)/blockcopy_tile_i); mid_j = blockcopy_tile_j*( (mid_j+blockcopy_tile_j-1)/blockcopy_tile_j); mid_k = blockcopy_tile_k*( (mid_k+blockcopy_tile_k-1)/blockcopy_tile_k); if(mid_i>dim_i)mid_i=dim_i; if(mid_j>dim_j)mid_j=dim_j; if(mid_k>dim_k)mid_k=dim_k; append_block_to_list(blocks,allocated_blocks,num_blocks, mid_i, mid_j, mid_k, read_box, read_ptr, read_i , read_j , read_k , read_jStride, read_kStride, read_scale, write_box,write_ptr,write_i ,write_j ,write_k ,write_jStride,write_kStride,write_scale, blockcopy_tile_i,blockcopy_tile_j,blockcopy_tile_k,subtype); append_block_to_list(blocks,allocated_blocks,num_blocks,dim_i-mid_i, mid_j, mid_k, read_box, read_ptr, read_i+mid_i, read_j , read_k , read_jStride, read_kStride, read_scale, write_box,write_ptr,write_i+mid_i,write_j ,write_k ,write_jStride,write_kStride,write_scale, blockcopy_tile_i,blockcopy_tile_j,blockcopy_tile_k,subtype); append_block_to_list(blocks,allocated_blocks,num_blocks, mid_i,dim_j-mid_j, mid_k, read_box, read_ptr, read_i , read_j+mid_j, read_k , read_jStride, read_kStride, read_scale, write_box,write_ptr,write_i ,write_j+mid_j,write_k ,write_jStride,write_kStride,write_scale, blockcopy_tile_i,blockcopy_tile_j,blockcopy_tile_k,subtype); append_block_to_list(blocks,allocated_blocks,num_blocks,dim_i-mid_i,dim_j-mid_j, mid_k, read_box, read_ptr, read_i+mid_i, read_j+mid_j, read_k , read_jStride, read_kStride, read_scale, write_box,write_ptr,write_i+mid_i,write_j+mid_j,write_k ,write_jStride,write_kStride,write_scale, blockcopy_tile_i,blockcopy_tile_j,blockcopy_tile_k,subtype); append_block_to_list(blocks,allocated_blocks,num_blocks, mid_i, mid_j,dim_k-mid_k, read_box, read_ptr, read_i , read_j , read_k+mid_k, read_jStride, read_kStride, read_scale, write_box,write_ptr,write_i ,write_j ,write_k+mid_k,write_jStride,write_kStride,write_scale, blockcopy_tile_i,blockcopy_tile_j,blockcopy_tile_k,subtype); append_block_to_list(blocks,allocated_blocks,num_blocks,dim_i-mid_i, mid_j,dim_k-mid_k, read_box, read_ptr, read_i+mid_i, read_j , read_k+mid_k, read_jStride, read_kStride, read_scale, write_box,write_ptr,write_i+mid_i,write_j ,write_k+mid_k,write_jStride,write_kStride,write_scale, blockcopy_tile_i,blockcopy_tile_j,blockcopy_tile_k,subtype); append_block_to_list(blocks,allocated_blocks,num_blocks, mid_i,dim_j-mid_j,dim_k-mid_k, read_box, read_ptr, read_i , read_j+mid_j, read_k+mid_k, read_jStride, read_kStride, read_scale, write_box,write_ptr,write_i ,write_j+mid_j,write_k+mid_k,write_jStride,write_kStride,write_scale, blockcopy_tile_i,blockcopy_tile_j,blockcopy_tile_k,subtype); append_block_to_list(blocks,allocated_blocks,num_blocks,dim_i-mid_i,dim_j-mid_j,dim_k-mid_k, read_box, read_ptr, read_i+mid_i, read_j+mid_j, read_k+mid_k, read_jStride, read_kStride, read_scale, write_box,write_ptr,write_i+mid_i,write_j+mid_j,write_k+mid_k,write_jStride,write_kStride,write_scale, blockcopy_tile_i,blockcopy_tile_j,blockcopy_tile_k,subtype); return; } #endif // read_/write_scale are used to stride appropriately when read and write loop iterations spaces are different // ghostZone: read_scale=1, write_scale=1 // interpolation: read_scale=1, write_scale=2 // restriction: read_scale=2, write_scale=1 // FIX... dim_i,j,k -> read_dim_i,j,k, write_dim_i,j,k int ii,jj,kk; for(kk=0;kk<dim_k;kk+=blockcopy_tile_k){ for(jj=0;jj<dim_j;jj+=blockcopy_tile_j){ for(ii=0;ii<dim_i;ii+=blockcopy_tile_i){ int dim_k_mod = dim_k-kk;if(dim_k_mod>blockcopy_tile_k)dim_k_mod=blockcopy_tile_k; int dim_j_mod = dim_j-jj;if(dim_j_mod>blockcopy_tile_j)dim_j_mod=blockcopy_tile_j; int dim_i_mod = dim_i-ii;if(dim_i_mod>blockcopy_tile_i)dim_i_mod=blockcopy_tile_i; if(*num_blocks >= *allocated_blocks){ int oldSize = *allocated_blocks; if(*allocated_blocks == 0){*allocated_blocks=BLOCK_LIST_MIN_SIZE;*blocks=(blockCopy_type*) malloc( (*allocated_blocks)*sizeof(blockCopy_type));} else{*allocated_blocks*=2; *blocks=(blockCopy_type*)realloc((void*)(*blocks),(*allocated_blocks)*sizeof(blockCopy_type));} if(*blocks == NULL){fprintf(stderr,"realloc failed - append_block_to_list (%d -> %d)\n",oldSize,*allocated_blocks);exit(0);} } (*blocks)[*num_blocks].subtype = subtype; (*blocks)[*num_blocks].dim.i = dim_i_mod; (*blocks)[*num_blocks].dim.j = dim_j_mod; (*blocks)[*num_blocks].dim.k = dim_k_mod; (*blocks)[*num_blocks].read.box = read_box; (*blocks)[*num_blocks].read.ptr = read_ptr; (*blocks)[*num_blocks].read.i = read_i + read_scale*ii; (*blocks)[*num_blocks].read.j = read_j + read_scale*jj; (*blocks)[*num_blocks].read.k = read_k + read_scale*kk; (*blocks)[*num_blocks].read.jStride = read_jStride; (*blocks)[*num_blocks].read.kStride = read_kStride; (*blocks)[*num_blocks].write.box = write_box; (*blocks)[*num_blocks].write.ptr = write_ptr; (*blocks)[*num_blocks].write.i = write_i + write_scale*ii; (*blocks)[*num_blocks].write.j = write_j + write_scale*jj; (*blocks)[*num_blocks].write.k = write_k + write_scale*kk; (*blocks)[*num_blocks].write.jStride = write_jStride; (*blocks)[*num_blocks].write.kStride = write_kStride; (*num_blocks)++; }}} } //---------------------------------------------------------------------------------------------------------------------------------------------------- // create a mini program that traverses the domain boundary intersecting with this process's boxes // This includes faces, corners, and edges void build_boundary_conditions(level_type *level, int shape){ level->boundary_condition.blocks[shape] = NULL; // default for periodic (i.e. no BC's) level->boundary_condition.num_blocks[shape] = 0; // default for periodic (i.e. no BC's) level->boundary_condition.allocated_blocks[shape] = 0; // default for periodic (i.e. no BC's) if(level->boundary_condition.type == BC_PERIODIC)return; //int faces[27] = {0,0,0,0,1,0,0,0,0, 0,1,0,1,0,1,0,1,0, 0,0,0,0,1,0,0,0,0}; int edges[27] = {0,1,0,1,0,1,0,1,0, 1,0,1,0,0,0,1,0,1, 0,1,0,1,0,1,0,1,0}; int corners[27] = {1,0,1,0,0,0,1,0,1, 0,0,0,0,0,0,0,0,0, 1,0,1,0,0,0,1,0,1}; int box, di,dj,dk; for(box=0;box<level->num_my_boxes;box++){ // traverse my list of boxes... for(dk=-1;dk<=1;dk++){ // for each box, examine its 26 neighbors... for(dj=-1;dj<=1;dj++){ for(di=-1;di<=1;di++){ int dir = 13+di+3*dj+9*dk; // face/edge/corner of *THIS* box (not the domain) // determine if this region (box's di,dj,dk ghost zone) is outside of the domain int regionIsOutside=0; int normal = 13; // normal effectively defines the normal vector to the *DOMAIN* for this region... // this addition is necessary for linearly interpolated BC's as a box's corner is not necessarily a domain's corner int myBox_i = level->my_boxes[box].low.i / level->box_dim; int myBox_j = level->my_boxes[box].low.j / level->box_dim; int myBox_k = level->my_boxes[box].low.k / level->box_dim; int neighborBox_i = ( myBox_i + di ); int neighborBox_j = ( myBox_j + dj ); int neighborBox_k = ( myBox_k + dk ); if( neighborBox_i < 0 ){regionIsOutside=1;normal-=1;} if( neighborBox_j < 0 ){regionIsOutside=1;normal-=3;} if( neighborBox_k < 0 ){regionIsOutside=1;normal-=9;} if( neighborBox_i >=level->boxes_in.i ){regionIsOutside=1;normal+=1;} if( neighborBox_j >=level->boxes_in.j ){regionIsOutside=1;normal+=3;} if( neighborBox_k >=level->boxes_in.k ){regionIsOutside=1;normal+=9;} // calculate ghost zone region size and coordinates relative to the first non-ghost zone element (0,0,0) int block_i=-1,block_j=-1,block_k=-1; int dim_i=-1, dim_j=-1, dim_k=-1; switch(di){ case -1:dim_i=level->box_ghosts;block_i=0-level->box_ghosts;break; case 0:dim_i=level->box_dim; block_i=0; break; case 1:dim_i=level->box_ghosts;block_i=0+level->box_dim; break; } switch(dj){ case -1:dim_j=level->box_ghosts;block_j=0-level->box_ghosts;break; case 0:dim_j=level->box_dim; block_j=0; break; case 1:dim_j=level->box_ghosts;block_j=0+level->box_dim; break; } switch(dk){ case -1:dim_k=level->box_ghosts;block_k=0-level->box_ghosts;break; case 0:dim_k=level->box_dim; block_k=0; break; case 1:dim_k=level->box_ghosts;block_k=0+level->box_dim; break; } // use regionIsOutside to short circuit logic and cull unnecessary regions... switch(shape){ case STENCIL_SHAPE_STAR: if(edges[dir]||corners[dir])regionIsOutside=0;break; // star-shaped stencils don't need BC's enforced on corners or edges case STENCIL_SHAPE_NO_CORNERS:if( corners[dir])regionIsOutside=0;break; // these stencils don't need BC's enforced on edges } // default tile sizes... // NOTE, BC's may never tile smaller than the ghost zone depth int blockcopy_i = (BLOCKCOPY_TILE_I < level->box_ghosts) ? level->box_ghosts : BLOCKCOPY_TILE_I; int blockcopy_j = (BLOCKCOPY_TILE_J < level->box_ghosts) ? level->box_ghosts : BLOCKCOPY_TILE_J; int blockcopy_k = (BLOCKCOPY_TILE_K < level->box_ghosts) ? level->box_ghosts : BLOCKCOPY_TILE_K; #if 0 // 2D tiling of faces // 1D tiling of edges // corners use defaults switch(dir){ case 1:blockcopy_i= 8;blockcopy_j=10000;blockcopy_k=10000;break; // i edge case 3:blockcopy_i=10000;blockcopy_j= 8;blockcopy_k=10000;break; // j edge case 4:blockcopy_i= 8;blockcopy_j= 8;blockcopy_k=10000;break; // ij face case 5:blockcopy_i=10000;blockcopy_j= 8;blockcopy_k=10000;break; // j edge case 7:blockcopy_i= 8;blockcopy_j=10000;blockcopy_k=10000;break; // i edge case 9:blockcopy_i=10000;blockcopy_j=10000;blockcopy_k= 8;break; // k edge case 10:blockcopy_i= 8;blockcopy_j=10000;blockcopy_k= 8;break; // ik face case 11:blockcopy_i=10000;blockcopy_j=10000;blockcopy_k= 8;break; // k edge case 12:blockcopy_i=10000;blockcopy_j= 8;blockcopy_k= 8;break; // jk face case 14:blockcopy_i=10000;blockcopy_j= 8;blockcopy_k= 8;break; // jk face case 15:blockcopy_i=10000;blockcopy_j=10000;blockcopy_k= 8;break; // k edge case 16:blockcopy_i= 8;blockcopy_j=10000;blockcopy_k= 8;break; // ik face case 17:blockcopy_i=10000;blockcopy_j=10000;blockcopy_k= 8;break; // k edge case 19:blockcopy_i= 8;blockcopy_j=10000;blockcopy_k=10000;break; // i edge case 21:blockcopy_i=10000;blockcopy_j= 8;blockcopy_k=10000;break; // j edge case 22:blockcopy_i= 8;blockcopy_j= 8;blockcopy_k=10000;break; // ij face case 23:blockcopy_i=10000;blockcopy_j= 8;blockcopy_k=10000;break; // j edge case 25:blockcopy_i= 8;blockcopy_j=10000;blockcopy_k=10000;break; // i edge } #endif if(regionIsOutside){ append_block_to_list(&(level->boundary_condition.blocks[shape]),&(level->boundary_condition.allocated_blocks[shape]),&(level->boundary_condition.num_blocks[shape]), /* dim.i = */ dim_i, /* dim.j = */ dim_j, /* dim.k = */ dim_k, /* read.box = */ box, /* read.ptr = */ NULL, /* read.i = */ block_i, /* read.j = */ block_j, /* read.k = */ block_k, /* read.jStride = */ level->my_boxes[box].jStride, /* read.kStride = */ level->my_boxes[box].kStride, /* read.scale = */ 1, /* write.box = */ box, /* write.ptr = */ NULL, /* write.i = */ block_i, /* write.j = */ block_j, /* write.k = */ block_k, /* write.jStride = */ level->my_boxes[box].jStride, /* write.kStride = */ level->my_boxes[box].kStride, /* write.scale = */ 1, /* blockcopy_i = */ blockcopy_i, /* blockcopy_j = */ blockcopy_j, /* blockcopy_k = */ blockcopy_k, /* subtype = */ normal ); }}}}} #ifdef BLOCK_SPATIAL_SORT // sort all the resultant blocks by box,k,j,i (good locality) qsort(level->boundary_condition.blocks[shape],level->boundary_condition.num_blocks[shape],sizeof(blockCopy_type),qsortBlock); #endif } //---------------------------------------------------------------------------------------------------------------------------------------------------- // create a mini program that packs data into MPI recv buffers, exchanges local data, and unpacks the MPI send buffers // broadly speaking... // 1. traverse my list of Boxes and create a list of ghosts that must be sent // 2. create a list of neighbors to send to // 3. allocate and populate the pack list and allocate the send buffers // 4. allocate and populate the local exchange list // 5. traverse my list of Boxes and create a list of ghosts that must be received // 6. create a list of neighbors to receive from // 7. allocate and populate the unpack list and allocate the recv buffers // // thus a ghost zone exchange is // 1. prepost a Irecv for each MPI recv buffer (1 per neighbor) // 2. traverse the pack list // 3. post the Isends for each MPI send buffer (1 per neighbor) // 4. traverse the local copy list // 5. waitall // 6. traverse the unpack list // // / 24 25 26 / // / 21 22 23 / (k+1) // / 18 19 20 / // // / 15 16 17 / // / 12 13 14 / (k) // / 9 10 11 / // // / 6 7 8 / // / 3 4 5 / (k-1) // / 0 1 2 / // void build_exchange_ghosts(level_type *level, int shape){ int faces[27] = {0,0,0,0,1,0,0,0,0, 0,1,0,1,0,1,0,1,0, 0,0,0,0,1,0,0,0,0}; int edges[27] = {0,1,0,1,0,1,0,1,0, 1,0,1,0,0,0,1,0,1, 0,1,0,1,0,1,0,1,0}; int corners[27] = {1,0,1,0,0,0,1,0,1, 0,0,0,0,0,0,0,0,0, 1,0,1,0,0,0,1,0,1}; // initialize to defaults... level->exchange_ghosts[shape].num_recvs = 0; level->exchange_ghosts[shape].num_sends = 0; level->exchange_ghosts[shape].recv_ranks = NULL; level->exchange_ghosts[shape].send_ranks = NULL; level->exchange_ghosts[shape].recv_sizes = NULL; level->exchange_ghosts[shape].send_sizes = NULL; level->exchange_ghosts[shape].recv_buffers = NULL; level->exchange_ghosts[shape].send_buffers = NULL; level->exchange_ghosts[shape].blocks[0] = NULL; level->exchange_ghosts[shape].blocks[1] = NULL; level->exchange_ghosts[shape].blocks[2] = NULL; level->exchange_ghosts[shape].num_blocks[0] = 0; level->exchange_ghosts[shape].num_blocks[1] = 0; level->exchange_ghosts[shape].num_blocks[2] = 0; level->exchange_ghosts[shape].allocated_blocks[0] = 0; level->exchange_ghosts[shape].allocated_blocks[1] = 0; level->exchange_ghosts[shape].allocated_blocks[2] = 0; #ifdef USE_MPI level->exchange_ghosts[shape].requests = NULL; level->exchange_ghosts[shape].status = NULL; #endif int n,CommunicateThisDir[27];for(n=0;n<27;n++)CommunicateThisDir[n] = faces[n] + edges[n] + corners[n];// to be safe, communicate everything switch(shape){ case STENCIL_SHAPE_BOX: for(n=0;n<27;n++)CommunicateThisDir[n] = faces[n] + edges[n] + corners[n];break; case STENCIL_SHAPE_STAR: for(n=0;n<27;n++)CommunicateThisDir[n] = faces[n] ;break; case STENCIL_SHAPE_NO_CORNERS:for(n=0;n<27;n++)CommunicateThisDir[n] = faces[n] + edges[n] ;break; } int sendBox,recvBox; int stage; int _rank; int ghost,numGhosts,numGhostsRemote; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // traverse my list of boxes and create a lists of neighboring boxes and neighboring ranks GZ_type *ghostsToSend = (GZ_type*)malloc(26*level->num_my_boxes*sizeof(GZ_type)); // There are at most 26 neighbors per box. int *sendRanks = ( int*)malloc(26*level->num_my_boxes*sizeof( int)); // There are at most 26 neighbors per box. if(level->num_my_boxes>0){ if(ghostsToSend == NULL){fprintf(stderr,"malloc failed - build_exchange_ghosts/ghostsToSend\n");exit(0);} if(sendRanks == NULL){fprintf(stderr,"malloc failed - build_exchange_ghosts/sendRanks \n");exit(0);} } numGhosts = 0; numGhostsRemote = 0; for(sendBox=0;sendBox<level->num_my_boxes;sendBox++){ int di,dj,dk; for(dk=-1;dk<=1;dk++){ for(dj=-1;dj<=1;dj++){ for(di=-1;di<=1;di++){ int dir = 13+di+3*dj+9*dk;if(CommunicateThisDir[dir]){ int myBoxID = level->my_boxes[sendBox].global_box_id; int myBox_i = level->my_boxes[sendBox].low.i / level->box_dim; int myBox_j = level->my_boxes[sendBox].low.j / level->box_dim; int myBox_k = level->my_boxes[sendBox].low.k / level->box_dim; int neighborBoxID = -1; if(level->boundary_condition.type == BC_PERIODIC){ int neighborBox_i = ( myBox_i + di + level->boxes_in.i) % level->boxes_in.i; int neighborBox_j = ( myBox_j + dj + level->boxes_in.j) % level->boxes_in.j; int neighborBox_k = ( myBox_k + dk + level->boxes_in.k) % level->boxes_in.k; neighborBoxID = neighborBox_i + neighborBox_j*level->boxes_in.i + neighborBox_k*level->boxes_in.i*level->boxes_in.j; }else{ int neighborBox_i = ( myBox_i + di ); int neighborBox_j = ( myBox_j + dj ); int neighborBox_k = ( myBox_k + dk ); if( (neighborBox_i>=0) && (neighborBox_i<level->boxes_in.i) && (neighborBox_j>=0) && (neighborBox_j<level->boxes_in.j) && (neighborBox_k>=0) && (neighborBox_k<level->boxes_in.k) ){ // i.e. the neighbor is a valid box neighborBoxID = neighborBox_i + neighborBox_j*level->boxes_in.i + neighborBox_k*level->boxes_in.i*level->boxes_in.j; } } if(neighborBoxID>=0){ if( level->rank_of_box[neighborBoxID] != -1 ){ ghostsToSend[numGhosts].sendRank = level->my_rank; ghostsToSend[numGhosts].sendBoxID = myBoxID; ghostsToSend[numGhosts].sendBox = sendBox; ghostsToSend[numGhosts].sendDir = dir; ghostsToSend[numGhosts].recvRank = level->rank_of_box[neighborBoxID]; ghostsToSend[numGhosts].recvBoxID = neighborBoxID; ghostsToSend[numGhosts].recvBox = -1; if( level->rank_of_box[neighborBoxID] != level->my_rank ){ sendRanks[numGhostsRemote++] = level->rank_of_box[neighborBoxID]; }else{ int recvBox=0;while(level->my_boxes[recvBox].global_box_id!=neighborBoxID)recvBox++; // search my list of boxes for the appropriate recvBox index ghostsToSend[numGhosts].recvBox = recvBox; } numGhosts++; }} }}}} } // sort boxes by sendRank(==my rank) then by sendBoxID... ensures the sends and receive buffers are always sorted by sendBoxID... qsort(ghostsToSend,numGhosts ,sizeof(GZ_type),qsortGZ ); // sort the lists of neighboring ranks and remove duplicates... qsort(sendRanks ,numGhostsRemote,sizeof( int),qsortInt); int numSendRanks=0;_rank=-1;for(ghost=0;ghost<numGhostsRemote;ghost++)if(sendRanks[ghost] != _rank){_rank=sendRanks[ghost];sendRanks[numSendRanks++]=sendRanks[ghost];} // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // in a two-stage process, traverse the list of ghosts and allocate the pack/local lists as well as the MPI buffers, and then populate the pack/local lists level->exchange_ghosts[shape].num_sends = numSendRanks; level->exchange_ghosts[shape].send_ranks = (int*)malloc(numSendRanks*sizeof(int)); level->exchange_ghosts[shape].send_sizes = (int*)malloc(numSendRanks*sizeof(int)); level->exchange_ghosts[shape].send_buffers = (double**)malloc(numSendRanks*sizeof(double*)); if(numSendRanks>0){ if(level->exchange_ghosts[shape].send_ranks ==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].send_ranks\n",shape);exit(0);} if(level->exchange_ghosts[shape].send_sizes ==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].send_sizes\n",shape);exit(0);} if(level->exchange_ghosts[shape].send_buffers==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].send_buffers\n",shape);exit(0);} } level->exchange_ghosts[shape].blocks[0] = NULL; level->exchange_ghosts[shape].blocks[1] = NULL; level->exchange_ghosts[shape].num_blocks[0] = 0; level->exchange_ghosts[shape].num_blocks[1] = 0; level->exchange_ghosts[shape].allocated_blocks[0] = 0; level->exchange_ghosts[shape].allocated_blocks[1] = 0; for(stage=0;stage<=1;stage++){ // stage=0... traverse the list and calculate the buffer sizes // stage=1... allocate MPI send buffers, traverse the list, and populate the unpack/local lists... int neighbor; for(neighbor=0;neighbor<numSendRanks;neighbor++){ if(stage==1){ level->exchange_ghosts[shape].send_buffers[neighbor] = (double*)malloc(level->exchange_ghosts[shape].send_sizes[neighbor]*sizeof(double)); if(level->exchange_ghosts[shape].send_sizes[neighbor]>0) if(level->exchange_ghosts[shape].send_buffers[neighbor]==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].send_buffers[neighbor]\n",shape);exit(0);} memset(level->exchange_ghosts[shape].send_buffers[neighbor], 0,level->exchange_ghosts[shape].send_sizes[neighbor]*sizeof(double)); } level->exchange_ghosts[shape].send_ranks[neighbor]=sendRanks[neighbor]; level->exchange_ghosts[shape].send_sizes[neighbor]=0; } for(ghost=0;ghost<numGhosts;ghost++){ int dim_i=-1, dim_j=-1, dim_k=-1; int send_i=-1,send_j=-1,send_k=-1; int recv_i=-1,recv_j=-1,recv_k=-1; // decode ghostsToSend[ghost].sendDir (direction sent) into di/dj/dk int di = ((ghostsToSend[ghost].sendDir % 3) )-1; int dj = ((ghostsToSend[ghost].sendDir % 9)/3)-1; int dk = ((ghostsToSend[ghost].sendDir / 9) )-1; switch(di){ // direction relative to sender case -1:send_i=0; dim_i=level->box_ghosts;recv_i= level->box_dim; break; case 0:send_i=0; dim_i=level->box_dim; recv_i=0; break; case 1:send_i=level->box_dim-level->box_ghosts;dim_i=level->box_ghosts;recv_i=0-level->box_ghosts;break; } switch(dj){ // direction relative to sender case -1:send_j=0; dim_j=level->box_ghosts;recv_j= level->box_dim; break; case 0:send_j=0; dim_j=level->box_dim; recv_j=0; break; case 1:send_j=level->box_dim-level->box_ghosts;dim_j=level->box_ghosts;recv_j=0-level->box_ghosts;break; } switch(dk){ // direction relative to sender case -1:send_k=0; dim_k=level->box_ghosts;recv_k= level->box_dim; break; case 0:send_k=0; dim_k=level->box_dim; recv_k=0; break; case 1:send_k=level->box_dim-level->box_ghosts;dim_k=level->box_ghosts;recv_k=0-level->box_ghosts;break; } // determine if this ghost requires a pack or local exchange int LocalExchange; // 0 = pack list, 1 = local exchange list if(ghostsToSend[ghost].recvRank != level->my_rank){ LocalExchange=0; // pack neighbor=0;while(level->exchange_ghosts[shape].send_ranks[neighbor] != ghostsToSend[ghost].recvRank)neighbor++; }else{ LocalExchange=1; // local neighbor=-1; } if(stage==1){ if(LocalExchange) // append to the local exchange list... append_block_to_list(&(level->exchange_ghosts[shape].blocks[1]),&(level->exchange_ghosts[shape].allocated_blocks[1]),&(level->exchange_ghosts[shape].num_blocks[1]), /* dim.i = */ dim_i, /* dim.j = */ dim_j, /* dim.k = */ dim_k, /* read.box = */ ghostsToSend[ghost].sendBox, /* read.ptr = */ NULL, /* read.i = */ send_i, /* read.j = */ send_j, /* read.k = */ send_k, /* read.jStride = */ level->my_boxes[ghostsToSend[ghost].sendBox].jStride, /* read.kStride = */ level->my_boxes[ghostsToSend[ghost].sendBox].kStride, /* read.scale = */ 1, /* write.box = */ ghostsToSend[ghost].recvBox, /* write.ptr = */ NULL, /* write.i = */ recv_i, /* write.j = */ recv_j, /* write.k = */ recv_k, /* write.jStride = */ level->my_boxes[ghostsToSend[ghost].recvBox].jStride, /* write.kStride = */ level->my_boxes[ghostsToSend[ghost].recvBox].kStride, /* write.scale = */ 1, /* blockcopy_i = */ BLOCKCOPY_TILE_I, // default /* blockcopy_j = */ BLOCKCOPY_TILE_J, // default /* blockcopy_k = */ BLOCKCOPY_TILE_K, // default /* subtype = */ 0 ); else // append to the MPI pack list... append_block_to_list(&(level->exchange_ghosts[shape].blocks[0]),&(level->exchange_ghosts[shape].allocated_blocks[0]),&(level->exchange_ghosts[shape].num_blocks[0]), /* dim.i = */ dim_i, /* dim.j = */ dim_j, /* dim.k = */ dim_k, /* read.box = */ ghostsToSend[ghost].sendBox, /* read.ptr = */ NULL, /* read.i = */ send_i, /* read.j = */ send_j, /* read.k = */ send_k, /* read.jStride = */ level->my_boxes[ghostsToSend[ghost].sendBox].jStride, /* read.kStride = */ level->my_boxes[ghostsToSend[ghost].sendBox].kStride, /* read.scale = */ 1, /* write.box = */ -1, /* write.ptr = */ level->exchange_ghosts[shape].send_buffers[neighbor], // NOTE, 1. count _sizes, 2. allocate _buffers, 3. populate blocks /* write.i = */ level->exchange_ghosts[shape].send_sizes[neighbor], // current offset in the MPI send buffer /* write.j = */ 0, /* write.k = */ 0, /* write.jStride = */ dim_i, // contiguous block /* write.kStride = */ dim_i*dim_j, // contiguous block /* write.scale = */ 1, /* blockcopy_i = */ BLOCKCOPY_TILE_I, // default /* blockcopy_j = */ BLOCKCOPY_TILE_J, // default /* blockcopy_k = */ BLOCKCOPY_TILE_K, // default /* subtype = */ 0 );} if(neighbor>=0)level->exchange_ghosts[shape].send_sizes[neighbor]+=dim_i*dim_j*dim_k; } // ghost for-loop } // stage for-loop // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // free temporary storage... free(ghostsToSend); free(sendRanks); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // traverse my list of boxes and create a lists of neighboring boxes and neighboring ranks GZ_type *ghostsToRecv = (GZ_type*)malloc(26*level->num_my_boxes*sizeof(GZ_type)); // There are at most 26 neighbors per box. int *recvRanks = ( int*)malloc(26*level->num_my_boxes*sizeof( int)); // There are at most 26 neighbors per box. if(level->num_my_boxes>0){ if(ghostsToRecv == NULL){fprintf(stderr,"malloc failed - build_exchange_ghosts/ghostsToRecv\n");exit(0);} if(recvRanks == NULL){fprintf(stderr,"malloc failed - build_exchange_ghosts/recvRanks \n");exit(0);} } numGhosts = 0; numGhostsRemote = 0; for(recvBox=0;recvBox<level->num_my_boxes;recvBox++){ int di,dj,dk; for(dk=-1;dk<=1;dk++){ for(dj=-1;dj<=1;dj++){ for(di=-1;di<=1;di++){ int dir = 13+di+3*dj+9*dk;if(CommunicateThisDir[dir]){ int myBoxID = level->my_boxes[recvBox].global_box_id; int myBox_i = level->my_boxes[recvBox].low.i / level->box_dim; int myBox_j = level->my_boxes[recvBox].low.j / level->box_dim; int myBox_k = level->my_boxes[recvBox].low.k / level->box_dim; int neighborBoxID = -1; if(level->boundary_condition.type == BC_PERIODIC){ int neighborBox_i = ( myBox_i + di + level->boxes_in.i) % level->boxes_in.i; int neighborBox_j = ( myBox_j + dj + level->boxes_in.j) % level->boxes_in.j; int neighborBox_k = ( myBox_k + dk + level->boxes_in.k) % level->boxes_in.k; neighborBoxID = neighborBox_i + neighborBox_j*level->boxes_in.i + neighborBox_k*level->boxes_in.i*level->boxes_in.j; }else{ int neighborBox_i = ( myBox_i + di ); int neighborBox_j = ( myBox_j + dj ); int neighborBox_k = ( myBox_k + dk ); if( (neighborBox_i>=0) && (neighborBox_i<level->boxes_in.i) && (neighborBox_j>=0) && (neighborBox_j<level->boxes_in.j) && (neighborBox_k>=0) && (neighborBox_k<level->boxes_in.k) ){ // i.e. the neighbor is a valid box neighborBoxID = neighborBox_i + neighborBox_j*level->boxes_in.i + neighborBox_k*level->boxes_in.i*level->boxes_in.j; } } if(neighborBoxID>=0){ if( (level->rank_of_box[neighborBoxID] != -1) && (level->rank_of_box[neighborBoxID] != level->my_rank) ){ ghostsToRecv[numGhosts].sendRank = level->rank_of_box[neighborBoxID]; ghostsToRecv[numGhosts].sendBoxID = neighborBoxID; ghostsToRecv[numGhosts].sendBox = -1; ghostsToRecv[numGhosts].sendDir = 26-dir; ghostsToRecv[numGhosts].recvRank = level->my_rank; ghostsToRecv[numGhosts].recvBoxID = myBoxID; ghostsToRecv[numGhosts].recvBox = recvBox; numGhosts++; recvRanks[numGhostsRemote++] = level->rank_of_box[neighborBoxID]; }} }}}} } // sort boxes by sendRank then by sendBoxID... ensures the recvs and receive buffers are always sorted by sendBoxID... qsort(ghostsToRecv,numGhosts ,sizeof(GZ_type),qsortGZ ); // sort the lists of neighboring ranks and remove duplicates... qsort(recvRanks ,numGhostsRemote,sizeof( int),qsortInt); int numRecvRanks=0;_rank=-1;for(ghost=0;ghost<numGhostsRemote;ghost++)if(recvRanks[ghost] != _rank){_rank=recvRanks[ghost];recvRanks[numRecvRanks++]=recvRanks[ghost];} // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // in a two-stage process, traverse the list of ghosts and allocate the unpack lists as well as the MPI buffers, and then populate the unpack list level->exchange_ghosts[shape].num_recvs = numRecvRanks; level->exchange_ghosts[shape].recv_ranks = (int*)malloc(numRecvRanks*sizeof(int)); level->exchange_ghosts[shape].recv_sizes = (int*)malloc(numRecvRanks*sizeof(int)); level->exchange_ghosts[shape].recv_buffers = (double**)malloc(numRecvRanks*sizeof(double*)); if(numRecvRanks>0){ if(level->exchange_ghosts[shape].recv_ranks ==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].recv_ranks\n",shape);exit(0);} if(level->exchange_ghosts[shape].recv_sizes ==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].recv_sizes\n",shape);exit(0);} if(level->exchange_ghosts[shape].recv_buffers==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].recv_buffers\n",shape);exit(0);} } level->exchange_ghosts[shape].blocks[2] = NULL; level->exchange_ghosts[shape].num_blocks[2] = 0; level->exchange_ghosts[shape].allocated_blocks[2] = 0; for(stage=0;stage<=1;stage++){ // stage=0... traverse the list and calculate the buffer sizes // stage=1... allocate MPI recv buffers, traverse the list, and populate the unpack/local lists... int neighbor; for(neighbor=0;neighbor<numRecvRanks;neighbor++){ if(stage==1){ level->exchange_ghosts[shape].recv_buffers[neighbor] = (double*)malloc(level->exchange_ghosts[shape].recv_sizes[neighbor]*sizeof(double)); if(level->exchange_ghosts[shape].recv_sizes[neighbor]>0) if(level->exchange_ghosts[shape].recv_buffers[neighbor]==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].recv_buffers[neighbor]\n",shape);exit(0);} memset(level->exchange_ghosts[shape].recv_buffers[neighbor], 0,level->exchange_ghosts[shape].recv_sizes[neighbor]*sizeof(double)); } level->exchange_ghosts[shape].recv_ranks[neighbor]=recvRanks[neighbor]; level->exchange_ghosts[shape].recv_sizes[neighbor]=0; } for(ghost=0;ghost<numGhosts;ghost++){ int dim_i=-1, dim_j=-1, dim_k=-1; //int send_i=-1,send_j=-1,send_k=-1; int recv_i=-1,recv_j=-1,recv_k=-1; // decode ghostsToRecv[ghost].sendDir (direction sent) into di/dj/dk int di = ((ghostsToRecv[ghost].sendDir % 3) )-1; int dj = ((ghostsToRecv[ghost].sendDir % 9)/3)-1; int dk = ((ghostsToRecv[ghost].sendDir / 9) )-1; switch(di){ // direction relative to sender case -1:dim_i=level->box_ghosts;recv_i= level->box_dim; break; case 0:dim_i=level->box_dim; recv_i=0; break; case 1:dim_i=level->box_ghosts;recv_i=0-level->box_ghosts;break; } switch(dj){ // direction relative to sender case -1:dim_j=level->box_ghosts;recv_j= level->box_dim; break; case 0:dim_j=level->box_dim; recv_j=0; break; case 1:dim_j=level->box_ghosts;recv_j=0-level->box_ghosts;break; } switch(dk){ // direction relative to sender case -1:dim_k=level->box_ghosts;recv_k= level->box_dim; break; case 0:dim_k=level->box_dim; recv_k=0; break; case 1:dim_k=level->box_ghosts;recv_k=0-level->box_ghosts;break; } // determine if this ghost requires a pack or local exchange neighbor=0;while(level->exchange_ghosts[shape].recv_ranks[neighbor] != ghostsToRecv[ghost].sendRank)neighbor++; if(stage==1)append_block_to_list(&(level->exchange_ghosts[shape].blocks[2]),&(level->exchange_ghosts[shape].allocated_blocks[2]),&(level->exchange_ghosts[shape].num_blocks[2]), /*dim.i = */ dim_i, /*dim.j = */ dim_j, /*dim.k = */ dim_k, /*read.box = */ -1, /*read.ptr = */ level->exchange_ghosts[shape].recv_buffers[neighbor], // NOTE, 1. count _sizes, 2. allocate _buffers, 3. populate blocks /*read.i = */ level->exchange_ghosts[shape].recv_sizes[neighbor], // current offset in the MPI recv buffer /*read.j = */ 0, /*read.k = */ 0, /*read.jStride = */ dim_i, // contiguous block /*read.kStride = */ dim_i*dim_j, // contiguous block /*read.scale = */ 1, /*write.box = */ ghostsToRecv[ghost].recvBox, /*write.ptr = */ NULL, /*write.i = */ recv_i, /*write.j = */ recv_j, /*write.k = */ recv_k, /*write.jStride = */ level->my_boxes[ghostsToRecv[ghost].recvBox].jStride, /*write.kStride = */ level->my_boxes[ghostsToRecv[ghost].recvBox].kStride, /*write.scale = */ 1, /* blockcopy_i = */ BLOCKCOPY_TILE_I, // default /* blockcopy_j = */ BLOCKCOPY_TILE_J, // default /* blockcopy_k = */ BLOCKCOPY_TILE_K, // default /* subtype = */ 0 ); if(neighbor>=0)level->exchange_ghosts[shape].recv_sizes[neighbor]+=dim_i*dim_j*dim_k; } // ghost for-loop } // stage for-loop // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // free temporary storage... free(ghostsToRecv); free(recvRanks); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // malloc MPI requests/status arrays #ifdef USE_MPI level->exchange_ghosts[shape].requests = (MPI_Request*)malloc((level->exchange_ghosts[shape].num_sends+level->exchange_ghosts[shape].num_recvs)*sizeof(MPI_Request)); level->exchange_ghosts[shape].status = (MPI_Status *)malloc((level->exchange_ghosts[shape].num_sends+level->exchange_ghosts[shape].num_recvs)*sizeof(MPI_Status )); if((level->exchange_ghosts[shape].num_sends+level->exchange_ghosts[shape].num_recvs)>0){ if(level->exchange_ghosts[shape].requests==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].requests\n",shape);exit(0);} if(level->exchange_ghosts[shape].status ==NULL){fprintf(stderr,"malloc failed - exchange_ghosts[%d].status\n",shape);exit(0);} } #endif // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #ifdef BLOCK_SPATIAL_SORT // sort all the resultant blocks by box,k,j,i (good locality) qsort(level->exchange_ghosts[shape].blocks[0],level->exchange_ghosts[shape].num_blocks[0],sizeof(blockCopy_type),qsortBlock); qsort(level->exchange_ghosts[shape].blocks[1],level->exchange_ghosts[shape].num_blocks[1],sizeof(blockCopy_type),qsortBlock); qsort(level->exchange_ghosts[shape].blocks[2],level->exchange_ghosts[shape].num_blocks[2],sizeof(blockCopy_type),qsortBlock); #endif } //--------------------------------------------------------------------------------------------------------------------------------------------------- // create the pointers in level_type to the contiguous vector FP data (useful for bulk copies to/from accelerators) // create the pointers in each box to their respective segment of the level's vector FP data (useful for box-relative operators) // if( (level->numVectors > 0) && (numVectors > level->numVectors) ) then allocate additional space for (numVectors-level->numVectors) and copy old leve->numVectors data void create_vectors(level_type *level, int numVectors){ if(numVectors <= level->numVectors)return; // already have enough space double * old_vectors_base = level->vectors_base; // save a pointer to the originally allocated data for subsequent free() double * old_vector0 = NULL; if(level->numVectors>0)old_vector0 = level->vectors[0]; // save a pointer to old FP data to copy // calculate the size of each box... level->box_jStride = (level->box_dim+2*level->box_ghosts);while(level->box_jStride % BOX_ALIGN_JSTRIDE)level->box_jStride++; // pencil level->box_kStride = level->box_jStride*(level->box_dim+2*level->box_ghosts);while(level->box_kStride % BOX_ALIGN_KSTRIDE)level->box_kStride++; // plane level->box_volume = level->box_kStride*(level->box_dim+2*level->box_ghosts);while(level->box_volume % BOX_ALIGN_VOLUME )level->box_volume++; // volume #define VECTOR_MALLOC_BULK #ifdef VECTOR_MALLOC_BULK // allocate one aligned, double-precision array and divide it among vectors... uint64_t malloc_size = (uint64_t)numVectors*level->num_my_boxes*level->box_volume*sizeof(double) + 4096; level->vectors_base = (double*)malloc(malloc_size); if((numVectors>0)&&(level->vectors_base==NULL)){fprintf(stderr,"malloc failed - level->vectors_base\n");exit(0);} double * tmpbuf = level->vectors_base; while( (uint64_t)(tmpbuf+level->box_ghosts*(1+level->box_jStride+level->box_kStride)) & 0xff ){tmpbuf++;} // align first *non-ghost* zone element of first component to a 256-Byte boundary uint64_t ofs; #ifdef _OPENMP #pragma omp parallel for #endif for(ofs=0;ofs<(uint64_t)numVectors*level->num_my_boxes*level->box_volume;ofs++){tmpbuf[ofs]=0.0;} // Faster in MPI+OpenMP environments, but not NUMA-aware // if there is existing FP data... copy it, then free old data and pointer array if(level->numVectors>0){ memcpy(tmpbuf,old_vector0,(uint64_t)level->numVectors*level->num_my_boxes*level->box_volume*sizeof(double)); // FIX... omp thread ??? if(old_vectors_base)free(old_vectors_base); // free old data... } // allocate an array of pointers which point to the union of boxes for each vector // NOTE, this requires just one copyin per vector to an accelerator rather than requiring one copyin per box per vector if(level->numVectors>0)free(level->vectors); // free any previously allocated vector array level->vectors = (double **)malloc(numVectors*sizeof(double*)); if((numVectors>0)&&(level->vectors==NULL)){fprintf(stderr,"malloc failed - level->vectors\n");exit(0);} uint64_t c;for(c=0;c<numVectors;c++){level->vectors[c] = tmpbuf + (uint64_t)c*level->num_my_boxes*level->box_volume;} #else // allocate vectors individually (simple, but may cause conflict misses) double ** old_vectors = level->vectors; level->vectors = (double **)malloc(numVectors*sizeof(double*)); uint64_t c; for(c= 0;c<level->numVectors;c++){level->vectors[c] = old_vectors[c];} for(c=level->numVectors;c< numVectors;c++){ level->vectors[c] = (double*)malloc((uint64_t)level->num_my_boxes*level->box_volume*sizeof(double)); uint64_t ofs; #ifdef _OPENMP #pragma omp parallel for #endif for(ofs=0;ofs<(uint64_t)level->num_my_boxes*level->box_volume;ofs++){level->vectors[c][ofs]=0.0;} // Faster in MPI+OpenMP environments, but not NUMA-aware } free(old_vectors); #endif // build the list of boxes... int box=0; int i,j,k; for(k=0;k<level->boxes_in.k;k++){ for(j=0;j<level->boxes_in.j;j++){ for(i=0;i<level->boxes_in.i;i++){ int jStride = level->boxes_in.i; int kStride = level->boxes_in.i*level->boxes_in.j; int b=i + j*jStride + k*kStride; if(level->rank_of_box[b]==level->my_rank){ if(level->numVectors>0)free(level->my_boxes[box].vectors); // free previously allocated vector array level->my_boxes[box].vectors = (double **)malloc(numVectors*sizeof(double*)); if((numVectors>0)&&(level->my_boxes[box].vectors==NULL)){fprintf(stderr,"malloc failed - level->my_boxes[box].vectors\n");exit(0);} uint64_t c;for(c=0;c<numVectors;c++){level->my_boxes[box].vectors[c] = level->vectors[c] + (uint64_t)box*level->box_volume;} level->my_boxes[box].numVectors = numVectors; level->my_boxes[box].dim = level->box_dim; level->my_boxes[box].ghosts = level->box_ghosts; level->my_boxes[box].jStride = level->box_jStride; level->my_boxes[box].kStride = level->box_kStride; level->my_boxes[box].volume = level->box_volume; level->my_boxes[box].low.i = i*level->box_dim; level->my_boxes[box].low.j = j*level->box_dim; level->my_boxes[box].low.k = k*level->box_dim; level->my_boxes[box].global_box_id = b; box++; }}}} // level now has created/initialized vector FP data level->numVectors = numVectors; } //--------------------------------------------------------------------------------------------------------------------------------------------------- // create a level by populating the basic data structure, distribute boxes within the level among processes, allocate memory, and create any auxilliaries // box_ghosts must be >= stencil_get_radius() // numVectors represents an estimate of the number of vectors needed in this level. Additional vectors can be added via subsequent calls to create_vectors() void create_level(level_type *level, int boxes_in_i, int box_dim, int box_ghosts, int numVectors, int domain_boundary_condition, int my_rank, int num_ranks){ int box; int TotalBoxes = boxes_in_i*boxes_in_i*boxes_in_i; if(my_rank==0){ //if(domain_boundary_condition==BC_DIRICHLET)fprintf(stdout,"\nattempting to create a %d^3 level (with Dirichlet BC) using a %d^3 grid of %d^3 boxes and %d tasks...\n",box_dim*boxes_in_i,boxes_in_i,box_dim,num_ranks); //if(domain_boundary_condition==BC_PERIODIC )fprintf(stdout,"\nattempting to create a %d^3 level (with Periodic BC) using a %d^3 grid of %d^3 boxes and %d tasks...\n", box_dim*boxes_in_i,boxes_in_i,box_dim,num_ranks); fprintf(stdout,"\nattempting to create a %d^3 level from %d x %d^3 boxes distributed among %d tasks...\n", box_dim*boxes_in_i,TotalBoxes,box_dim,num_ranks); if(domain_boundary_condition==BC_DIRICHLET)fprintf(stdout," boundary condition = BC_DIRICHLET\n"); if(domain_boundary_condition==BC_PERIODIC )fprintf(stdout," boundary condition = BC_PERIODIC\n"); } int omp_threads = 1; #ifdef _OPENMP #pragma omp parallel { #pragma omp master { omp_threads = omp_get_num_threads(); } } #endif if(box_ghosts < stencil_get_radius() ){ if(my_rank==0)fprintf(stderr,"ghosts(%d) must be >= stencil_get_radius(%d)\n",box_ghosts,stencil_get_radius()); exit(0); } level->box_dim = box_dim; level->box_ghosts = box_ghosts; level->numVectors = 0; // no vectors have been allocated yet level->vectors_base = NULL; // pointer returned by bulk malloc level->vectors = NULL; // pointers to individual vectors level->boxes_in.i = boxes_in_i; level->boxes_in.j = boxes_in_i; level->boxes_in.k = boxes_in_i; level->dim.i = box_dim*level->boxes_in.i; level->dim.j = box_dim*level->boxes_in.j; level->dim.k = box_dim*level->boxes_in.k; level->active = 1; level->my_rank = my_rank; level->num_ranks = num_ranks; level->boundary_condition.type = domain_boundary_condition; level->must_subtract_mean = -1; level->num_threads = omp_threads; level->my_blocks = NULL; level->num_my_blocks = 0; level->allocated_blocks = 0; level->tag = log2(level->dim.i); level->fluxes = NULL; // allocate 3D array of integers to hold the MPI rank of the corresponding box and initialize to -1 (unassigned) level->rank_of_box = (int*)malloc(level->boxes_in.i*level->boxes_in.j*level->boxes_in.k*sizeof(int)); if(level->rank_of_box==NULL){fprintf(stderr,"malloc of level->rank_of_box failed\n");exit(0);} for(box=0;box<level->boxes_in.i*level->boxes_in.j*level->boxes_in.k;box++){level->rank_of_box[box]=-1;} // -1 denotes that there is no actual box assigned to this region // parallelize the level (i.e. assign a process rank to each box)... #ifdef DECOMPOSE_LEX // lexicographical ordering... good load balance, potentially high bisection bandwidth requirements, bad surface:volume ratio when #boxes/proc is large if(my_rank==0){fprintf(stdout," Decomposing level via lexicographical ordering... ");fflush(stdout);} decompose_level_lex(level->rank_of_box,level->boxes_in.i,level->boxes_in.j,level->boxes_in.k,num_ranks); #elif DECOMPOSE_BISECTION_SPECIAL // recursive partitioning by primes if(my_rank==0){fprintf(stdout," Decomposing level via partitioning by primes... ");fflush(stdout);} decompose_level_bisection_special(level->rank_of_box,level->boxes_in.i,level->boxes_in.i*level->boxes_in.j,0,0,0,level->boxes_in.i,level->boxes_in.j,level->boxes_in.k,0,num_ranks); #elif DECOMPOSE_BISECTION // recursive bisection if(my_rank==0){fprintf(stdout," Decomposing level via recursive bisection... ");fflush(stdout);} decompose_level_bisection(level->rank_of_box,level->boxes_in.i,level->boxes_in.i*level->boxes_in.j,0,0,0,level->boxes_in.i,level->boxes_in.j,level->boxes_in.k,num_ranks,0,level->boxes_in.i*level->boxes_in.j*level->boxes_in.k); #else//#elif DECOMPOSE_ZMORT if(my_rank==0){fprintf(stdout," Decomposing level via Z-mort ordering... ");fflush(stdout);} #if 0 // Z-Mort over a power of two bounding box skipping boxes outside the domain int idim_padded=1;while(idim_padded<level->boxes_in.i)idim_padded*=2; int jdim_padded=1;while(jdim_padded<level->boxes_in.j)jdim_padded*=2; int kdim_padded=1;while(kdim_padded<level->boxes_in.k)kdim_padded*=2; #else // Z-Mort over the valid domain wtih odd-sized base cases (i.e. zmort on 3x3) int idim_padded=level->boxes_in.i; int jdim_padded=level->boxes_in.j; int kdim_padded=level->boxes_in.k; #endif decompose_level_zmort(level->rank_of_box,level->boxes_in.i,level->boxes_in.j,level->boxes_in.k,0,0,0,idim_padded,jdim_padded,kdim_padded,num_ranks,0,level->boxes_in.i*level->boxes_in.j*level->boxes_in.k); #endif if(my_rank==0){fprintf(stdout,"done\n");fflush(stdout);} //print_decomposition(level);// for debug purposes only // calculate how many boxes I own... level->num_my_boxes=0; for(box=0;box<level->boxes_in.i*level->boxes_in.j*level->boxes_in.k;box++){if(level->rank_of_box[box]==level->my_rank)level->num_my_boxes++;} level->my_boxes = (box_type*)malloc(level->num_my_boxes*sizeof(box_type)); if((level->num_my_boxes>0)&&(level->my_boxes==NULL)){fprintf(stderr,"malloc failed - create_level/level->my_boxes\n");exit(0);} // allocate flattened vector FP data and create pointers... if(my_rank==0){fprintf(stdout," Allocating vectors... ");fflush(stdout);} create_vectors(level,numVectors); if(my_rank==0){fprintf(stdout,"done\n");fflush(stdout);} // Build and auxilarlly data structure that flattens boxes into blocks... for(box=0;box<level->num_my_boxes;box++){ int blockcopy_i = BLOCKCOPY_TILE_I; int blockcopy_j = BLOCKCOPY_TILE_J; int blockcopy_k = BLOCKCOPY_TILE_K; append_block_to_list(&(level->my_blocks),&(level->allocated_blocks),&(level->num_my_blocks), /* dim.i = */ level->my_boxes[box].dim, /* dim.j = */ level->my_boxes[box].dim, /* dim.k = */ level->my_boxes[box].dim, /* read.box = */ box, /* read.ptr = */ NULL, /* read.i = */ 0, /* read.j = */ 0, /* read.k = */ 0, /* read.jStride = */ level->my_boxes[box].jStride, /* read.kStride = */ level->my_boxes[box].kStride, /* read.scale = */ 1, /* write.box = */ box, /* write.ptr = */ NULL, /* write.i = */ 0, /* write.j = */ 0, /* write.k = */ 0, /* write.jStride = */ level->my_boxes[box].jStride, /* write.kStride = */ level->my_boxes[box].kStride, /* write.scale = */ 1, /* blockcopy_i = */ blockcopy_i, /* blockcopy_j = */ blockcopy_j, /* blockcopy_k = */ blockcopy_k, /* subtype = */ 0 ); } // build an assist structure for Gauss Seidel Red Black that would facilitate unrolling and SIMDization... level->RedBlack_base = NULL; level->RedBlack_FP = NULL; if(level->num_my_boxes){ int i,j; int kStride = level->my_boxes[0].kStride; int jStride = level->my_boxes[0].jStride; level->RedBlack_base = (double*)malloc(2*kStride*sizeof(double)+256); // used for free() level->RedBlack_FP = level->RedBlack_base; // aligned version // align first *non-ghost* zone element to a 64-Byte boundary... while( (uint64_t)(level->RedBlack_FP + level->box_ghosts*(1+level->box_jStride)) & 0x3f ){level->RedBlack_FP++;} // initialize RedBlack array... for(j=0-level->box_ghosts;j<level->box_dim+level->box_ghosts;j++){ for(i=0-level->box_ghosts;i<level->box_dim+level->box_ghosts;i++){ int ij = (i+level->box_ghosts) + (j+level->box_ghosts)*jStride; if((i^j^1)&0x1){ level->RedBlack_FP[ij ]=1.0; level->RedBlack_FP[ij+kStride]=0.0; }else{ level->RedBlack_FP[ij ]=0.0; level->RedBlack_FP[ij+kStride]=1.0; } // Never update ghost zones //if( (i<0) || (i>=level->box_dim) || (j<0) || (j>=level->box_dim) ){ // level->RedBlack_FP[ij ]=0.0; // level->RedBlack_FP[ij+kStride]=0.0; //} }} } int shape; // create mini program for each stencil shape to perform a ghost zone exchange... for(shape=0;shape<STENCIL_MAX_SHAPES;shape++)build_exchange_ghosts( level,shape); // create mini program for each stencil shape to perform a boundary condition... for(shape=0;shape<STENCIL_MAX_SHAPES;shape++)build_boundary_conditions(level,shape); // duplicate MPI_COMM_WORLD to be the communicator for each level #ifdef USE_MPI if(my_rank==0){fprintf(stdout," Duplicating MPI_COMM_WORLD... ");fflush(stdout);} double time_start = MPI_Wtime(); MPI_Comm_dup(MPI_COMM_WORLD,&level->MPI_COMM_ALLREDUCE); double time_end = MPI_Wtime(); double time_in_comm_dup = 0; double time_in_comm_dup_send = time_end-time_start; MPI_Allreduce(&time_in_comm_dup_send,&time_in_comm_dup,1,MPI_DOUBLE,MPI_MAX,MPI_COMM_WORLD); if(my_rank==0){fprintf(stdout,"done (%0.6f seconds)\n",time_in_comm_dup);fflush(stdout);} #endif // report on potential load imbalance int BoxesPerProcess = level->num_my_boxes; #ifdef USE_MPI int BoxesPerProcessSend = level->num_my_boxes; MPI_Allreduce(&BoxesPerProcessSend,&BoxesPerProcess,1,MPI_INT,MPI_MAX,MPI_COMM_WORLD); #endif if(my_rank==0){fprintf(stdout," Calculating boxes per process... target=%0.3f, max=%d\n",(double)TotalBoxes/(double)num_ranks,BoxesPerProcess);} } //--------------------------------------------------------------------------------------------------------------------------------------------------- // zeros are the timers within this level // useful if one wishes to separate setup(build) timing from solve timing void reset_level_timers(level_type *level){ // cycle counters information... level->timers.smooth = 0; level->timers.apply_op = 0; level->timers.residual = 0; level->timers.blas1 = 0; level->timers.blas3 = 0; level->timers.boundary_conditions = 0; level->timers.restriction_total = 0; level->timers.restriction_pack = 0; level->timers.restriction_local = 0; level->timers.restriction_unpack = 0; level->timers.restriction_recv = 0; level->timers.restriction_send = 0; level->timers.restriction_wait = 0; level->timers.interpolation_total = 0; level->timers.interpolation_pack = 0; level->timers.interpolation_local = 0; level->timers.interpolation_unpack = 0; level->timers.interpolation_recv = 0; level->timers.interpolation_send = 0; level->timers.interpolation_wait = 0; level->timers.ghostZone_total = 0; level->timers.ghostZone_pack = 0; level->timers.ghostZone_local = 0; level->timers.ghostZone_unpack = 0; level->timers.ghostZone_recv = 0; level->timers.ghostZone_send = 0; level->timers.ghostZone_wait = 0; level->timers.collectives = 0; level->timers.Total = 0; // solver events information... level->Krylov_iterations = 0; level->CAKrylov_formations_of_G = 0; level->vcycles_from_this_level = 0; } //--------------------------------------------------------------------------------------------------------------------------------------------------- // free all memory allocated by this level // n.b. in some cases a malloc was used as the basis for an array of pointers. As such free(x[0]) void destroy_level(level_type *level){ int i,j; if(level->my_rank==0){fprintf(stdout,"attempting to free the %5d^3 level... ",level->dim.i);fflush(stdout);} // box ... for(i=0;i<level->num_my_boxes;i++)if(level->my_boxes[i].vectors)free(level->my_boxes[i].vectors); // misc ... if(level->rank_of_box )free(level->rank_of_box); if(level->my_boxes )free(level->my_boxes); if(level->my_blocks )free(level->my_blocks); if(level->RedBlack_base)free(level->RedBlack_base); // FP vector data... #ifdef VECTOR_MALLOC_BULK if(level->vectors_base)free(level->vectors_base); if(level->vectors )free(level->vectors); #else for(i=0;i<level->numVectors;i++)if(level->vectors[i])free(level->vectors[i]); if(level->vectors )free(level->vectors); #endif // boundary condition mini program... for(i=0;i<STENCIL_MAX_SHAPES;i++){ if(level->boundary_condition.blocks[i])free(level->boundary_condition.blocks[i]); } // ghost zone exchange mini programs... for(i=0;i<STENCIL_MAX_SHAPES;i++){ if(level->exchange_ghosts[i].num_recvs>0){ for(j=0;j<level->exchange_ghosts[i].num_recvs;j++)if(level->exchange_ghosts[i].recv_buffers[j])free(level->exchange_ghosts[i].recv_buffers[j]); if(level->exchange_ghosts[i].recv_buffers)free(level->exchange_ghosts[i].recv_buffers); if(level->exchange_ghosts[i].recv_ranks )free(level->exchange_ghosts[i].recv_ranks ); if(level->exchange_ghosts[i].recv_sizes )free(level->exchange_ghosts[i].recv_sizes ); } if(level->exchange_ghosts[i].num_sends>0){ for(j=0;j<level->exchange_ghosts[i].num_sends;j++)if(level->exchange_ghosts[i].send_buffers[j])free(level->exchange_ghosts[i].send_buffers[j]); if(level->exchange_ghosts[i].send_buffers)free(level->exchange_ghosts[i].send_buffers); if(level->exchange_ghosts[i].send_ranks )free(level->exchange_ghosts[i].send_ranks ); if(level->exchange_ghosts[i].send_sizes )free(level->exchange_ghosts[i].send_sizes ); } if(level->exchange_ghosts[i].blocks[0] )free(level->exchange_ghosts[i].blocks[0] ); if(level->exchange_ghosts[i].blocks[1] )free(level->exchange_ghosts[i].blocks[1] ); if(level->exchange_ghosts[i].blocks[2] )free(level->exchange_ghosts[i].blocks[2] ); #ifdef USE_MPI if(level->exchange_ghosts[i].requests )free(level->exchange_ghosts[i].requests ); if(level->exchange_ghosts[i].status )free(level->exchange_ghosts[i].status ); #endif } if(level->my_rank==0){fprintf(stdout,"done\n");} } //#if CD //size_t cd_preserve_box_type(cd_handle_t* cd_h, const box_type& box, const char* name){ // size_t size=0; // char prv_name[100]; // sprintf(prv_name, "box_%s", name); // size_t tmp_size = sizeof(box_type); // cd_preserve(cd_h, (void*)&box, tmp_size, kCopy, prv_name, prv_name); // size += tmp_size; // // // preserve vectors // sprintf(prv_name, "box_vectors_%s", name); // size += cd_preserve_global_ptr(cd_h, box.vectors, prv_name); // for (int ii=0; ii<box.numVectors; ii++){ // sprintf(prv_name, "box_vectors_%d_%s", ii, name); // size += cd_preserve_global_ptr(cd_h, box.vectors[ii].get(), prv_name); // } // // // preserve vectors_base // sprintf(prv_name, "box_vectors_base_%s", name); // size += cd_preserve_global_ptr(cd_h, box.vectors_base, prv_name); // uint64_t malloc_size = box.volume*box.numVectors + BOX_ALIGN_1ST_CELL/sizeof(double); // cd_preserve(cd_h, box.vectors_base.raw_ptr(), malloc_size, kCopy, prv_name, prv_name); // size += malloc_size; // return size; //} // //size_t cd_preserve_communication_type_extra(cd_handle_t *cd_h, const communicator_type& comm, const char* name){ // size_t ret_size=0; // char prv_name[100]; // size_t size=0; // // sprintf(prv_name, "commtype_recvrank_%s", name); // size=comm.num_recvs*sizeof(int); // cd_preserve(cd_h, comm.recv_ranks, size, kCopy, prv_name, prv_name); // ret_size += size; // sprintf(prv_name, "commtype_sendrank_%s", name); // size=comm.num_sends*sizeof(int); // cd_preserve(cd_h, comm.send_ranks, size, kCopy, prv_name, prv_name); // ret_size += size; // sprintf(prv_name, "commtype_recvsize_%s", name); // size=comm.num_recvs*sizeof(int); // cd_preserve(cd_h, comm.recv_sizes, size, kCopy, prv_name, prv_name); // ret_size += size; // sprintf(prv_name, "commtype_sendsize_%s", name); // size=comm.num_sends*sizeof(int); // cd_preserve(cd_h, comm.send_sizes, size, kCopy, prv_name, prv_name); // ret_size += size; // // sprintf(prv_name, "commtype_rflag_%s", name); // ret_size += cd_preserve_global_ptr(cd_h, comm.rflag, name); // // sprintf(prv_name, "commtype_matchflag_%s", name); // size = comm.num_sends*sizeof(global_ptr<int>); // cd_preserve(cd_h, comm.match_rflag, size, kCopy, prv_name, prv_name); // ret_size += size; // //for (int ii=0; ii<comm.num_sends; ii++){ // // sprintf(prv_name, "commtype_matchflag_%d_%s", ii, name); // // ret_size += cd_preserve_global_ptr(cd_h, comm.match_rflag[ii], name); // //} // // sprintf(prv_name, "commtype_sblock2_%s", name); // //size = (comm.num_recvs+2) * sizeof(int); // size = comm.num_recvs * sizeof(int); // cd_preserve(cd_h, comm.sblock2, size, kCopy, prv_name, prv_name); // ret_size += size; // // // FIXME: comm.eblock2 is never used??? // //sprintf(prv_name, "commtype_eblock2_%s", name); // // sprintf(prv_name, "commtype_sendmatchpos_%s", name); // size = (comm.num_sends) * sizeof(int); // cd_preserve(cd_h, comm.send_match_pos, size, kCopy, prv_name, prv_name); // ret_size += size; // // // only need to preserve pointer information.. // sprintf(prv_name, "commtype_grecvbuffer_%s", name); // size = comm.num_recvs*sizeof(global_ptr<double>); // cd_preserve(cd_h, comm.global_recv_buffers, size, kCopy, prv_name, prv_name); // ret_size += size; // sprintf(prv_name, "commtype_gsendbuffer_%s", name); // size = comm.num_sends*sizeof(global_ptr<double>); // cd_preserve(cd_h, comm.global_send_buffers, size, kCopy, prv_name, prv_name); // ret_size += size; // sprintf(prv_name, "commtype_gmatchbuffer_%s", name); // size = comm.num_sends*sizeof(global_ptr<double>); // cd_preserve(cd_h, comm.global_match_buffers, size, kCopy, prv_name, prv_name); // ret_size += size; // // // FIXME: how to preserve copy_e and data_e // // sprintf(prv_name, "commtype_recvbuffer_%s", name); // size=comm.num_recvs*sizeof(double*); // cd_preserve(cd_h, comm.recv_buffers, size, kCopy, prv_name, prv_name); // ret_size += size; // sprintf(prv_name, "commtype_sendbuffer_%s", name); // size=comm.num_sends*sizeof(double*); // cd_preserve(cd_h, comm.send_buffers, size, kCopy, prv_name, prv_name); // ret_size += size; // // for (int ii=0; ii<4; ii++){ // if (comm.blocks[ii]==NULL) continue; // sprintf(prv_name, "commtype_blocks_%d_%s", ii, name); // size = comm.num_blocks[ii]*sizeof(blockCopy_type); // cd_preserve(cd_h, comm.blocks[ii], size, kCopy, prv_name, prv_name); // ret_size += size; // } // return ret_size; //} // //size_t cd_preserve_level(cd_handle_t* cd_h, level_type *level, const char* name){ // size_t prv_size=0; // char prv_name[100]; // sprintf(prv_name, "level_%s", name); // size_t tmp_size = sizeof(level_type); // cd_preserve(cd_h, level, tmp_size, kCopy, prv_name, prv_name); // prv_size += tmp_size; // // // preserve subteam information // // FIXME: pointers inside subteam (e.g. ptrs to parent and child teams) may be wrong in recovery, // // because only the pointer data are preserved. // // So if we have node recovery in higher level, the pointers need to be fixed! // sprintf(prv_name, "level_subteam_%s", name); // tmp_size = sizeof(team); // cd_preserve(cd_h, level->subteam, tmp_size, kCopy, prv_name, prv_name); // prv_size += tmp_size; // // // preserve rank_of_box // sprintf(prv_name, "level_rankofbox_%s", name); // size_t size = level->boxes_in.i*level->boxes_in.j*level->boxes_in.k*sizeof(int); // cd_preserve(cd_h, level->rank_of_box, size, kCopy, prv_name, prv_name); // prv_size += size; // // // preserve my_boxes; place and T* should be preserved; need to preserve the allocated data // sprintf(prv_name, "level_myboxes_%s", name); // prv_size += cd_preserve_global_ptr(cd_h, level->my_boxes, prv_name); // // preserve all pointers inside box_type // for (int ii=0; ii<level->num_my_boxes; ii++){ // prv_size += cd_preserve_box_type(cd_h, level->my_boxes[ii].get(), prv_name); // } // // // preserve addr_of_box // sprintf(prv_name, "level_aob_%s", name); // size = level->boxes_in.i*level->boxes_in.j*level->boxes_in.k; // tmp_size = size*sizeof(global_ptr<box_type>); // cd_preserve(cd_h, level->addr_of_box, tmp_size, kCopy, prv_name, prv_name); // prv_size += tmp_size; // for (size_t ii=0; ii<size; ii++){ // prv_size += cd_preserve_global_ptr(cd_h, level->addr_of_box[ii], prv_name); // } // // // preserve my_local_boxes // sprintf(prv_name, "level_mlb_%s", name); // size = level->num_my_boxes * sizeof(box_type *); // cd_preserve(cd_h, level->my_local_boxes, size, kCopy, prv_name, prv_name); // prv_size += size; // // // preserve my_blocks // // SZNOTE: no need to do extra things for blockCopy_type, // // because pointers are saved with blockCopy_type, while the contents have been preserved in preservations // sprintf(prv_name, "level_myblocks_%s", name); // size = level->num_my_boxes * sizeof(blockCopy_type); // cd_preserve(cd_h, level->my_blocks, size, kCopy, prv_name, prv_name); // // // preserve RedBlack_FP // sprintf(prv_name, "level_rbfp_%s", name); // size = sizeof(double*)*2; // cd_preserve(cd_h, level->RedBlack_FP, size, kCopy, prv_name, prv_name); // prv_size += size; // if (level->my_boxes!=NULL){ // size = level->my_boxes[0].get().kStride*sizeof(double); // for (int ii=0; ii<2; ii++){ // sprintf(prv_name, "level_rbfp_%d_%s", ii, name); // cd_preserve(cd_h, level->RedBlack_FP[ii], size, kCopy, prv_name, prv_name); // prv_size += size; // } // } // // //std::cout << "before preserving exchange_ghosts\n"; // // preserve exchange_ghosts // sprintf(prv_name, "level_eg_%s", name); // size = 2*sizeof(communicator_type); // cd_preserve(cd_h, level->exchange_ghosts, size, kCopy, prv_name, prv_name); // prv_size += size; // for (int ii=0; ii<2; ii++){ // sprintf(prv_name, "level_eg_%d_%s", ii, name); // prv_size += cd_preserve_communication_type_extra(cd_h, level->exchange_ghosts[ii], prv_name); // } // // //std::cout << "before preserving restriction\n"; // // preserve restriction // sprintf(prv_name, "level_restriction_%s", name); // size = 4*sizeof(communicator_type); // cd_preserve(cd_h, level->restriction, size, kCopy, prv_name, prv_name); // prv_size += size; // for (int ii=0; ii<4; ii++){ // sprintf(prv_name, "level_restriction_%d_%s", ii, name); // prv_size += cd_preserve_communication_type_extra(cd_h, level->restriction[ii], prv_name); // } // // //std::cout << "before preserving interpolation\n"; // // preserve interpolation // sprintf(prv_name, "level_interpolation_%s", name); // size = sizeof(communicator_type); // cd_preserve(cd_h, &(level->interpolation), size, kCopy, prv_name, prv_name); // sprintf(prv_name, "level_interpolation_extra_%s", name); // prv_size += cd_preserve_communication_type_extra(cd_h, level->interpolation, prv_name); // // //std::cout << "before preserving boundary_condition\n"; // // preserve boundary_condition.blocks // for (int ii=0; ii<2; ii++){ // if (level->boundary_condition.blocks[ii]==NULL) continue; // sprintf(prv_name, "level_bc_blocks_%d_%s", ii, name); // size = level->boundary_condition.num_blocks[ii]*sizeof(blockCopy_type); // cd_preserve(cd_h, level->boundary_condition.blocks[ii], size, kCopy, prv_name, prv_name); // prv_size += size; // } // // return prv_size; //} // //size_t cd_preserve_levels(cd_handle_t* cd_h, level_type **levels, int num_levels, const char* name){ // size_t prv_size=0; // char prv_name[100]; // // preserve pointers to all levels; guarded by num_levels // sprintf(prv_name, "level_type_ptr_%s", name); // size_t tmp_size = sizeof(level_type*)*num_levels; // cd_preserve(cd_h, levels, tmp_size, kCopy, prv_name, prv_name); // prv_size += tmp_size; // // // preserve each level // for (int ii=0; ii<num_levels; ii++){ // //std::cout << "before preserving level::" << ii << "\n"; // prv_size += cd_preserve_level(cd_h, levels[ii], name); // } // return prv_size; //} // //#endif
threading.h
/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for * license information. */ #ifndef LIGHTGBM_UTILS_THREADING_H_ #define LIGHTGBM_UTILS_THREADING_H_ #include <LightGBM/meta.h> #include <LightGBM/utils/common.h> #include <LightGBM/utils/openmp_wrapper.h> #include <algorithm> #include <functional> #include <vector> namespace LightGBM { class Threading { public: template <typename INDEX_T> static inline void BlockInfo(INDEX_T cnt, INDEX_T min_cnt_per_block, int* out_nblock, INDEX_T* block_size) { int num_threads = OMP_NUM_THREADS(); BlockInfo<INDEX_T>(num_threads, cnt, min_cnt_per_block, out_nblock, block_size); } template <typename INDEX_T> static inline void BlockInfo(int num_threads, INDEX_T cnt, INDEX_T min_cnt_per_block, int* out_nblock, INDEX_T* block_size) { *out_nblock = std::min<int>( num_threads, static_cast<int>((cnt + min_cnt_per_block - 1) / min_cnt_per_block)); if (*out_nblock > 1) { *block_size = SIZE_ALIGNED((cnt + (*out_nblock) - 1) / (*out_nblock)); } else { *block_size = cnt; } } template <typename INDEX_T> static inline void BlockInfoForceSize(int num_threads, INDEX_T cnt, INDEX_T min_cnt_per_block, int* out_nblock, INDEX_T* block_size) { *out_nblock = std::min<int>( num_threads, static_cast<int>((cnt + min_cnt_per_block - 1) / min_cnt_per_block)); if (*out_nblock > 1) { *block_size = (cnt + (*out_nblock) - 1) / (*out_nblock); // force the block size to the times of min_cnt_per_block *block_size = (*block_size + min_cnt_per_block - 1) / min_cnt_per_block * min_cnt_per_block; } else { *block_size = cnt; } } template <typename INDEX_T> static inline int For( INDEX_T start, INDEX_T end, INDEX_T min_block_size, const std::function<void(int, INDEX_T, INDEX_T)>& inner_fun) { int n_block = 1; INDEX_T num_inner = end - start; BlockInfo<INDEX_T>(end - start, min_block_size, &n_block, &num_inner); OMP_INIT_EX(); #pragma omp parallel for schedule(static, 1) for (int i = 0; i < n_block; ++i) { OMP_LOOP_EX_BEGIN(); INDEX_T inner_start = start + num_inner * i; INDEX_T inner_end = std::min(end, inner_start + num_inner); inner_fun(i, inner_start, inner_end); OMP_LOOP_EX_END(); } OMP_THROW_EX(); return n_block; } }; template <typename INDEX_T, bool TWO_BUFFER> class ParallelPartitionRunner { public: ParallelPartitionRunner(INDEX_T num_data, INDEX_T min_block_size) : min_block_size_(min_block_size) { num_threads_ = OMP_NUM_THREADS(); left_.resize(num_data); if (TWO_BUFFER) { right_.resize(num_data); } offsets_.resize(num_threads_); left_cnts_.resize(num_threads_); right_cnts_.resize(num_threads_); left_write_pos_.resize(num_threads_); right_write_pos_.resize(num_threads_); } ~ParallelPartitionRunner() {} void ReSize(INDEX_T num_data) { left_.resize(num_data); if (TWO_BUFFER) { right_.resize(num_data); } } template<bool FORCE_SIZE> INDEX_T Run( INDEX_T cnt, const std::function<INDEX_T(int, INDEX_T, INDEX_T, INDEX_T*, INDEX_T*)>& func, INDEX_T* out) { int nblock = 1; INDEX_T inner_size = cnt; if (FORCE_SIZE) { Threading::BlockInfoForceSize<INDEX_T>(num_threads_, cnt, min_block_size_, &nblock, &inner_size); } else { Threading::BlockInfo<INDEX_T>(num_threads_, cnt, min_block_size_, &nblock, &inner_size); } OMP_INIT_EX(); #pragma omp parallel for schedule(static, 1) num_threads(num_threads_) for (int i = 0; i < nblock; ++i) { OMP_LOOP_EX_BEGIN(); INDEX_T cur_start = i * inner_size; INDEX_T cur_cnt = std::min(inner_size, cnt - cur_start); offsets_[i] = cur_start; if (cur_cnt <= 0) { left_cnts_[i] = 0; right_cnts_[i] = 0; continue; } auto left_ptr = left_.data() + cur_start; INDEX_T* right_ptr = nullptr; if (TWO_BUFFER) { right_ptr = right_.data() + cur_start; } // split data inner, reduce the times of function called INDEX_T cur_left_count = func(i, cur_start, cur_cnt, left_ptr, right_ptr); if (!TWO_BUFFER) { // reverse for one buffer std::reverse(left_ptr + cur_left_count, left_ptr + cur_cnt); } left_cnts_[i] = cur_left_count; right_cnts_[i] = cur_cnt - cur_left_count; OMP_LOOP_EX_END(); } OMP_THROW_EX(); left_write_pos_[0] = 0; right_write_pos_[0] = 0; for (int i = 1; i < nblock; ++i) { left_write_pos_[i] = left_write_pos_[i - 1] + left_cnts_[i - 1]; right_write_pos_[i] = right_write_pos_[i - 1] + right_cnts_[i - 1]; } data_size_t left_cnt = left_write_pos_[nblock - 1] + left_cnts_[nblock - 1]; auto right_start = out + left_cnt; #pragma omp parallel for schedule(static, 1) num_threads(num_threads_) for (int i = 0; i < nblock; ++i) { std::copy_n(left_.data() + offsets_[i], left_cnts_[i], out + left_write_pos_[i]); if (TWO_BUFFER) { std::copy_n(right_.data() + offsets_[i], right_cnts_[i], right_start + right_write_pos_[i]); } else { std::copy_n(left_.data() + offsets_[i] + left_cnts_[i], right_cnts_[i], right_start + right_write_pos_[i]); } } return left_cnt; } private: int num_threads_; INDEX_T min_block_size_; std::vector<INDEX_T> left_; std::vector<INDEX_T> right_; std::vector<INDEX_T> offsets_; std::vector<INDEX_T> left_cnts_; std::vector<INDEX_T> right_cnts_; std::vector<INDEX_T> left_write_pos_; std::vector<INDEX_T> right_write_pos_; }; } // namespace LightGBM #endif // LightGBM_UTILS_THREADING_H_
GB_select_phase1.c
//------------------------------------------------------------------------------ // GB_select_phase1: count entries in each vector for C=select(A,thunk) //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ //-------------------------------------------------------------------------- // get A and its slicing //-------------------------------------------------------------------------- const int64_t *restrict kfirst_Aslice = A_ek_slicing ; const int64_t *restrict klast_Aslice = A_ek_slicing + A_ntasks ; const int64_t *restrict pstart_Aslice = A_ek_slicing + A_ntasks * 2 ; const int64_t *restrict Ap = A->p ; const int64_t *restrict Ah = A->h ; const int64_t *restrict Ai = A->i ; int64_t avlen = A->vlen ; int64_t anvec = A->nvec ; #if defined ( GB_ENTRY_SELECTOR ) //========================================================================== // entry selector //========================================================================== ASSERT (GB_JUMBLED_OK (A)) ; // The count of live entries kth vector A(:,k) is reduced to the kth scalar // Cp(k). Each thread computes the reductions on roughly the same number // of entries, which means that a vector A(:,k) may be reduced by more than // one thread. The first vector A(:,kfirst) reduced by thread tid may be // partial, where the prior thread tid-1 (and other prior threads) may also // do some of the reductions for this same vector A(:,kfirst). The thread // tid reduces all vectors A(:,k) for k in the range kfirst+1 to klast-1. // The last vector A(:,klast) reduced by thread tid may also be partial. // Thread tid+1, and following threads, may also do some of the reduces for // A(:,klast). //-------------------------------------------------------------------------- // get A //-------------------------------------------------------------------------- const GB_ATYPE *restrict Ax = (GB_ATYPE *) A->x ; size_t asize = A->type->size ; int64_t avdim = A->vdim ; ASSERT (GB_JUMBLED_OK (A)) ; //-------------------------------------------------------------------------- // reduce each slice //-------------------------------------------------------------------------- // each thread reduces its own part in parallel int tid ; #pragma omp parallel for num_threads(A_nthreads) schedule(dynamic,1) for (tid = 0 ; tid < A_ntasks ; tid++) { // if kfirst > klast then thread tid does no work at all int64_t kfirst = kfirst_Aslice [tid] ; int64_t klast = klast_Aslice [tid] ; Wfirst [tid] = 0 ; Wlast [tid] = 0 ; //---------------------------------------------------------------------- // reduce vectors kfirst to klast //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // find the part of A(:,k) to be reduced by this thread //------------------------------------------------------------------ int64_t j = GBH (Ah, k) ; int64_t pA, pA_end ; GB_get_pA (&pA, &pA_end, tid, k, kfirst, klast, pstart_Aslice, Ap, avlen) ; //------------------------------------------------------------------ // count entries in Ax [pA ... pA_end-1] //------------------------------------------------------------------ int64_t cjnz = 0 ; for ( ; pA < pA_end ; pA++) { ASSERT (Ai != NULL) ; int64_t i = Ai [pA] ; GB_TEST_VALUE_OF_ENTRY (keep, pA) ; if (keep) cjnz++ ; } if (k == kfirst) { Wfirst [tid] = cjnz ; } else if (k == klast) { Wlast [tid] = cjnz ; } else { Cp [k] = cjnz ; } } } //-------------------------------------------------------------------------- // reduce the first and last vector of each slice using a single thread //-------------------------------------------------------------------------- GB_ek_slice_merge1 (Cp, Wfirst, Wlast, A_ek_slicing, A_ntasks) ; #else //========================================================================== // positional selector (tril, triu, diag, offdiag, resize, row*) //========================================================================== ASSERT (!GB_JUMBLED (A)) ; //-------------------------------------------------------------------------- // tril, triu, diag, offdiag, resize: binary search in each vector //-------------------------------------------------------------------------- int64_t k ; #pragma omp parallel for num_threads(A_nthreads) schedule(guided) for (k = 0 ; k < anvec ; k++) { //---------------------------------------------------------------------- // get A(:,k) //---------------------------------------------------------------------- int64_t pA_start = GBP (Ap, k, avlen) ; int64_t pA_end = GBP (Ap, k+1, avlen) ; int64_t p = pA_start ; int64_t cjnz = 0 ; int64_t ajnz = pA_end - pA_start ; bool found = false ; if (ajnz > 0) { //------------------------------------------------------------------ // search for the entry A(i,k) //------------------------------------------------------------------ int64_t ifirst = GBI (Ai, pA_start, avlen) ; int64_t ilast = GBI (Ai, pA_end-1, avlen) ; #if defined ( GB_ROWINDEX_SELECTOR ) int64_t i = -ithunk ; #elif defined ( GB_ROWLE_SELECTOR ) || defined ( GB_ROWGT_SELECTOR ) int64_t i = ithunk ; #else // TRIL, TRIU, DIAG, OFFDIAG int64_t j = GBH (Ah, k) ; int64_t i = j-ithunk ; #endif if (i < ifirst) { // all entries in A(:,k) come after i ; } else if (i > ilast) { // all entries in A(:,k) come before i p = pA_end ; } else if (ajnz == avlen) { // A(:,k) is dense found = true ; p += i ; ASSERT (GBI (Ai, p, avlen) == i) ; } else { // binary search for A (i,k) int64_t pright = pA_end - 1 ; GB_SPLIT_BINARY_SEARCH (i, Ai, p, pright, found) ; } #if defined ( GB_TRIL_SELECTOR ) // keep p to pA_end-1 cjnz = pA_end - p ; #elif defined ( GB_ROWGT_SELECTOR ) // if found, keep p+1 to pA_end-1 // else keep p to pA_end-1 if (found) { p++ ; // now in both cases, keep p to pA_end-1 } // keep p to pA_end-1 cjnz = pA_end - p ; #elif defined ( GB_TRIU_SELECTOR ) \ || defined ( GB_ROWLE_SELECTOR ) // if found, keep pA_start to p // else keep pA_start to p-1 if (found) { p++ ; // now in both cases, keep pA_start to p-1 } // keep pA_start to p-1 cjnz = p - pA_start ; #elif defined ( GB_DIAG_SELECTOR ) // if found, keep p // else keep nothing cjnz = found ; if (!found) p = -1 ; // if (cjnz >= 0) keep p, else keep nothing #elif defined ( GB_OFFDIAG_SELECTOR ) || \ defined ( GB_ROWINDEX_SELECTOR ) // if found, keep pA_start to p-1 and p+1 to pA_end-1 // else keep pA_start to pA_end cjnz = ajnz - found ; if (!found) { p = pA_end ; // now just keep pA_start to p-1; p+1 to pA_end is // now empty } // in both cases, keep pA_start to p-1 and // p+1 to pA_end-1. If the entry is not found, then // p == pA_end, and all entries are kept. #endif } //---------------------------------------------------------------------- // log the result for the kth vector //---------------------------------------------------------------------- Zp [k] = p ; Cp [k] = cjnz ; } //-------------------------------------------------------------------------- // compute Wfirst and Wlast for each task //-------------------------------------------------------------------------- // Wfirst [0..A_ntasks-1] and Wlast [0..A_ntasks-1] are required for // constructing C_start_slice [0..A_ntasks-1] in GB_selector. for (int tid = 0 ; tid < A_ntasks ; tid++) { // if kfirst > klast then task tid does no work at all int64_t kfirst = kfirst_Aslice [tid] ; int64_t klast = klast_Aslice [tid] ; Wfirst [tid] = 0 ; Wlast [tid] = 0 ; if (kfirst <= klast) { int64_t pA_start = pstart_Aslice [tid] ; int64_t pA_end = GBP (Ap, kfirst+1, avlen) ; pA_end = GB_IMIN (pA_end, pstart_Aslice [tid+1]) ; if (pA_start < pA_end) { #if defined ( GB_TRIL_SELECTOR ) || \ defined ( GB_ROWGT_SELECTOR ) // keep Zp [kfirst] to pA_end-1 int64_t p = GB_IMAX (Zp [kfirst], pA_start) ; Wfirst [tid] = GB_IMAX (0, pA_end - p) ; #elif defined ( GB_TRIU_SELECTOR ) || \ defined ( GB_ROWLE_SELECTOR ) // keep pA_start to Zp [kfirst]-1 int64_t p = GB_IMIN (Zp [kfirst], pA_end) ; Wfirst [tid] = GB_IMAX (0, p - pA_start) ; #elif defined ( GB_DIAG_SELECTOR ) // task that owns the diagonal entry does this work int64_t p = Zp [kfirst] ; Wfirst [tid] = (pA_start <= p && p < pA_end) ? 1 : 0 ; #elif defined ( GB_OFFDIAG_SELECTOR ) || \ defined ( GB_ROWINDEX_SELECTOR ) // keep pA_start to Zp [kfirst]-1 int64_t p = GB_IMIN (Zp [kfirst], pA_end) ; Wfirst [tid] = GB_IMAX (0, p - pA_start) ; // keep Zp [kfirst]+1 to pA_end-1 p = GB_IMAX (Zp [kfirst]+1, pA_start) ; Wfirst [tid] += GB_IMAX (0, pA_end - p) ; #endif } } if (kfirst < klast) { int64_t pA_start = GBP (Ap, klast, avlen) ; int64_t pA_end = pstart_Aslice [tid+1] ; if (pA_start < pA_end) { #if defined ( GB_TRIL_SELECTOR ) || \ defined ( GB_ROWGT_SELECTOR ) // keep Zp [klast] to pA_end-1 int64_t p = GB_IMAX (Zp [klast], pA_start) ; Wlast [tid] = GB_IMAX (0, pA_end - p) ; #elif defined ( GB_TRIU_SELECTOR ) || \ defined ( GB_ROWLE_SELECTOR ) // keep pA_start to Zp [klast]-1 int64_t p = GB_IMIN (Zp [klast], pA_end) ; Wlast [tid] = GB_IMAX (0, p - pA_start) ; #elif defined ( GB_DIAG_SELECTOR ) // task that owns the diagonal entry does this work int64_t p = Zp [klast] ; Wlast [tid] = (pA_start <= p && p < pA_end) ? 1 : 0 ; #elif defined ( GB_OFFDIAG_SELECTOR ) || \ defined ( GB_ROWINDEX_SELECTOR ) // keep pA_start to Zp [klast]-1 int64_t p = GB_IMIN (Zp [klast], pA_end) ; Wlast [tid] = GB_IMAX (0, p - pA_start) ; // keep Zp [klast]+1 to pA_end-1 p = GB_IMAX (Zp [klast]+1, pA_start) ; Wlast [tid] += GB_IMAX (0, pA_end - p) ; #endif } } } #endif
imm.h
//===------------------------------------------------------------*- C++ -*-===// // // Ripples: A C++ Library for Influence Maximization // Marco Minutoli <marco.minutoli@pnnl.gov> // Pacific Northwest National Laboratory // //===----------------------------------------------------------------------===// // // Copyright (c) 2019, Battelle Memorial Institute // // Battelle Memorial Institute (hereinafter Battelle) hereby grants permission // to any person or entity lawfully obtaining a copy of this software and // associated documentation files (hereinafter “the Software”) to redistribute // and use the Software in source and binary forms, with or without // modification. Such person or entity may use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and may permit // others to do so, subject to the following conditions: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimers. // // 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. // // 3. Other than as used herein, neither the name Battelle Memorial Institute or // Battelle may be used in any form whatsoever without the express written // consent of Battelle. // // 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 BATTELLE 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 RIPPLES_IMM_H #define RIPPLES_IMM_H #include <cmath> #include <cstddef> #include <limits> #include <unordered_map> #include <vector> #include "nlohmann/json.hpp" #include "trng/lcg64.hpp" #include "trng/uniform01_dist.hpp" #include "trng/uniform_int_dist.hpp" #include "ripples/configuration.h" #include "ripples/find_most_influential.h" #include "ripples/generate_rrr_sets.h" #include "ripples/imm_execution_record.h" #include "ripples/tim.h" #include "ripples/utility.h" #include "ripples/streaming_rrr_generator.h" #define CUDA_PROFILE 0 namespace ripples { //! The IMM algorithm configuration descriptor. struct IMMConfiguration : public TIMConfiguration { size_t streaming_workers{0}; size_t streaming_gpu_workers{0}; size_t seed_select_max_workers{std::numeric_limits<size_t>::max()}; size_t seed_select_max_gpu_workers{0}; std::string gpu_mapping_string{""}; std::unordered_map<size_t, size_t> worker_to_gpu; //! \brief Add command line options to configure IMM. //! //! \param app The command-line parser object. void addCmdOptions(CLI::App &app) { TIMConfiguration::addCmdOptions(app); app.add_option( "--streaming-gpu-workers", streaming_gpu_workers, "The number of GPU workers for the CPU+GPU streaming engine.") ->group("Streaming-Engine Options"); app.add_option("--streaming-gpu-mapping", gpu_mapping_string, "A comma-separated set of OpenMP numbers for GPU workers.") ->group("Streaming-Engine Options"); app.add_option("--seed-select-max-workers", seed_select_max_workers, "The max number of workers for seed selection.") ->group("Streaming-Engine Options"); app.add_option("--seed-select-max-gpu-workers", seed_select_max_gpu_workers, "The max number of GPU workers for seed selection.") ->group("Streaming-Engine Options"); } }; //! Retrieve the configuration parsed from command line. //! \return the configuration parsed from command line. ToolConfiguration<ripples::IMMConfiguration> configuration(); //! Approximate logarithm of n chose k. //! \param n //! \param k //! \return an approximation of log(n choose k). inline double logBinomial(size_t n, size_t k) { return n * log(n) - k * log(k) - (n - k) * log(n - k); } //! Compute ThetaPrime. //! //! \tparam execution_tag The execution policy //! //! \param x The index of the current iteration. //! \param epsilonPrime Parameter controlling the approximation factor. //! \param l Parameter usually set to 1. //! \param k The size of the seed set. //! \param num_nodes The number of nodes in the input graph. template <typename execution_tag> ssize_t ThetaPrime(ssize_t x, double epsilonPrime, double l, size_t k, size_t num_nodes, execution_tag &&) { k = std::min(k, num_nodes/2); return (2 + 2. / 3. * epsilonPrime) * (l * std::log(num_nodes) + logBinomial(num_nodes, k) + std::log(std::log2(num_nodes))) * std::pow(2.0, x) / (epsilonPrime * epsilonPrime); } //! Compute Theta. //! //! \param epsilon Parameter controlling the approximation factor. //! \param l Parameter usually set to 1. //! \param k The size of the seed set. //! \param LB The estimate of the lower bound. //! \param num_nodes The number of nodes in the input graph. inline size_t Theta(double epsilon, double l, size_t k, double LB, size_t num_nodes) { if (LB == 0) return 0; k = std::min(k, num_nodes/2); double term1 = 0.6321205588285577; // 1 - 1/e double alpha = sqrt(l * std::log(num_nodes) + std::log(2)); double beta = sqrt(term1 * (logBinomial(num_nodes, k) + l * std::log(num_nodes) + std::log(2))); double lamdaStar = 2 * num_nodes * (term1 * alpha + beta) * (term1 * alpha + beta) * pow(epsilon, -2); // std::cout << "#### " << lamdaStar << " / " << LB << " = " << lamdaStar / LB << std::endl; return lamdaStar / LB; } //! Collect a set of Random Reverse Reachable set. //! //! \tparam GraphTy The type of the input graph. //! \tparam RRRGeneratorTy The type of the RRR generator. //! \tparam diff_model_tag Type-Tag to selecte the diffusion model. //! \tparam execution_tag Type-Tag to select the execution policy. //! //! \param G The input graph. The graph is transoposed. //! \param k The size of the seed set. //! \param epsilon The parameter controlling the approximation guarantee. //! \param l Parameter usually set to 1. //! \param generator The rrr sets generator. //! \param record Data structure storing timing and event counts. //! \param model_tag The diffusion model tag. //! \param ex_tag The execution policy tag. template <typename GraphTy, typename ConfTy, typename RRRGeneratorTy, typename diff_model_tag, typename execution_tag> auto Sampling(const GraphTy &G, const ConfTy &CFG, double l, RRRGeneratorTy &generator, IMMExecutionRecord &record, diff_model_tag &&model_tag, execution_tag &&ex_tag) { using vertex_type = typename GraphTy::vertex_type; size_t k = CFG.k; double epsilon = CFG.epsilon; // sqrt(2) * epsilon double epsilonPrime = 1.4142135623730951 * epsilon; double LB = 0; #ifdef ENABLE_MEMKIND RRRsetAllocator<vertex_type> allocator(libmemkind::kinds::DAX_KMEM_PREFERRED); #else RRRsetAllocator<vertex_type> allocator; #endif std::vector<RRRset<GraphTy>> RR; auto start = std::chrono::high_resolution_clock::now(); size_t thetaPrime = 0; for (ssize_t x = 1; x < std::log2(G.num_nodes()); ++x) { // Equation 9 ssize_t thetaPrime = ThetaPrime(x, epsilonPrime, l, k, G.num_nodes(), std::forward<execution_tag>(ex_tag)); size_t delta = thetaPrime - RR.size(); record.ThetaPrimeDeltas.push_back(delta); auto timeRRRSets = measure<>::exec_time([&]() { RR.insert(RR.end(), delta, RRRset<GraphTy>(allocator)); auto begin = RR.end() - delta; GenerateRRRSets(G, generator, begin, RR.end(), record, std::forward<diff_model_tag>(model_tag), std::forward<execution_tag>(ex_tag)); }); record.ThetaEstimationGenerateRRR.push_back(timeRRRSets); double f; auto timeMostInfluential = measure<>::exec_time([&]() { const auto &S = FindMostInfluentialSet(G, CFG, RR, record, generator.isGpuEnabled(), std::forward<execution_tag>(ex_tag)); f = S.first; }); record.ThetaEstimationMostInfluential.push_back(timeMostInfluential); if (f >= std::pow(2, -x)) { // std::cout << "Fraction " << f << std::endl; LB = (G.num_nodes() * f) / (1 + epsilonPrime); break; } } size_t theta = Theta(epsilon, l, k, LB, G.num_nodes()); auto end = std::chrono::high_resolution_clock::now(); record.ThetaEstimationTotal = end - start; record.Theta = theta; std::cout << G.num_nodes() << "," << theta << std::endl; record.GenerateRRRSets = measure<>::exec_time([&]() { if (theta > RR.size()) { size_t final_delta = theta - RR.size(); RR.insert(RR.end(), final_delta, RRRset<GraphTy>(allocator)); auto begin = RR.end() - final_delta; GenerateRRRSets(G, generator, begin, RR.end(), record, std::forward<diff_model_tag>(model_tag), std::forward<execution_tag>(ex_tag)); } }); return RR; } template <typename GraphTy, typename ConfTy, typename RRRGeneratorTy, typename diff_model_tag> auto Sampling(const GraphTy &G, const ConfTy &CFG, double l, RRRGeneratorTy &generator, IMMExecutionRecord &record, diff_model_tag &&model_tag, sequential_tag &&ex_tag) { using vertex_type = typename GraphTy::vertex_type; size_t k = CFG.k; double epsilon = CFG.epsilon; // sqrt(2) * epsilon double epsilonPrime = 1.4142135623730951 * epsilon; double LB = 0; #ifdef ENABLE_MEMKIND RRRsetAllocator<vertex_type> allocator(libmemkind::kinds::DAX_KMEM_PREFERRED); #else RRRsetAllocator<vertex_type> allocator; #endif std::vector<RRRset<GraphTy>> RR; auto start = std::chrono::high_resolution_clock::now(); size_t thetaPrime = 0; for (ssize_t x = 1; x < std::log2(G.num_nodes()); ++x) { // Equation 9 ssize_t thetaPrime = ThetaPrime(x, epsilonPrime, l, k, G.num_nodes(), std::forward<sequential_tag>(ex_tag)); size_t delta = thetaPrime - RR.size(); record.ThetaPrimeDeltas.push_back(delta); auto timeRRRSets = measure<>::exec_time([&]() { RR.insert(RR.end(), delta, RRRset<GraphTy>(allocator)); auto begin = RR.end() - delta; GenerateRRRSets(G, generator, begin, RR.end(), record, std::forward<diff_model_tag>(model_tag), std::forward<sequential_tag>(ex_tag)); }); record.ThetaEstimationGenerateRRR.push_back(timeRRRSets); double f; auto timeMostInfluential = measure<>::exec_time([&]() { const auto &S = FindMostInfluentialSet( G, CFG, RR, record, false, std::forward<sequential_tag>(ex_tag)); f = S.first; }); record.ThetaEstimationMostInfluential.push_back(timeMostInfluential); if (f >= std::pow(2, -x)) { LB = (G.num_nodes() * f) / (1 + epsilonPrime); break; } } size_t theta = Theta(epsilon, l, k, LB, G.num_nodes()); auto end = std::chrono::high_resolution_clock::now(); record.ThetaEstimationTotal = end - start; record.Theta = theta; record.GenerateRRRSets = measure<>::exec_time([&]() { if (theta > RR.size()) { size_t final_delta = theta - RR.size(); RR.insert(RR.end(), final_delta, RRRset<GraphTy>(allocator)); auto begin = RR.end() - final_delta; GenerateRRRSets(G, generator, begin, RR.end(), record, std::forward<diff_model_tag>(model_tag), std::forward<sequential_tag>(ex_tag)); } }); return RR; } //! The IMM algroithm for Influence Maximization //! //! \tparam GraphTy The type of the input graph. //! \tparam ConfTy The configuration type. //! \tparam PRNG The type of the parallel random number generator. //! \tparam diff_model_tag Type-Tag to selecte the diffusion model. //! //! \param G The input graph. The graph is transoposed. //! \param CFG The configuration. //! \param l Parameter usually set to 1. //! \param gen The parallel random number generator. //! \param model_tag The diffusion model tag. //! \param ex_tag The execution policy tag. template <typename GraphTy, typename ConfTy, typename PRNG, typename diff_model_tag> auto IMM(const GraphTy &G, const ConfTy &CFG, double l, PRNG &gen, IMMExecutionRecord &record, diff_model_tag &&model_tag, sequential_tag &&ex_tag) { using vertex_type = typename GraphTy::vertex_type; size_t k = CFG.k; double epsilon = CFG.epsilon; std::vector<trng::lcg64> generator(1, gen); l = l * (1 + 1 / std::log2(G.num_nodes())); auto R = Sampling(G, CFG, l, generator, record, std::forward<diff_model_tag>(model_tag), std::forward<sequential_tag>(ex_tag)); #if CUDA_PROFILE auto logst = spdlog::stdout_color_st("IMM-profile"); std::vector<size_t> rrr_sizes; for (auto &rrr_set : R) rrr_sizes.push_back(rrr_set.size()); print_profile_counter(logst, rrr_sizes, "RRR sizes"); #endif auto start = std::chrono::high_resolution_clock::now(); const auto &S = FindMostInfluentialSet(G, CFG, R, record, false, std::forward<sequential_tag>(ex_tag)); auto end = std::chrono::high_resolution_clock::now(); record.FindMostInfluentialSet = end - start; return S.second; } //! The IMM algroithm for Influence Maximization //! //! \tparam GraphTy The type of the input graph. //! \tparam ConfTy The configuration type //! \tparam PRNG The type of the parallel random number generator. //! \tparam diff_model_tag Type-Tag to selecte the diffusion model. //! \tparam execution_tag Type-Tag to select the execution policy. //! //! \param G The input graph. The graph is transoposed. //! \param CFG The configuration. //! \param l Parameter usually set to 1. //! \param gen The parallel random number generator. //! \param model_tag The diffusion model tag. //! \param ex_tag The execution policy tag. template <typename GraphTy, typename ConfTy, typename GeneratorTy, typename diff_model_tag> auto IMM(const GraphTy &G, const ConfTy &CFG, double l, GeneratorTy &gen, diff_model_tag &&model_tag, omp_parallel_tag &&ex_tag) { using vertex_type = typename GraphTy::vertex_type; size_t k = CFG.k; double epsilon = CFG.epsilon; auto &record(gen.execution_record()); l = l * (1 + 1 / std::log2(G.num_nodes())); auto R = Sampling(G, CFG, l, gen, record, std::forward<diff_model_tag>(model_tag), std::forward<omp_parallel_tag>(ex_tag)); #if CUDA_PROFILE auto logst = spdlog::stdout_color_st("IMM-profile"); std::vector<size_t> rrr_sizes; size_t sizeBytes = 0; for (auto &rrr_set : R) { rrr_sizes.push_back(rrr_set.size()); sizeBytes += rrr_set.size() * sizeof(rrr_set[0]); } record.RRRSetSize = sizeBytes; print_profile_counter(logst, rrr_sizes, "RRR sizes"); #endif auto start = std::chrono::high_resolution_clock::now(); const auto &S = FindMostInfluentialSet(G, CFG, R, record, gen.isGpuEnabled(), std::forward<omp_parallel_tag>(ex_tag)); auto end = std::chrono::high_resolution_clock::now(); record.FindMostInfluentialSet = end - start; start = std::chrono::high_resolution_clock::now(); size_t total_size = 0; #pragma omp parallel for reduction(+:total_size) for (size_t i = 0; i < R.size(); ++i) { total_size += R[i].size() * sizeof(vertex_type); } record.RRRSetSize = total_size; end = std::chrono::high_resolution_clock::now(); record.Total = end - start; return S.second; } } // namespace ripples #endif // RIPPLES_IMM_H
GB_binop__div_uint16.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__div_uint16) // A.*B function (eWiseMult): GB (_AemultB_08__div_uint16) // A.*B function (eWiseMult): GB (_AemultB_02__div_uint16) // A.*B function (eWiseMult): GB (_AemultB_04__div_uint16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__div_uint16) // A*D function (colscale): GB (_AxD__div_uint16) // D*A function (rowscale): GB (_DxB__div_uint16) // C+=B function (dense accum): GB (_Cdense_accumB__div_uint16) // C+=b function (dense accum): GB (_Cdense_accumb__div_uint16) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__div_uint16) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__div_uint16) // C=scalar+B GB (_bind1st__div_uint16) // C=scalar+B' GB (_bind1st_tran__div_uint16) // C=A+scalar GB (_bind2nd__div_uint16) // C=A'+scalar GB (_bind2nd_tran__div_uint16) // C type: uint16_t // A type: uint16_t // A pattern? 0 // B type: uint16_t // B pattern? 0 // BinaryOp: cij = GB_IDIV_UNSIGNED (aij, bij, 16) #define GB_ATYPE \ uint16_t #define GB_BTYPE \ uint16_t #define GB_CTYPE \ uint16_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) \ uint16_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) \ uint16_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) \ uint16_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 = GB_IDIV_UNSIGNED (x, y, 16) ; // 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_DIV || GxB_NO_UINT16 || GxB_NO_DIV_UINT16) //------------------------------------------------------------------------------ // 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__div_uint16) ( 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 //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__div_uint16) ( 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__div_uint16) ( 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__div_uint16) ( 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 uint16_t uint16_t bwork = (*((uint16_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__div_uint16) ( 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 uint16_t *restrict Cx = (uint16_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__div_uint16) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *restrict Cx = (uint16_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__div_uint16) ( 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) ; uint16_t alpha_scalar ; uint16_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint16_t *) alpha_scalar_in)) ; beta_scalar = (*((uint16_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__div_uint16) ( 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__div_uint16) ( 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__div_uint16) ( 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__div_uint16) ( 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__div_uint16) ( 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 uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t x = (*((uint16_t *) x_input)) ; uint16_t *Bx = (uint16_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 ; uint16_t bij = GBX (Bx, p, false) ; Cx [p] = GB_IDIV_UNSIGNED (x, bij, 16) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__div_uint16) ( 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 ; uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t *Ax = (uint16_t *) Ax_input ; uint16_t y = (*((uint16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint16_t aij = GBX (Ax, p, false) ; Cx [p] = GB_IDIV_UNSIGNED (aij, y, 16) ; } 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) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IDIV_UNSIGNED (x, aij, 16) ; \ } GrB_Info GB (_bind1st_tran__div_uint16) ( 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 \ uint16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t x = (*((const uint16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint16_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) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IDIV_UNSIGNED (aij, y, 16) ; \ } GrB_Info GB (_bind2nd_tran__div_uint16) ( 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 uint16_t y = (*((const uint16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__identity_uint64_bool.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 Generated/ folder, do not edit it (auto-generated). #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_uint64_bool) // op(A') function: GB (_unop_tran__identity_uint64_bool) // C type: uint64_t // A type: bool // cast: uint64_t cij = (uint64_t) aij // unaryop: cij = aij #define GB_ATYPE \ bool #define GB_CTYPE \ uint64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ bool aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint64_t z = (uint64_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ bool aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint64_t z = (uint64_t) aij ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT64 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_uint64_bool) ( uint64_t *Cx, // Cx and Ax may be aliased const bool *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 ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (bool), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { bool aij = Ax [p] ; uint64_t z = (uint64_t) aij ; Cx [p] = z ; } #endif } 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 ; bool aij = Ax [p] ; uint64_t z = (uint64_t) 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_uint64_bool) ( 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
declare_variant_messages.c
// RUN: %clang_cc1 -triple=x86_64-pc-win32 -verify -fopenmp -x c -std=c99 -fms-extensions -Wno-pragma-pack %s // RUN: %clang_cc1 -triple=x86_64-pc-win32 -verify -fopenmp-simd -x c -std=c99 -fms-extensions -Wno-pragma-pack %s #pragma omp declare // expected-error {{expected an OpenMP directive}} int foo(void); #pragma omp declare variant // expected-error {{expected '(' after 'declare variant'}} #pragma omp declare variant( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} #pragma omp declare variant(foo // expected-error {{expected ')'}} expected-error {{expected 'match' clause on 'omp declare variant' directive}} expected-note {{to match this '('}} #pragma omp declare variant(x) // expected-error {{use of undeclared identifier 'x'}} expected-error {{expected 'match' clause on}} #pragma omp declare variant(foo) // expected-error {{expected 'match' clause on 'omp declare variant' directive}} #pragma omp declare variant(foo) // expected-error {{expected 'match' clause on 'omp declare variant' directive}} #pragma omp declare variant(foo) xxx // expected-error {{expected 'match' clause on 'omp declare variant' directive}} #pragma omp declare variant(foo) match // expected-error {{expected '(' after 'match'}} #pragma omp declare variant(foo) match( // expected-error {{expected ')'}} expected-warning {{expected identifier or string literal describing a context set; set skipped}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} expected-note {{to match this '('}} #pragma omp declare variant(foo) match() // expected-warning {{expected identifier or string literal describing a context set; set skipped}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} #pragma omp declare variant(foo) match(xxx) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} #pragma omp declare variant(foo) match(xxx=) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} #pragma omp declare variant(foo) match(xxx=yyy) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} #pragma omp declare variant(foo) match(xxx=yyy}) // expected-error {{expected ')'}} expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} expected-note {{to match this '('}} expected-error {{expected 'match' clause on 'omp declare variant' directive}} #pragma omp declare variant(foo) match(xxx={) // expected-error {{expected ')'}} expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} expected-note {{to match this '('}} #pragma omp declare variant(foo) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} #pragma omp declare variant(foo) match(xxx={vvv, vvv}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} #pragma omp declare variant(foo) match(xxx={vvv} xxx) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} #pragma omp declare variant(foo) match(xxx={vvv}) xxx // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} expected-error {{expected 'match' clause on 'omp declare variant' directive}} #pragma omp declare variant(foo) match(implementation={xxx}) // expected-warning {{'xxx' is not a valid context selector for the context set 'implementation'; selector ignored}} expected-note {{context selector options are: 'vendor' 'extension' 'unified_address' 'unified_shared_memory' 'reverse_offload' 'dynamic_allocators' 'atomic_default_mem_order'}} expected-note {{the ignored selector spans until here}} #pragma omp declare variant(foo) match(implementation={vendor}) // expected-warning {{the context selector 'vendor' in context set 'implementation' requires a context property defined in parentheses; selector ignored}} expected-note {{the ignored selector spans until here}} #pragma omp declare variant(foo) match(implementation={vendor(}) // expected-error {{expected ')'}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'amd' 'arm' 'bsc' 'cray' 'fujitsu' 'gnu' 'ibm' 'intel' 'llvm' 'nec' 'nvidia' 'pgi' 'ti' 'unknown'}} expected-note {{to match this '('}} #pragma omp declare variant(foo) match(implementation={vendor()}) // expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'amd' 'arm' 'bsc' 'cray' 'fujitsu' 'gnu' 'ibm' 'intel' 'llvm' 'nec' 'nvidia' 'pgi' 'ti' 'unknown'}} #pragma omp declare variant(foo) match(implementation={vendor(score ibm)}) // expected-error {{expected '(' after 'score'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} #pragma omp declare variant(foo) match(implementation={vendor(score( ibm)}) // expected-error {{use of undeclared identifier 'ibm'}} expected-error {{expected ')'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'amd' 'arm' 'bsc' 'cray' 'fujitsu' 'gnu' 'ibm' 'intel' 'llvm' 'nec' 'nvidia' 'pgi' 'ti' 'unknown'}} expected-note {{to match this '('}} #pragma omp declare variant(foo) match(implementation={vendor(score(2 ibm)}) // expected-error {{expected ')'}} expected-error {{expected ')'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{to match this '('}} expected-note {{context property options are: 'amd' 'arm' 'bsc' 'cray' 'fujitsu' 'gnu' 'ibm' 'intel' 'llvm' 'nec' 'nvidia' 'pgi' 'ti' 'unknown'}} expected-note {{to match this '('}} #pragma omp declare variant(foo) match(implementation={vendor(score(foo()) ibm)}) // expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{score expressions in the OpenMP context selector need to be constant; foo() is not and will be ignored}} #pragma omp declare variant(foo) match(implementation={vendor(score(5): ibm), vendor(llvm)}) // expected-warning {{the context selector 'vendor' was used already in the same 'omp declare variant' directive; selector ignored}} expected-note {{the previous context selector 'vendor' used here}} expected-note {{the ignored selector spans until here}} #pragma omp declare variant(foo) match(implementation={vendor(score(5): ibm), kind(cpu)}) // expected-warning {{the context selector 'kind' is not valid for the context set 'implementation'; selector ignored}} expected-note {{the context selector 'kind' can be nested in the context set 'device'; try 'match(device={kind(property)})'}} expected-note {{the ignored selector spans until here}} #pragma omp declare variant(foo) match(device={xxx}) // expected-warning {{'xxx' is not a valid context selector for the context set 'device'; selector ignored}} expected-note {{context selector options are: 'kind' 'arch' 'isa'}} expected-note {{the ignored selector spans until here}} #pragma omp declare variant(foo) match(device={kind}) // expected-warning {{the context selector 'kind' in context set 'device' requires a context property defined in parentheses; selector ignored}} expected-note {{the ignored selector spans until here}} #pragma omp declare variant(foo) match(device={kind(}) // expected-error {{expected ')'}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'host' 'nohost' 'cpu' 'gpu' 'fpga' 'any'}} expected-note {{to match this '('}} #pragma omp declare variant(foo) match(device={kind()}) // expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'host' 'nohost' 'cpu' 'gpu' 'fpga' 'any'}} #pragma omp declare variant(foo) match(device={kind(score cpu)}) // expected-error {{expected '(' after 'score'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('<invalid>'); score ignored}} #pragma omp declare variant(foo) match(device = {kind(score(ibm) }) // expected-error {{use of undeclared identifier 'ibm'}} expected-error {{expected ')'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('<recovery-expr>()'); score ignored}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'host' 'nohost' 'cpu' 'gpu' 'fpga' 'any'}} expected-note {{to match this '('}} #pragma omp declare variant(foo) match(device={kind(score(2 gpu)}) // expected-error {{expected ')'}} expected-error {{expected ')'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('2'); score ignored}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{to match this '('}} expected-note {{context property options are: 'host' 'nohost' 'cpu' 'gpu' 'fpga' 'any'}} expected-note {{to match this '('}} #pragma omp declare variant(foo) match(device={kind(score(foo()) ibm)}) // expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('foo()'); score ignored}} expected-warning {{'ibm' is not a valid context property for the context selector 'kind' and the context set 'device'; property ignored}} expected-note {{try 'match(implementation={vendor(ibm)})'}} expected-note {{the ignored property spans until here}} #pragma omp declare variant(foo) match(device={kind(score(5): host), kind(llvm)}) // expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('5'); score ignored}} expected-warning {{the context selector 'kind' was used already in the same 'omp declare variant' directive; selector ignored}} expected-note {{the previous context selector 'kind' used here}} expected-note {{the ignored selector spans until here}} #pragma omp declare variant(foo) match(device={kind(score(5): nohost), vendor(llvm)}) // expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('5'); score ignored}} expected-warning {{the context selector 'vendor' is not valid for the context set 'device'; selector ignored}} expected-note {{the context selector 'vendor' can be nested in the context set 'implementation'; try 'match(implementation={vendor(property)})'}} expected-note {{the ignored selector spans until here}} #pragma omp declare variant(foo) match(implementation={extension("aaa")}) // expected-warning {{'aaa' is not a valid context property for the context selector 'extension' and the context set 'implementation'; property ignored}} expected-note {{context property options are: 'match_all' 'match_any' 'match_none'}} expected-note {{the ignored property spans until here}} int bar(void); #pragma omp declare variant(foo) match(implementation = {vendor(score(foo) :llvm)}) // expected-warning {{score expressions in the OpenMP context selector need to be constant; foo is not and will be ignored}} #pragma omp declare variant(foo) match(implementation = {vendor(score(foo()) :llvm)}) // expected-warning {{score expressions in the OpenMP context selector need to be constant; foo() is not and will be ignored}} #pragma omp declare variant(foo) match(implementation = {vendor(score(<expr>) :llvm)}) // expected-error {{expected expression}} expected-error {{use of undeclared identifier 'expr'}} expected-error {{expected expression}} #pragma omp declare variant(foo) match(user = {condition(foo)}) // expected-error {{the user condition in the OpenMP context selector needs to be constant; foo is not}} #pragma omp declare variant(foo) match(user = {condition(foo())}) // expected-error {{the user condition in the OpenMP context selector needs to be constant; foo() is not}} #pragma omp declare variant(foo) match(user = {condition(<expr>)}) // expected-error {{expected expression}} expected-error {{use of undeclared identifier 'expr'}} expected-error {{expected expression}} expected-note {{the ignored selector spans until here}} int score_and_cond_non_const(void); #pragma omp declare variant(foo) match(construct={teams,parallel,for,simd}) #pragma omp declare variant(foo) match(construct={target teams}) // expected-error {{expected ')'}} expected-warning {{expected '}' after the context selectors for the context set "construct"; '}' assumed}} expected-note {{to match this '('}} expected-error {{expected 'match' clause on 'omp declare variant' directive}} #pragma omp declare variant(foo) match(construct={parallel for}) // expected-error {{expected ')'}} expected-warning {{expected '}' after the context selectors for the context set "construct"; '}' assumed}} expected-note {{to match this '('}} expected-error {{expected 'match' clause on 'omp declare variant' directive}} #pragma omp declare variant(foo) match(construct={for simd}) // expected-error {{expected ')'}} expected-warning {{expected '}' after the context selectors for the context set "construct"; '}' assumed}} expected-note {{to match this '('}} expected-error {{expected 'match' clause on 'omp declare variant' directive}} int construct(void); #pragma omp declare variant(foo) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} int a; // expected-error {{'#pragma omp declare variant' can only be applied to functions}} #pragma omp declare variant(foo) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} #pragma omp threadprivate(a) // expected-error {{'#pragma omp declare variant' can only be applied to functions}} int var; #pragma omp threadprivate(var) #pragma omp declare variant(foo) match(xxx={}) // expected-error {{function declaration is expected after 'declare variant' directive}} #pragma omp declare // expected-error {{expected an OpenMP directive}} #pragma omp declare variant(foo) match(xxx={}) // expected-error {{function declaration is expected after 'declare variant' directive}} #pragma omp declare variant(foo) match(xxx={}) // expected-error {{function declaration is expected after 'declare variant' directive}} #pragma options align=packed int main(void); #pragma omp declare variant(foo) match(implementation={vendor(llvm)}) // expected-error {{function declaration is expected after 'declare variant' directive}} #pragma omp declare variant(foo) match(implementation={vendor(llvm)}) // expected-error {{function declaration is expected after 'declare variant' directive}} #pragma init_seg(compiler) int main(void); #pragma omp declare variant(foo) match(xxx={}) // expected-error {{single declaration is expected after 'declare variant' directive}} expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} int b, c; int no_proto(); #pragma omp declare variant(no_proto) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} int no_proto_too(); int proto1(int); #pragma omp declare variant(proto1) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} int diff_proto(); // expected-note {{previous declaration is here}} int diff_proto(double); // expected-error {{conflicting types for 'diff_proto'}} #pragma omp declare variant(no_proto) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} int diff_proto1(double); int after_use_variant(void); int after_use(void); int bar(void) { return after_use(); } #pragma omp declare variant(after_use_variant) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-warning {{'#pragma omp declare variant' cannot be applied for function after first usage; the original function might be used}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} int after_use(void); #pragma omp declare variant(after_use_variant) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} int defined(void) { return 0; } int defined1(void) { return 0; } #pragma omp declare variant(after_use_variant) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-warning {{'#pragma omp declare variant' cannot be applied to the function that was defined already; the original function might be used}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} int defined1(void); int diff_cc_variant(void); #pragma omp declare variant(diff_cc_variant) match(xxx={}) // expected-error {{variant in '#pragma omp declare variant' with type 'int (void)' is incompatible with type 'int (void) __attribute__((vectorcall))'}} expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} __vectorcall int diff_cc(void); int diff_ret_variant(void); #pragma omp declare variant(diff_ret_variant) match(xxx={}) // expected-error {{variant in '#pragma omp declare variant' with type 'int (void)' is incompatible with type 'void (void)'}} expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} void diff_ret(void); void marked(void); void not_marked(void); #pragma omp declare variant(not_marked) match(implementation={vendor(unknown)}, device={kind(cpu)}) // expected-note {{marked as 'declare variant' here}} void marked_variant(void); #pragma omp declare variant(marked_variant) match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-warning {{variant function in '#pragma omp declare variant' is itself marked as '#pragma omp declare variant'}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} void marked(void); #pragma omp declare variant(foo) match(device = {isa("foo")}) int unknown_isa_trait(void); #pragma omp declare variant(foo) match(device = {isa(foo)}) int unknown_isa_trait2(void); #pragma omp declare variant(foo) match(device = {kind(fpga), isa(bar)}) int ignored_isa_trait(void); void caller(void) { unknown_isa_trait(); // expected-warning {{isa trait 'foo' is not known to the current target; verify the spelling or consider restricting the context selector with the 'arch' selector further}} unknown_isa_trait2(); // expected-warning {{isa trait 'foo' is not known to the current target; verify the spelling or consider restricting the context selector with the 'arch' selector further}} ignored_isa_trait(); } // Unknown arch #pragma omp begin declare variant match(device={isa(sse2020)}) // expected-warning {{isa trait 'sse2020' is not known to the current target; verify the spelling or consider restricting the context selector with the 'arch' selector further}} #pragma omp end declare variant // Unknown arch guarded by arch. #pragma omp begin declare variant match(device={isa(sse2020), arch(ppc)}) #pragma omp end declare variant #pragma omp declare variant // expected-error {{function declaration is expected after 'declare variant' directive}} #pragma omp declare variant // expected-error {{function declaration is expected after 'declare variant' directive}} // FIXME: If the scores are equivalent we should detect that and allow it. #pragma omp begin declare variant match(implementation = {vendor(score(2) \ : llvm)}) #pragma omp declare variant(foo) match(implementation = {vendor(score(2) \ : llvm)}) // expected-error@-1 {{nested OpenMP context selector contains duplicated trait 'llvm' in selector 'vendor' and set 'implementation' with different score}} int conflicting_nested_score(void); #pragma omp end declare variant // FIXME: We should build the conjuction of different conditions, see also the score fixme above. #pragma omp begin declare variant match(user = {condition(1)}) #pragma omp declare variant(foo) match(user = {condition(1)}) // expected-error {{nested user conditions in OpenMP context selector not supported (yet)}} int conflicting_nested_condition(void); #pragma omp end declare variant
image.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % IIIII M M AAA GGGG EEEEE % % I MM MM A A G E % % I M M M AAAAA G GG EEE % % I M M A A G G E % % IIIII M M A A GGGG EEEEE % % % % % % MagickCore Image Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2020 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/animate.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/compress.h" #include "MagickCore/constitute.h" #include "MagickCore/delegate.h" #include "MagickCore/display.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magic.h" #include "MagickCore/magick.h" #include "MagickCore/magick-private.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/module.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/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantize.h" #include "MagickCore/random_.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/semaphore.h" #include "MagickCore/signature-private.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/timer.h" #include "MagickCore/timer-private.h" #include "MagickCore/token.h" #include "MagickCore/token-private.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" #include "MagickCore/xwindow-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireImage() returns a pointer to an image structure initialized to % default values. % % The format of the AcquireImage method is: % % Image *AcquireImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Many of the image default values are set from this % structure. For example, filename, compression, depth, background color, % and others. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AcquireImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; Image *image; MagickStatusType flags; /* Allocate image structure. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); image=(Image *) AcquireCriticalMemory(sizeof(*image)); (void) memset(image,0,sizeof(*image)); /* Initialize Image structure. */ (void) CopyMagickString(image->magick,"MIFF",MagickPathExtent); image->storage_class=DirectClass; image->depth=MAGICKCORE_QUANTUM_DEPTH; image->colorspace=sRGBColorspace; image->rendering_intent=PerceptualIntent; image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.red_primary.z=0.0300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.green_primary.z=0.1000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.blue_primary.z=0.7900f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; image->chromaticity.white_point.z=0.3583f; image->interlace=NoInterlace; image->ticks_per_second=UndefinedTicksPerSecond; image->compose=OverCompositeOp; (void) QueryColorCompliance(MatteColor,AllCompliance,&image->matte_color, exception); (void) QueryColorCompliance(BackgroundColor,AllCompliance, &image->background_color,exception); (void) QueryColorCompliance(BorderColor,AllCompliance,&image->border_color, exception); (void) QueryColorCompliance(TransparentColor,AllCompliance, &image->transparent_color,exception); GetTimerInfo(&image->timer); image->cache=AcquirePixelCache(0); image->channel_mask=DefaultChannels; image->channel_map=AcquirePixelChannelMap(); image->blob=CloneBlobInfo((BlobInfo *) NULL); image->timestamp=GetMagickTime(); image->debug=IsEventLogging(); image->reference_count=1; image->semaphore=AcquireSemaphoreInfo(); image->signature=MagickCoreSignature; if (image_info == (ImageInfo *) NULL) return(image); /* Transfer image info. */ SetBlobExempt(image,image_info->file != (FILE *) NULL ? MagickTrue : MagickFalse); (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,image_info->magick,MagickPathExtent); if (image_info->size != (char *) NULL) { (void) ParseAbsoluteGeometry(image_info->size,&image->extract_info); image->columns=image->extract_info.width; image->rows=image->extract_info.height; image->offset=image->extract_info.x; image->extract_info.x=0; image->extract_info.y=0; } if (image_info->extract != (char *) NULL) { RectangleInfo geometry; (void) memset(&geometry,0,sizeof(geometry)); flags=ParseAbsoluteGeometry(image_info->extract,&geometry); if (((flags & XValue) != 0) || ((flags & YValue) != 0)) { image->extract_info=geometry; Swap(image->columns,image->extract_info.width); Swap(image->rows,image->extract_info.height); } } image->compression=image_info->compression; image->quality=image_info->quality; image->endian=image_info->endian; image->interlace=image_info->interlace; image->units=image_info->units; if (image_info->density != (char *) NULL) { GeometryInfo geometry_info; flags=ParseGeometry(image_info->density,&geometry_info); if ((flags & RhoValue) != 0) image->resolution.x=geometry_info.rho; image->resolution.y=image->resolution.x; if ((flags & SigmaValue) != 0) image->resolution.y=geometry_info.sigma; } if (image_info->page != (char *) NULL) { char *geometry; image->page=image->extract_info; geometry=GetPageGeometry(image_info->page); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); } if (image_info->depth != 0) image->depth=image_info->depth; image->dither=image_info->dither; image->matte_color=image_info->matte_color; image->background_color=image_info->background_color; image->border_color=image_info->border_color; image->transparent_color=image_info->transparent_color; image->ping=image_info->ping; image->progress_monitor=image_info->progress_monitor; image->client_data=image_info->client_data; if (image_info->cache != (void *) NULL) ClonePixelCacheMethods(image->cache,image_info->cache); /* Set all global options that map to per-image settings. */ (void) SyncImageSettings(image_info,image,exception); /* Global options that are only set for new images. */ option=GetImageOption(image_info,"delay"); if (option != (const char *) NULL) { GeometryInfo geometry_info; flags=ParseGeometry(option,&geometry_info); if ((flags & GreaterValue) != 0) { if (image->delay > (size_t) floor(geometry_info.rho+0.5)) image->delay=(size_t) floor(geometry_info.rho+0.5); } else if ((flags & LessValue) != 0) { if (image->delay < (size_t) floor(geometry_info.rho+0.5)) image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); } else image->delay=(size_t) floor(geometry_info.rho+0.5); if ((flags & SigmaValue) != 0) image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); } option=GetImageOption(image_info,"dispose"); if (option != (const char *) NULL) image->dispose=(DisposeType) ParseCommandOption(MagickDisposeOptions, MagickFalse,option); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireImageInfo() allocates the ImageInfo structure. % % The format of the AcquireImageInfo method is: % % ImageInfo *AcquireImageInfo(void) % */ MagickExport ImageInfo *AcquireImageInfo(void) { ImageInfo *image_info; image_info=(ImageInfo *) AcquireCriticalMemory(sizeof(*image_info)); GetImageInfo(image_info); return(image_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e N e x t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireNextImage() initializes the next image in a sequence to % default values. The next member of image points to the newly allocated % image. If there is a memory shortage, next is assigned NULL. % % The format of the AcquireNextImage method is: % % void AcquireNextImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Many of the image default values are set from this % structure. For example, filename, compression, depth, background color, % and others. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport void AcquireNextImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { /* Allocate image structure. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); image->next=AcquireImage(image_info,exception); if (GetNextImageInList(image) == (Image *) NULL) return; (void) CopyMagickString(GetNextImageInList(image)->filename,image->filename, MagickPathExtent); if (image_info != (ImageInfo *) NULL) (void) CopyMagickString(GetNextImageInList(image)->filename, image_info->filename,MagickPathExtent); DestroyBlob(GetNextImageInList(image)); image->next->blob=ReferenceBlob(image->blob); image->next->endian=image->endian; image->next->scene=image->scene+1; image->next->previous=image; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A p p e n d I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AppendImages() takes all images from the current image pointer to the end % of the image list and appends them to each other top-to-bottom if the % stack parameter is true, otherwise left-to-right. % % The current gravity setting effects how the image is justified in the % final image. % % The format of the AppendImages method is: % % Image *AppendImages(const Image *images,const MagickBooleanType stack, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o stack: A value other than 0 stacks the images top-to-bottom. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AppendImages(const Image *images, const MagickBooleanType stack,ExceptionInfo *exception) { #define AppendImageTag "Append/Image" CacheView *append_view; Image *append_image; MagickBooleanType homogeneous_colorspace, status; MagickOffsetType n; PixelTrait alpha_trait; RectangleInfo geometry; register const Image *next; size_t depth, height, number_images, width; ssize_t x_offset, y, y_offset; /* Compute maximum area of appended area. */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); alpha_trait=images->alpha_trait; number_images=1; width=images->columns; height=images->rows; depth=images->depth; homogeneous_colorspace=MagickTrue; next=GetNextImageInList(images); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (next->depth > depth) depth=next->depth; if (next->colorspace != images->colorspace) homogeneous_colorspace=MagickFalse; if (next->alpha_trait != UndefinedPixelTrait) alpha_trait=BlendPixelTrait; number_images++; if (stack != MagickFalse) { if (next->columns > width) width=next->columns; height+=next->rows; continue; } width+=next->columns; if (next->rows > height) height=next->rows; } /* Append images. */ append_image=CloneImage(images,width,height,MagickTrue,exception); if (append_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(append_image,DirectClass,exception) == MagickFalse) { append_image=DestroyImage(append_image); return((Image *) NULL); } if (homogeneous_colorspace == MagickFalse) (void) SetImageColorspace(append_image,sRGBColorspace,exception); append_image->depth=depth; append_image->alpha_trait=alpha_trait; append_image->page=images->page; (void) SetImageBackgroundColor(append_image,exception); status=MagickTrue; x_offset=0; y_offset=0; next=images; append_view=AcquireAuthenticCacheView(append_image,exception); for (n=0; n < (MagickOffsetType) number_images; n++) { CacheView *image_view; MagickBooleanType proceed; SetGeometry(append_image,&geometry); GravityAdjustGeometry(next->columns,next->rows,next->gravity,&geometry); if (stack != MagickFalse) x_offset-=geometry.x; else y_offset-=geometry.y; image_view=AcquireVirtualCacheView(next,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(next,next,next->rows,1) #endif for (y=0; y < (ssize_t) next->rows; y++) { MagickBooleanType sync; PixelInfo pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,next->columns,1,exception); q=QueueCacheViewAuthenticPixels(append_view,x_offset,y+y_offset, next->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } GetPixelInfo(next,&pixel); for (x=0; x < (ssize_t) next->columns; x++) { GetPixelInfoPixel(next,p,&pixel); SetPixelViaPixelInfo(append_image,&pixel,q); p+=GetPixelChannels(next); q+=GetPixelChannels(append_image); } sync=SyncCacheViewAuthenticPixels(append_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (stack == MagickFalse) { x_offset+=(ssize_t) next->columns; y_offset=0; } else { x_offset=0; y_offset+=(ssize_t) next->rows; } proceed=SetImageProgress(append_image,AppendImageTag,n,number_images); if (proceed == MagickFalse) break; next=GetNextImageInList(next); } append_view=DestroyCacheView(append_view); if (status == MagickFalse) append_image=DestroyImage(append_image); return(append_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C a t c h I m a g e E x c e p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CatchImageException() returns if no exceptions are found in the image % sequence, otherwise it determines the most severe exception and reports % it as a warning or error depending on the severity. % % The format of the CatchImageException method is: % % ExceptionType CatchImageException(Image *image) % % A description of each parameter follows: % % o image: An image sequence. % */ MagickExport ExceptionType CatchImageException(Image *image) { ExceptionInfo *exception; ExceptionType severity; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); exception=AcquireExceptionInfo(); CatchException(exception); severity=exception->severity; exception=DestroyExceptionInfo(exception); return(severity); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l i p I m a g e P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClipImagePath() sets the image clip mask based any clipping path information % if it exists. % % The format of the ClipImagePath method is: % % MagickBooleanType ClipImagePath(Image *image,const char *pathname, % const MagickBooleanType inside,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o pathname: name of clipping path resource. If name is preceded by #, use % clipping path numbered by name. % % o inside: if non-zero, later operations take effect inside clipping path. % Otherwise later operations take effect outside clipping path. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ClipImage(Image *image,ExceptionInfo *exception) { return(ClipImagePath(image,"#1",MagickTrue,exception)); } MagickExport MagickBooleanType ClipImagePath(Image *image,const char *pathname, const MagickBooleanType inside,ExceptionInfo *exception) { #define ClipImagePathTag "ClipPath/Image" char *property; const char *value; Image *clip_mask; ImageInfo *image_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pathname != NULL); property=AcquireString(pathname); (void) FormatLocaleString(property,MagickPathExtent,"8BIM:1999,2998:%s", pathname); value=GetImageProperty(image,property,exception); property=DestroyString(property); if (value == (const char *) NULL) { ThrowFileException(exception,OptionError,"NoClipPathDefined", image->filename); return(MagickFalse); } image_info=AcquireImageInfo(); (void) CopyMagickString(image_info->filename,image->filename, MagickPathExtent); (void) ConcatenateMagickString(image_info->filename,pathname, MagickPathExtent); clip_mask=BlobToImage(image_info,value,strlen(value),exception); image_info=DestroyImageInfo(image_info); if (clip_mask == (Image *) NULL) return(MagickFalse); if (clip_mask->storage_class == PseudoClass) { (void) SyncImage(clip_mask,exception); if (SetImageStorageClass(clip_mask,DirectClass,exception) == MagickFalse) return(MagickFalse); } if (inside == MagickFalse) (void) NegateImage(clip_mask,MagickFalse,exception); (void) FormatLocaleString(clip_mask->magick_filename,MagickPathExtent, "8BIM:1999,2998:%s\nPS",pathname); (void) SetImageMask(image,WritePixelMask,clip_mask,exception); image->mask_trait=UpdatePixelTrait; clip_mask=DestroyImage(clip_mask); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImage() copies an image and returns the copy as a new image object. % % If the specified columns and rows is 0, an exact copy of the image is % returned, otherwise the pixel data is undefined and must be initialized % with the QueueAuthenticPixels() and SyncAuthenticPixels() methods. On % failure, a NULL image is returned and exception describes the reason for the % failure. % % The format of the CloneImage method is: % % Image *CloneImage(const Image *image,const size_t columns, % const size_t rows,const MagickBooleanType orphan, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the cloned image. % % o rows: the number of rows in the cloned image. % % o detach: With a value other than 0, the cloned image is detached from % its parent I/O stream. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CloneImage(const Image *image,const size_t columns, const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception) { Image *clone_image; double scale; size_t length; /* Clone the image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((image->columns == 0) || (image->rows == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "NegativeOrZeroImageSize","`%s'",image->filename); return((Image *) NULL); } clone_image=(Image *) AcquireCriticalMemory(sizeof(*clone_image)); (void) memset(clone_image,0,sizeof(*clone_image)); clone_image->signature=MagickCoreSignature; clone_image->storage_class=image->storage_class; clone_image->number_channels=image->number_channels; clone_image->number_meta_channels=image->number_meta_channels; clone_image->metacontent_extent=image->metacontent_extent; clone_image->colorspace=image->colorspace; clone_image->alpha_trait=image->alpha_trait; clone_image->channels=image->channels; clone_image->mask_trait=image->mask_trait; clone_image->columns=image->columns; clone_image->rows=image->rows; clone_image->dither=image->dither; clone_image->image_info=CloneImageInfo(image->image_info); (void) CloneImageProfiles(clone_image,image); (void) CloneImageProperties(clone_image,image); (void) CloneImageArtifacts(clone_image,image); GetTimerInfo(&clone_image->timer); if (image->ascii85 != (void *) NULL) Ascii85Initialize(clone_image); clone_image->extent=image->extent; clone_image->magick_columns=image->magick_columns; clone_image->magick_rows=image->magick_rows; clone_image->type=image->type; clone_image->channel_mask=image->channel_mask; clone_image->channel_map=ClonePixelChannelMap(image->channel_map); (void) CopyMagickString(clone_image->magick_filename,image->magick_filename, MagickPathExtent); (void) CopyMagickString(clone_image->magick,image->magick,MagickPathExtent); (void) CopyMagickString(clone_image->filename,image->filename, MagickPathExtent); clone_image->progress_monitor=image->progress_monitor; clone_image->client_data=image->client_data; clone_image->reference_count=1; clone_image->next=image->next; clone_image->previous=image->previous; clone_image->list=NewImageList(); if (detach == MagickFalse) clone_image->blob=ReferenceBlob(image->blob); else { clone_image->next=NewImageList(); clone_image->previous=NewImageList(); clone_image->blob=CloneBlobInfo((BlobInfo *) NULL); } clone_image->ping=image->ping; clone_image->debug=IsEventLogging(); clone_image->semaphore=AcquireSemaphoreInfo(); if (image->colormap != (PixelInfo *) NULL) { /* Allocate and copy the image colormap. */ clone_image->colors=image->colors; length=(size_t) image->colors; clone_image->colormap=(PixelInfo *) AcquireQuantumMemory(length+1, sizeof(*clone_image->colormap)); if (clone_image->colormap == (PixelInfo *) NULL) { clone_image=DestroyImage(clone_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } (void) memcpy(clone_image->colormap,image->colormap,length* sizeof(*clone_image->colormap)); } if ((columns == 0) || (rows == 0)) { if (image->montage != (char *) NULL) (void) CloneString(&clone_image->montage,image->montage); if (image->directory != (char *) NULL) (void) CloneString(&clone_image->directory,image->directory); clone_image->cache=ReferencePixelCache(image->cache); return(clone_image); } scale=1.0; if (image->columns != 0) scale=(double) columns/(double) image->columns; clone_image->page.width=(size_t) floor(scale*image->page.width+0.5); clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5); clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5); scale=1.0; if (image->rows != 0) scale=(double) rows/(double) image->rows; clone_image->page.height=(size_t) floor(scale*image->page.height+0.5); clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5); clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5); clone_image->cache=ClonePixelCache(image->cache); if (SetImageExtent(clone_image,columns,rows,exception) == MagickFalse) clone_image=DestroyImage(clone_image); return(clone_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageInfo() makes a copy of the given image info structure. If % NULL is specified, a new image info structure is created initialized to % default values. % % The format of the CloneImageInfo method is: % % ImageInfo *CloneImageInfo(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport ImageInfo *CloneImageInfo(const ImageInfo *image_info) { ImageInfo *clone_info; clone_info=AcquireImageInfo(); if (image_info == (ImageInfo *) NULL) return(clone_info); clone_info->compression=image_info->compression; clone_info->temporary=image_info->temporary; clone_info->adjoin=image_info->adjoin; clone_info->antialias=image_info->antialias; clone_info->scene=image_info->scene; clone_info->number_scenes=image_info->number_scenes; clone_info->depth=image_info->depth; if (image_info->size != (char *) NULL) (void) CloneString(&clone_info->size,image_info->size); if (image_info->extract != (char *) NULL) (void) CloneString(&clone_info->extract,image_info->extract); if (image_info->scenes != (char *) NULL) (void) CloneString(&clone_info->scenes,image_info->scenes); if (image_info->page != (char *) NULL) (void) CloneString(&clone_info->page,image_info->page); clone_info->interlace=image_info->interlace; clone_info->endian=image_info->endian; clone_info->units=image_info->units; clone_info->quality=image_info->quality; if (image_info->sampling_factor != (char *) NULL) (void) CloneString(&clone_info->sampling_factor, image_info->sampling_factor); if (image_info->server_name != (char *) NULL) (void) CloneString(&clone_info->server_name,image_info->server_name); if (image_info->font != (char *) NULL) (void) CloneString(&clone_info->font,image_info->font); if (image_info->texture != (char *) NULL) (void) CloneString(&clone_info->texture,image_info->texture); if (image_info->density != (char *) NULL) (void) CloneString(&clone_info->density,image_info->density); clone_info->pointsize=image_info->pointsize; clone_info->fuzz=image_info->fuzz; clone_info->matte_color=image_info->matte_color; clone_info->background_color=image_info->background_color; clone_info->border_color=image_info->border_color; clone_info->transparent_color=image_info->transparent_color; clone_info->dither=image_info->dither; clone_info->monochrome=image_info->monochrome; clone_info->colorspace=image_info->colorspace; clone_info->type=image_info->type; clone_info->orientation=image_info->orientation; clone_info->ping=image_info->ping; clone_info->verbose=image_info->verbose; clone_info->progress_monitor=image_info->progress_monitor; clone_info->client_data=image_info->client_data; clone_info->cache=image_info->cache; if (image_info->cache != (void *) NULL) clone_info->cache=ReferencePixelCache(image_info->cache); if (image_info->profile != (void *) NULL) clone_info->profile=(void *) CloneStringInfo((StringInfo *) image_info->profile); SetImageInfoFile(clone_info,image_info->file); SetImageInfoBlob(clone_info,image_info->blob,image_info->length); clone_info->stream=image_info->stream; clone_info->custom_stream=image_info->custom_stream; (void) CopyMagickString(clone_info->magick,image_info->magick, MagickPathExtent); (void) CopyMagickString(clone_info->unique,image_info->unique, MagickPathExtent); (void) CopyMagickString(clone_info->filename,image_info->filename, MagickPathExtent); clone_info->channel=image_info->channel; (void) CloneImageOptions(clone_info,image_info); clone_info->debug=IsEventLogging(); clone_info->signature=image_info->signature; return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o p y I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CopyImagePixels() copies pixels from the source image as defined by the % geometry the destination image at the specified offset. % % The format of the CopyImagePixels method is: % % MagickBooleanType CopyImagePixels(Image *image,const Image *source_image, % const RectangleInfo *geometry,const OffsetInfo *offset, % ExceptionInfo *exception); % % A description of each parameter follows: % % o image: the destination image. % % o source_image: the source image. % % o geometry: define the dimensions of the source pixel rectangle. % % o offset: define the offset in the destination image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType CopyImagePixels(Image *image, const Image *source_image,const RectangleInfo *geometry, const OffsetInfo *offset,ExceptionInfo *exception) { #define CopyImageTag "Copy/Image" CacheView *image_view, *source_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(source_image != (Image *) NULL); assert(geometry != (RectangleInfo *) NULL); assert(offset != (OffsetInfo *) NULL); if ((offset->x < 0) || (offset->y < 0) || ((ssize_t) (offset->x+geometry->width) > (ssize_t) image->columns) || ((ssize_t) (offset->y+geometry->height) > (ssize_t) image->rows)) ThrowBinaryException(OptionError,"GeometryDoesNotContainImage", image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); /* Copy image pixels. */ status=MagickTrue; progress=0; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,source_image,geometry->height,1) #endif for (y=0; y < (ssize_t) geometry->height; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,geometry->x,y+geometry->y, geometry->width,1,exception); q=QueueCacheViewAuthenticPixels(image_view,offset->x,y+offset->y, geometry->width,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) geometry->width; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image,channel); if ((traits == UndefinedPixelTrait) || ((traits & UpdatePixelTrait) == 0) || (source_traits == UndefinedPixelTrait)) continue; SetPixelChannel(image,channel,p[i],q); } p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CopyImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImage() dereferences an image, deallocating memory associated with % the image if the reference count becomes zero. % % The format of the DestroyImage method is: % % Image *DestroyImage(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Image *DestroyImage(Image *image) { MagickBooleanType destroy; /* Dereference image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); destroy=MagickFalse; LockSemaphoreInfo(image->semaphore); image->reference_count--; if (image->reference_count == 0) destroy=MagickTrue; UnlockSemaphoreInfo(image->semaphore); if (destroy == MagickFalse) return((Image *) NULL); /* Destroy image. */ DestroyImagePixels(image); image->channel_map=DestroyPixelChannelMap(image->channel_map); if (image->montage != (char *) NULL) image->montage=DestroyString(image->montage); if (image->directory != (char *) NULL) image->directory=DestroyString(image->directory); if (image->colormap != (PixelInfo *) NULL) image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap); if (image->geometry != (char *) NULL) image->geometry=DestroyString(image->geometry); DestroyImageProfiles(image); DestroyImageProperties(image); DestroyImageArtifacts(image); if (image->ascii85 != (Ascii85Info *) NULL) image->ascii85=(Ascii85Info *) RelinquishMagickMemory(image->ascii85); if (image->image_info != (ImageInfo *) NULL) image->image_info=DestroyImageInfo(image->image_info); DestroyBlob(image); if (image->semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&image->semaphore); image->signature=(~MagickCoreSignature); image=(Image *) RelinquishMagickMemory(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageInfo() deallocates memory associated with an ImageInfo % structure. % % The format of the DestroyImageInfo method is: % % ImageInfo *DestroyImageInfo(ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport ImageInfo *DestroyImageInfo(ImageInfo *image_info) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); if (image_info->size != (char *) NULL) image_info->size=DestroyString(image_info->size); if (image_info->extract != (char *) NULL) image_info->extract=DestroyString(image_info->extract); if (image_info->scenes != (char *) NULL) image_info->scenes=DestroyString(image_info->scenes); if (image_info->page != (char *) NULL) image_info->page=DestroyString(image_info->page); if (image_info->sampling_factor != (char *) NULL) image_info->sampling_factor=DestroyString( image_info->sampling_factor); if (image_info->server_name != (char *) NULL) image_info->server_name=DestroyString( image_info->server_name); if (image_info->font != (char *) NULL) image_info->font=DestroyString(image_info->font); if (image_info->texture != (char *) NULL) image_info->texture=DestroyString(image_info->texture); if (image_info->density != (char *) NULL) image_info->density=DestroyString(image_info->density); if (image_info->cache != (void *) NULL) image_info->cache=DestroyPixelCache(image_info->cache); if (image_info->profile != (StringInfo *) NULL) image_info->profile=(void *) DestroyStringInfo((StringInfo *) image_info->profile); DestroyImageOptions(image_info); image_info->signature=(~MagickCoreSignature); image_info=(ImageInfo *) RelinquishMagickMemory(image_info); return(image_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D i s a s s o c i a t e I m a g e S t r e a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DisassociateImageStream() disassociates the image stream. It checks if the % blob of the specified image is referenced by other images. If the reference % count is higher then 1 a new blob is assigned to the specified image. % % The format of the DisassociateImageStream method is: % % void DisassociateImageStream(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DisassociateImageStream(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); DisassociateBlob(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageInfo() initializes image_info to default values. % % The format of the GetImageInfo method is: % % void GetImageInfo(ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport void GetImageInfo(ImageInfo *image_info) { char *synchronize; ExceptionInfo *exception; /* File and image dimension members. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image_info != (ImageInfo *) NULL); (void) memset(image_info,0,sizeof(*image_info)); image_info->adjoin=MagickTrue; image_info->interlace=NoInterlace; image_info->channel=DefaultChannels; image_info->quality=UndefinedCompressionQuality; image_info->antialias=MagickTrue; image_info->dither=MagickTrue; synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (synchronize != (const char *) NULL) { image_info->synchronize=IsStringTrue(synchronize); synchronize=DestroyString(synchronize); } exception=AcquireExceptionInfo(); (void) QueryColorCompliance(BackgroundColor,AllCompliance, &image_info->background_color,exception); (void) QueryColorCompliance(BorderColor,AllCompliance, &image_info->border_color,exception); (void) QueryColorCompliance(MatteColor,AllCompliance,&image_info->matte_color, exception); (void) QueryColorCompliance(TransparentColor,AllCompliance, &image_info->transparent_color,exception); exception=DestroyExceptionInfo(exception); image_info->debug=IsEventLogging(); image_info->signature=MagickCoreSignature; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e I n f o F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageInfoFile() returns the image info file member. % % The format of the GetImageInfoFile method is: % % FILE *GetImageInfoFile(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport FILE *GetImageInfoFile(const ImageInfo *image_info) { return(image_info->file); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageMask() returns the mask associated with the image. % % The format of the GetImageMask method is: % % Image *GetImageMask(const Image *image,const PixelMask type, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % */ MagickExport Image *GetImageMask(const Image *image,const PixelMask type, ExceptionInfo *exception) { CacheView *mask_view, *image_view; Image *mask_image; MagickBooleanType status; ssize_t y; /* Get image mask. */ assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); switch (type) { case ReadPixelMask: { if ((image->channels & ReadMaskChannel) == 0) return((Image *) NULL); break; } case WritePixelMask: { if ((image->channels & WriteMaskChannel) == 0) return((Image *) NULL); break; } default: { if ((image->channels & CompositeMaskChannel) == 0) return((Image *) NULL); break; } } mask_image=AcquireImage((ImageInfo *) NULL,exception); status=SetImageExtent(mask_image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImage(mask_image)); status=MagickTrue; mask_image->alpha_trait=UndefinedPixelTrait; (void) SetImageColorspace(mask_image,GRAYColorspace,exception); image_view=AcquireVirtualCacheView(image,exception); mask_view=AcquireAuthenticCacheView(mask_image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(mask_view,0,y,mask_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { switch (type) { case ReadPixelMask: { SetPixelGray(mask_image,GetPixelReadMask(image,p),q); break; } case WritePixelMask: { SetPixelGray(mask_image,GetPixelWriteMask(image,p),q); break; } default: { SetPixelGray(mask_image,GetPixelCompositeMask(image,p),q); break; } } p+=GetPixelChannels(image); q+=GetPixelChannels(mask_image); } if (SyncCacheViewAuthenticPixels(mask_view,exception) == MagickFalse) status=MagickFalse; } mask_view=DestroyCacheView(mask_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) mask_image=DestroyImage(mask_image); return(mask_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e R e f e r e n c e C o u n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageReferenceCount() returns the image reference count. % % The format of the GetReferenceCount method is: % % ssize_t GetImageReferenceCount(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport ssize_t GetImageReferenceCount(Image *image) { ssize_t reference_count; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); LockSemaphoreInfo(image->semaphore); reference_count=image->reference_count; UnlockSemaphoreInfo(image->semaphore); return(reference_count); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i r t u a l P i x e l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageVirtualPixelMethod() gets the "virtual pixels" method for the % image. A virtual pixel is any pixel access that is outside the boundaries % of the image cache. % % The format of the GetImageVirtualPixelMethod() method is: % % VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); return(GetPixelCacheVirtualMethod(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p r e t I m a g e F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpretImageFilename() interprets embedded characters in an image filename. % The filename length is returned. % % The format of the InterpretImageFilename method is: % % size_t InterpretImageFilename(const ImageInfo *image_info,Image *image, % const char *format,int value,char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info.. % % o image: the image. % % o format: A filename describing the format to use to write the numeric % argument. Only the first numeric format identifier is replaced. % % o value: Numeric value to substitute into format filename. % % o filename: return the formatted filename in this character buffer. % % o exception: return any errors or warnings in this structure. % */ MagickExport size_t InterpretImageFilename(const ImageInfo *image_info, Image *image,const char *format,int value,char *filename, ExceptionInfo *exception) { char *q; int c; MagickBooleanType canonical; register const char *p; ssize_t field_width, offset; canonical=MagickFalse; offset=0; (void) CopyMagickString(filename,format,MagickPathExtent); for (p=strchr(format,'%'); p != (char *) NULL; p=strchr(p+1,'%')) { q=(char *) p+1; if (*q == '%') { p=q+1; continue; } field_width=0; if (*q == '0') field_width=(ssize_t) strtol(q,&q,10); switch (*q) { case 'd': case 'o': case 'x': { q++; c=(*q); *q='\0'; (void) FormatLocaleString(filename+(p-format-offset),(size_t) (MagickPathExtent-(p-format-offset)),p,value); offset+=(4-field_width); *q=c; (void) ConcatenateMagickString(filename,q,MagickPathExtent); canonical=MagickTrue; if (*(q-1) != '%') break; p++; break; } case '[': { char pattern[MagickPathExtent]; const char *option; register char *r; register ssize_t i; ssize_t depth; /* Image option. */ if (strchr(p,']') == (char *) NULL) break; depth=1; r=q+1; for (i=0; (i < (MagickPathExtent-1L)) && (*r != '\0'); i++) { if (*r == '[') depth++; if (*r == ']') depth--; if (depth <= 0) break; pattern[i]=(*r++); } pattern[i]='\0'; if (LocaleNCompare(pattern,"filename:",9) != 0) break; option=(const char *) NULL; if (image != (Image *) NULL) option=GetImageProperty(image,pattern,exception); if ((option == (const char *) NULL) && (image != (Image *) NULL)) option=GetImageArtifact(image,pattern); if ((option == (const char *) NULL) && (image_info != (ImageInfo *) NULL)) option=GetImageOption(image_info,pattern); if (option == (const char *) NULL) break; q--; c=(*q); *q='\0'; (void) CopyMagickString(filename+(p-format-offset),option,(size_t) (MagickPathExtent-(p-format-offset))); offset+=strlen(pattern)-strlen(option)+3; *q=c; (void) ConcatenateMagickString(filename,r+1,MagickPathExtent); canonical=MagickTrue; if (*(q-1) != '%') break; p++; break; } default: break; } } if (canonical == MagickFalse) (void) CopyMagickString(filename,format,MagickPathExtent); else for (q=filename; *q != '\0'; q++) if ((*q == '%') && (*(q+1) == '%')) (void) CopyMagickString(q,q+1,(size_t) (MagickPathExtent-(q-filename))); return(strlen(filename)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s H i g h D y n a m i c R a n g e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsHighDynamicRangeImage() returns MagickTrue if any pixel component is % non-integer or exceeds the bounds of the quantum depth (e.g. for Q16 % 0..65535. % % The format of the IsHighDynamicRangeImage method is: % % MagickBooleanType IsHighDynamicRangeImage(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType IsHighDynamicRangeImage(const Image *image, ExceptionInfo *exception) { #if !defined(MAGICKCORE_HDRI_SUPPORT) (void) image; (void) exception; return(MagickFalse); #else CacheView *image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double pixel; PixelTrait traits; traits=GetPixelChannelTraits(image,(PixelChannel) i); if (traits == UndefinedPixelTrait) continue; pixel=(double) p[i]; if ((pixel < 0.0) || (pixel > QuantumRange) || (pixel != (double) ((QuantumAny) pixel))) break; } p+=GetPixelChannels(image); if (i < (ssize_t) GetPixelChannels(image)) status=MagickFalse; } if (x < (ssize_t) image->columns) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status != MagickFalse ? MagickFalse : MagickTrue); #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s I m a g e O b j e c t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsImageObject() returns MagickTrue if the image sequence contains a valid % set of image objects. % % The format of the IsImageObject method is: % % MagickBooleanType IsImageObject(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType IsImageObject(const Image *image) { register const Image *p; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) if (p->signature != MagickCoreSignature) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s T a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsTaintImage() returns MagickTrue any pixel in the image has been altered % since it was first constituted. % % The format of the IsTaintImage method is: % % MagickBooleanType IsTaintImage(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType IsTaintImage(const Image *image) { char magick[MagickPathExtent], filename[MagickPathExtent]; register const Image *p; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); (void) CopyMagickString(magick,image->magick,MagickPathExtent); (void) CopyMagickString(filename,image->filename,MagickPathExtent); for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { if (p->taint != MagickFalse) return(MagickTrue); if (LocaleCompare(p->magick,magick) != 0) return(MagickTrue); if (LocaleCompare(p->filename,filename) != 0) return(MagickTrue); } return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o d i f y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ModifyImage() ensures that there is only a single reference to the image % to be modified, updating the provided image pointer to point to a clone of % the original image if necessary. % % The format of the ModifyImage method is: % % MagickBooleanType ModifyImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ModifyImage(Image **image, ExceptionInfo *exception) { Image *clone_image; assert(image != (Image **) NULL); assert(*image != (Image *) NULL); assert((*image)->signature == MagickCoreSignature); if ((*image)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename); if (GetImageReferenceCount(*image) <= 1) return(MagickTrue); clone_image=CloneImage(*image,0,0,MagickTrue,exception); LockSemaphoreInfo((*image)->semaphore); (*image)->reference_count--; UnlockSemaphoreInfo((*image)->semaphore); *image=clone_image; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w M a g i c k I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewMagickImage() creates a blank image canvas of the specified size and % background color. % % The format of the NewMagickImage method is: % % Image *NewMagickImage(const ImageInfo *image_info,const size_t width, % const size_t height,const PixelInfo *background, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the image width. % % o height: the image height. % % o background: the image color. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *NewMagickImage(const ImageInfo *image_info, const size_t width,const size_t height,const PixelInfo *background, ExceptionInfo *exception) { CacheView *image_view; Image *image; MagickBooleanType status; ssize_t y; assert(image_info != (const ImageInfo *) NULL); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image_info->signature == MagickCoreSignature); assert(background != (const PixelInfo *) NULL); image=AcquireImage(image_info,exception); image->columns=width; image->rows=height; image->colorspace=background->colorspace; image->alpha_trait=background->alpha_trait; image->fuzz=background->fuzz; image->depth=background->depth; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelViaPixelInfo(image,background,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e f e r e n c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReferenceImage() increments the reference count associated with an image % returning a pointer to the image. % % The format of the ReferenceImage method is: % % Image *ReferenceImage(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Image *ReferenceImage(Image *image) { assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); LockSemaphoreInfo(image->semaphore); image->reference_count++; UnlockSemaphoreInfo(image->semaphore); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t I m a g e P a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImagePage() resets the image page canvas and position. % % The format of the ResetImagePage method is: % % MagickBooleanType ResetImagePage(Image *image,const char *page) % % A description of each parameter follows: % % o image: the image. % % o page: the relative page specification. % */ MagickExport MagickBooleanType ResetImagePage(Image *image,const char *page) { MagickStatusType flags; RectangleInfo geometry; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); flags=ParseAbsoluteGeometry(page,&geometry); if ((flags & WidthValue) != 0) { if ((flags & HeightValue) == 0) geometry.height=geometry.width; image->page.width=geometry.width; image->page.height=geometry.height; } if ((flags & AspectValue) != 0) { if ((flags & XValue) != 0) image->page.x+=geometry.x; if ((flags & YValue) != 0) image->page.y+=geometry.y; } else { if ((flags & XValue) != 0) { image->page.x=geometry.x; if ((image->page.width == 0) && (geometry.x > 0)) image->page.width=image->columns+geometry.x; } if ((flags & YValue) != 0) { image->page.y=geometry.y; if ((image->page.height == 0) && (geometry.y > 0)) image->page.height=image->rows+geometry.y; } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImagePixels() reset the image pixels, that is, all the pixel components % are zereod. % % The format of the SetImage method is: % % MagickBooleanType ResetImagePixels(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ResetImagePixels(Image *image, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; size_t length; ssize_t y; void *pixels; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); pixels=AcquirePixelCachePixels(image,&length,exception); if (pixels != (void *) NULL) { /* Reset in-core image pixels. */ (void) memset(pixels,0,length); return(MagickTrue); } /* Reset image pixels. */ status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { (void) memset(q,0,GetPixelChannels(image)*sizeof(Quantum)); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e A l p h a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageAlpha() sets the alpha levels of the image. % % The format of the SetImageAlpha method is: % % MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o alpha: the level of transparency: 0 is fully transparent and QuantumRange % is fully opaque. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); image->alpha_trait=BlendPixelTrait; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,q) > (QuantumRange/2)) SetPixelAlpha(image,alpha,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e B a c k g r o u n d C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageBackgroundColor() initializes the image pixels to the image % background color. The background color is defined by the background_color % member of the image structure. % % The format of the SetImage method is: % % MagickBooleanType SetImageBackgroundColor(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageBackgroundColor(Image *image, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; PixelInfo background; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if ((image->background_color.alpha_trait != UndefinedPixelTrait) && (image->alpha_trait == UndefinedPixelTrait)) (void) SetImageAlphaChannel(image,OnAlphaChannel,exception); ConformPixelInfo(image,&image->background_color,&background,exception); /* Set image background color. */ status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelViaPixelInfo(image,&background,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C h a n n e l M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageChannelMask() sets the image channel mask from the specified channel % mask. % % The format of the SetImageChannelMask method is: % % ChannelType SetImageChannelMask(Image *image, % const ChannelType channel_mask) % % A description of each parameter follows: % % o image: the image. % % o channel_mask: the channel mask. % */ MagickExport ChannelType SetImageChannelMask(Image *image, const ChannelType channel_mask) { return(SetPixelChannelMask(image,channel_mask)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageColor() set the entire image canvas to the specified color. % % The format of the SetImageColor method is: % % MagickBooleanType SetImageColor(Image *image,const PixelInfo *color, % ExeptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o background: the image color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageColor(Image *image, const PixelInfo *color,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); assert(color != (const PixelInfo *) NULL); image->colorspace=color->colorspace; image->alpha_trait=color->alpha_trait; image->fuzz=color->fuzz; image->depth=color->depth; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelViaPixelInfo(image,color,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e S t o r a g e C l a s s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageStorageClass() sets the image class: DirectClass for true color % images or PseudoClass for colormapped images. % % The format of the SetImageStorageClass method is: % % MagickBooleanType SetImageStorageClass(Image *image, % const ClassType storage_class,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o storage_class: The image class. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageStorageClass(Image *image, const ClassType storage_class,ExceptionInfo *exception) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image->storage_class=storage_class; return(SyncImagePixelCache(image,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageExtent() sets the image size (i.e. columns & rows). % % The format of the SetImageExtent method is: % % MagickBooleanType SetImageExtent(Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: The image width in pixels. % % o rows: The image height in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageExtent(Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { if ((columns == 0) || (rows == 0)) ThrowBinaryException(ImageError,"NegativeOrZeroImageSize",image->filename); image->columns=columns; image->rows=rows; if (image->depth == 0) { image->depth=8; (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageDepthNotSupported","`%s'",image->filename); } if (image->depth > (8*sizeof(MagickSizeType))) { image->depth=8*sizeof(MagickSizeType); (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageDepthNotSupported","`%s'",image->filename); } return(SyncImagePixelCache(image,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfo() initializes the 'magick' field of the ImageInfo structure. % It is set to a type of image format based on the prefix or suffix of the % filename. For example, 'ps:image' returns PS indicating a Postscript image. % JPEG is returned for this filename: 'image.jpg'. The filename prefix has % precendence over the suffix. Use an optional index enclosed in brackets % after a file name to specify a desired scene of a multi-resolution image % format like Photo CD (e.g. img0001.pcd[4]). A True (non-zero) return value % indicates success. % % The format of the SetImageInfo method is: % % MagickBooleanType SetImageInfo(ImageInfo *image_info, % const unsigned int frames,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o frames: the number of images you intend to write. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageInfo(ImageInfo *image_info, const unsigned int frames,ExceptionInfo *exception) { char component[MagickPathExtent], magic[MagickPathExtent], #if defined(MAGICKCORE_ZLIB_DELEGATE) || defined(MAGICKCORE_BZLIB_DELEGATE) path[MagickPathExtent], #endif *q; const MagicInfo *magic_info; const MagickInfo *magick_info; ExceptionInfo *sans_exception; Image *image; MagickBooleanType status; register const char *p; ssize_t count; /* Look for 'image.format' in filename. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); *component='\0'; GetPathComponent(image_info->filename,SubimagePath,component); if (*component != '\0') { /* Look for scene specification (e.g. img0001.pcd[4]). */ if (IsSceneGeometry(component,MagickFalse) == MagickFalse) { if (IsGeometry(component) != MagickFalse) (void) CloneString(&image_info->extract,component); } else { size_t first, last; (void) CloneString(&image_info->scenes,component); image_info->scene=StringToUnsignedLong(image_info->scenes); image_info->number_scenes=image_info->scene; p=image_info->scenes; for (q=(char *) image_info->scenes; *q != '\0'; p++) { while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; first=(size_t) strtol(p,&q,10); last=first; while (isspace((int) ((unsigned char) *q)) != 0) q++; if (*q == '-') last=(size_t) strtol(q+1,&q,10); if (first > last) Swap(first,last); if (first < image_info->scene) image_info->scene=first; if (last > image_info->number_scenes) image_info->number_scenes=last; p=q; } image_info->number_scenes-=image_info->scene-1; } } *component='\0'; if (*image_info->magick == '\0') GetPathComponent(image_info->filename,ExtensionPath,component); #if defined(MAGICKCORE_ZLIB_DELEGATE) if (*component != '\0') if ((LocaleCompare(component,"gz") == 0) || (LocaleCompare(component,"Z") == 0) || (LocaleCompare(component,"svgz") == 0) || (LocaleCompare(component,"wmz") == 0)) { (void) CopyMagickString(path,image_info->filename,MagickPathExtent); path[strlen(path)-strlen(component)-1]='\0'; GetPathComponent(path,ExtensionPath,component); } #endif #if defined(MAGICKCORE_BZLIB_DELEGATE) if (*component != '\0') if (LocaleCompare(component,"bz2") == 0) { (void) CopyMagickString(path,image_info->filename,MagickPathExtent); path[strlen(path)-strlen(component)-1]='\0'; GetPathComponent(path,ExtensionPath,component); } #endif image_info->affirm=MagickFalse; sans_exception=AcquireExceptionInfo(); if ((*component != '\0') && (IsGlob(component) == MagickFalse)) { MagickFormatType format_type; register ssize_t i; static const char *format_type_formats[] = { "AUTOTRACE", "BROWSE", "DCRAW", "EDIT", "LAUNCH", "MPEG:DECODE", "MPEG:ENCODE", "PRINT", "PS:ALPHA", "PS:CMYK", "PS:COLOR", "PS:GRAY", "PS:MONO", "SCAN", "SHOW", "WIN", (char *) NULL }; /* User specified image format. */ (void) CopyMagickString(magic,component,MagickPathExtent); LocaleUpper(magic); /* Look for explicit image formats. */ format_type=UndefinedFormatType; magick_info=GetMagickInfo(magic,sans_exception); if ((magick_info != (const MagickInfo *) NULL) && (magick_info->format_type != UndefinedFormatType)) format_type=magick_info->format_type; i=0; while ((format_type == UndefinedFormatType) && (format_type_formats[i] != (char *) NULL)) { if ((*magic == *format_type_formats[i]) && (LocaleCompare(magic,format_type_formats[i]) == 0)) format_type=ExplicitFormatType; i++; } if (format_type == UndefinedFormatType) (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); else if (format_type == ExplicitFormatType) { image_info->affirm=MagickTrue; (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); } if (LocaleCompare(magic,"RGB") == 0) image_info->affirm=MagickFalse; /* maybe SGI disguised as RGB */ } /* Look for explicit 'format:image' in filename. */ *magic='\0'; GetPathComponent(image_info->filename,MagickPath,magic); if (*magic == '\0') { (void) CopyMagickString(magic,image_info->magick,MagickPathExtent); magick_info=GetMagickInfo(magic,sans_exception); if (frames == 0) GetPathComponent(image_info->filename,CanonicalPath,component); else GetPathComponent(image_info->filename,SubcanonicalPath,component); (void) CopyMagickString(image_info->filename,component,MagickPathExtent); } else { const DelegateInfo *delegate_info; /* User specified image format. */ LocaleUpper(magic); magick_info=GetMagickInfo(magic,sans_exception); delegate_info=GetDelegateInfo(magic,"*",sans_exception); if (delegate_info == (const DelegateInfo *) NULL) delegate_info=GetDelegateInfo("*",magic,sans_exception); if (((magick_info != (const MagickInfo *) NULL) || (delegate_info != (const DelegateInfo *) NULL)) && (IsMagickConflict(magic) == MagickFalse)) { image_info->affirm=MagickTrue; (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); GetPathComponent(image_info->filename,CanonicalPath,component); (void) CopyMagickString(image_info->filename,component, MagickPathExtent); } } sans_exception=DestroyExceptionInfo(sans_exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; if ((image_info->adjoin != MagickFalse) && (frames > 1)) { /* Test for multiple image support (e.g. image%02d.png). */ (void) InterpretImageFilename(image_info,(Image *) NULL, image_info->filename,(int) image_info->scene,component,exception); if ((LocaleCompare(component,image_info->filename) != 0) && (strchr(component,'%') == (char *) NULL)) image_info->adjoin=MagickFalse; } if ((image_info->adjoin != MagickFalse) && (frames > 0)) { /* Some image formats do not support multiple frames per file. */ magick_info=GetMagickInfo(magic,exception); if (magick_info != (const MagickInfo *) NULL) if (GetMagickAdjoin(magick_info) == MagickFalse) image_info->adjoin=MagickFalse; } if (image_info->affirm != MagickFalse) return(MagickTrue); if (frames == 0) { unsigned char *magick; size_t magick_size; /* Determine the image format from the first few bytes of the file. */ magick_size=GetMagicPatternExtent(exception); if (magick_size == 0) return(MagickFalse); image=AcquireImage(image_info,exception); (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } if ((IsBlobSeekable(image) == MagickFalse) || (IsBlobExempt(image) != MagickFalse)) { /* Copy image to seekable temporary file. */ *component='\0'; status=ImageToFile(image,component,exception); (void) CloseBlob(image); if (status == MagickFalse) { (void) RelinquishUniqueFileResource(component); image=DestroyImage(image); return(MagickFalse); } SetImageInfoFile(image_info,(FILE *) NULL); (void) CopyMagickString(image->filename,component,MagickPathExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { (void) RelinquishUniqueFileResource(component); image=DestroyImage(image); return(MagickFalse); } (void) CopyMagickString(image_info->filename,component, MagickPathExtent); image_info->temporary=MagickTrue; } magick=(unsigned char *) AcquireMagickMemory(magick_size); if (magick == (unsigned char *) NULL) { (void) CloseBlob(image); image=DestroyImage(image); return(MagickFalse); } (void) memset(magick,0,magick_size); count=ReadBlob(image,magick_size,magick); (void) SeekBlob(image,-((MagickOffsetType) count),SEEK_CUR); (void) CloseBlob(image); image=DestroyImage(image); /* Check magic cache. */ sans_exception=AcquireExceptionInfo(); magic_info=GetMagicInfo(magick,(size_t) count,sans_exception); magick=(unsigned char *) RelinquishMagickMemory(magick); if ((magic_info != (const MagicInfo *) NULL) && (GetMagicName(magic_info) != (char *) NULL)) { /* Try to use magick_info that was determined earlier by the extension */ if ((magick_info != (const MagickInfo *) NULL) && (GetMagickUseExtension(magick_info) != MagickFalse) && (LocaleCompare(magick_info->magick_module,GetMagicName( magic_info)) == 0)) (void) CopyMagickString(image_info->magick,magick_info->name, MagickPathExtent); else { (void) CopyMagickString(image_info->magick,GetMagicName( magic_info),MagickPathExtent); magick_info=GetMagickInfo(image_info->magick,sans_exception); } if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; sans_exception=DestroyExceptionInfo(sans_exception); return(MagickTrue); } magick_info=GetMagickInfo(image_info->magick,sans_exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; sans_exception=DestroyExceptionInfo(sans_exception); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o B l o b % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoBlob() sets the image info blob member. % % The format of the SetImageInfoBlob method is: % % void SetImageInfoBlob(ImageInfo *image_info,const void *blob, % const size_t length) % % A description of each parameter follows: % % o image_info: the image info. % % o blob: the blob. % % o length: the blob length. % */ MagickExport void SetImageInfoBlob(ImageInfo *image_info,const void *blob, const size_t length) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->blob=(void *) blob; image_info->length=length; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o C u s t o m S t r e a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoCustomStream() sets the image info custom stream handlers. % % The format of the SetImageInfoCustomStream method is: % % void SetImageInfoCustomStream(ImageInfo *image_info, % CustomStreamInfo *custom_stream) % % A description of each parameter follows: % % o image_info: the image info. % % o custom_stream: your custom stream methods. % */ MagickExport void SetImageInfoCustomStream(ImageInfo *image_info, CustomStreamInfo *custom_stream) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->custom_stream=(CustomStreamInfo *) custom_stream; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoFile() sets the image info file member. % % The format of the SetImageInfoFile method is: % % void SetImageInfoFile(ImageInfo *image_info,FILE *file) % % A description of each parameter follows: % % o image_info: the image info. % % o file: the file. % */ MagickExport void SetImageInfoFile(ImageInfo *image_info,FILE *file) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->file=file; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageMask() associates a mask with the image. The mask must be the same % dimensions as the image. % % The format of the SetImageMask method is: % % MagickBooleanType SetImageMask(Image *image,const PixelMask type, % const Image *mask,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % % o mask: the image mask. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageMask(Image *image,const PixelMask type, const Image *mask,ExceptionInfo *exception) { CacheView *mask_view, *image_view; MagickBooleanType status; ssize_t y; /* Set image mask. */ assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (mask == (const Image *) NULL) { switch (type) { case ReadPixelMask: { image->channels=(ChannelType) (image->channels & ~ReadMaskChannel); break; } case WritePixelMask: { image->channels=(ChannelType) (image->channels & ~WriteMaskChannel); } default: { image->channels=(ChannelType) (image->channels & ~CompositeMaskChannel); break; } } return(SyncImagePixelCache(image,exception)); } switch (type) { case ReadPixelMask: { image->channels=(ChannelType) (image->channels | ReadMaskChannel); break; } case WritePixelMask: { image->channels=(ChannelType) (image->channels | WriteMaskChannel); break; } default: { image->channels=(ChannelType) (image->channels | CompositeMaskChannel); break; } } if (SyncImagePixelCache(image,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; image->mask_trait=UpdatePixelTrait; mask_view=AcquireVirtualCacheView(mask,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(mask,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(mask_view,0,y,mask->columns,1,exception); q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType intensity; intensity=0.0; if ((x < (ssize_t) mask->columns) && (y < (ssize_t) mask->rows)) intensity=GetPixelIntensity(mask,p); switch (type) { case ReadPixelMask: { SetPixelReadMask(image,ClampToQuantum(intensity),q); break; } case WritePixelMask: { SetPixelWriteMask(image,ClampToQuantum(intensity),q); break; } default: { SetPixelCompositeMask(image,ClampToQuantum(intensity),q); break; } } p+=GetPixelChannels(mask); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image->mask_trait=UndefinedPixelTrait; mask_view=DestroyCacheView(mask_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e R e g i o n M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageRegionMask() associates a mask with the image as defined by the % specified region. % % The format of the SetImageRegionMask method is: % % MagickBooleanType SetImageRegionMask(Image *image,const PixelMask type, % const RectangleInfo *region,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % % o geometry: the mask region. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageRegionMask(Image *image, const PixelMask type,const RectangleInfo *region,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; /* Set image mask as defined by the region. */ assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (region == (const RectangleInfo *) NULL) { switch (type) { case ReadPixelMask: { image->channels=(ChannelType) (image->channels & ~ReadMaskChannel); break; } case WritePixelMask: { image->channels=(ChannelType) (image->channels & ~WriteMaskChannel); break; } default: { image->channels=(ChannelType) (image->channels & ~CompositeMaskChannel); break; } } return(SyncImagePixelCache(image,exception)); } switch (type) { case ReadPixelMask: { image->channels=(ChannelType) (image->channels | ReadMaskChannel); break; } case WritePixelMask: { image->channels=(ChannelType) (image->channels | WriteMaskChannel); break; } default: { image->channels=(ChannelType) (image->channels | CompositeMaskChannel); break; } } if (SyncImagePixelCache(image,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; image->mask_trait=UpdatePixelTrait; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { Quantum pixel; pixel=QuantumRange; if (((x >= region->x) && (x < (region->x+(ssize_t) region->width))) && ((y >= region->y) && (y < (region->y+(ssize_t) region->height)))) pixel=(Quantum) 0; switch (type) { case ReadPixelMask: { SetPixelReadMask(image,pixel,q); break; } case WritePixelMask: { SetPixelWriteMask(image,pixel,q); break; } default: { SetPixelCompositeMask(image,pixel,q); break; } } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image->mask_trait=UndefinedPixelTrait; image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e V i r t u a l P i x e l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageVirtualPixelMethod() sets the "virtual pixels" method for the % image and returns the previous setting. A virtual pixel is any pixel access % that is outside the boundaries of the image cache. % % The format of the SetImageVirtualPixelMethod() method is: % % VirtualPixelMethod SetImageVirtualPixelMethod(Image *image, % const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: choose the type of virtual pixel. % % o exception: return any errors or warnings in this structure. % */ MagickExport VirtualPixelMethod SetImageVirtualPixelMethod(Image *image, const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) { assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); return(SetPixelCacheVirtualMethod(image,virtual_pixel_method,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S m u s h I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SmushImages() takes all images from the current image pointer to the end % of the image list and smushes them to each other top-to-bottom if the % stack parameter is true, otherwise left-to-right. % % The current gravity setting now effects how the image is justified in the % final image. % % The format of the SmushImages method is: % % Image *SmushImages(const Image *images,const MagickBooleanType stack, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o stack: A value other than 0 stacks the images top-to-bottom. % % o offset: minimum distance in pixels between images. % % o exception: return any errors or warnings in this structure. % */ static ssize_t SmushXGap(const Image *smush_image,const Image *images, const ssize_t offset,ExceptionInfo *exception) { CacheView *left_view, *right_view; const Image *left_image, *right_image; RectangleInfo left_geometry, right_geometry; register const Quantum *p; register ssize_t i, y; size_t gap; ssize_t x; if (images->previous == (Image *) NULL) return(0); right_image=images; SetGeometry(smush_image,&right_geometry); GravityAdjustGeometry(right_image->columns,right_image->rows, right_image->gravity,&right_geometry); left_image=images->previous; SetGeometry(smush_image,&left_geometry); GravityAdjustGeometry(left_image->columns,left_image->rows, left_image->gravity,&left_geometry); gap=right_image->columns; left_view=AcquireVirtualCacheView(left_image,exception); right_view=AcquireVirtualCacheView(right_image,exception); for (y=0; y < (ssize_t) smush_image->rows; y++) { for (x=(ssize_t) left_image->columns-1; x > 0; x--) { p=GetCacheViewVirtualPixels(left_view,x,left_geometry.y+y,1,1,exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(left_image,p) != TransparentAlpha) || ((left_image->columns-x-1) >= gap)) break; } i=(ssize_t) left_image->columns-x-1; for (x=0; x < (ssize_t) right_image->columns; x++) { p=GetCacheViewVirtualPixels(right_view,x,right_geometry.y+y,1,1, exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(right_image,p) != TransparentAlpha) || ((x+i) >= (ssize_t) gap)) break; } if ((x+i) < (ssize_t) gap) gap=(size_t) (x+i); } right_view=DestroyCacheView(right_view); left_view=DestroyCacheView(left_view); if (y < (ssize_t) smush_image->rows) return(offset); return((ssize_t) gap-offset); } static ssize_t SmushYGap(const Image *smush_image,const Image *images, const ssize_t offset,ExceptionInfo *exception) { CacheView *bottom_view, *top_view; const Image *bottom_image, *top_image; RectangleInfo bottom_geometry, top_geometry; register const Quantum *p; register ssize_t i, x; size_t gap; ssize_t y; if (images->previous == (Image *) NULL) return(0); bottom_image=images; SetGeometry(smush_image,&bottom_geometry); GravityAdjustGeometry(bottom_image->columns,bottom_image->rows, bottom_image->gravity,&bottom_geometry); top_image=images->previous; SetGeometry(smush_image,&top_geometry); GravityAdjustGeometry(top_image->columns,top_image->rows,top_image->gravity, &top_geometry); gap=bottom_image->rows; top_view=AcquireVirtualCacheView(top_image,exception); bottom_view=AcquireVirtualCacheView(bottom_image,exception); for (x=0; x < (ssize_t) smush_image->columns; x++) { for (y=(ssize_t) top_image->rows-1; y > 0; y--) { p=GetCacheViewVirtualPixels(top_view,top_geometry.x+x,y,1,1,exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(top_image,p) != TransparentAlpha) || ((top_image->rows-y-1) >= gap)) break; } i=(ssize_t) top_image->rows-y-1; for (y=0; y < (ssize_t) bottom_image->rows; y++) { p=GetCacheViewVirtualPixels(bottom_view,bottom_geometry.x+x,y,1,1, exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(bottom_image,p) != TransparentAlpha) || ((y+i) >= (ssize_t) gap)) break; } if ((y+i) < (ssize_t) gap) gap=(size_t) (y+i); } bottom_view=DestroyCacheView(bottom_view); top_view=DestroyCacheView(top_view); if (x < (ssize_t) smush_image->columns) return(offset); return((ssize_t) gap-offset); } MagickExport Image *SmushImages(const Image *images, const MagickBooleanType stack,const ssize_t offset,ExceptionInfo *exception) { #define SmushImageTag "Smush/Image" const Image *image; Image *smush_image; MagickBooleanType proceed, status; MagickOffsetType n; PixelTrait alpha_trait; RectangleInfo geometry; register const Image *next; size_t height, number_images, width; ssize_t x_offset, y_offset; /* Compute maximum area of smushed area. */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=images; alpha_trait=image->alpha_trait; number_images=1; width=image->columns; height=image->rows; next=GetNextImageInList(image); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (next->alpha_trait != UndefinedPixelTrait) alpha_trait=BlendPixelTrait; number_images++; if (stack != MagickFalse) { if (next->columns > width) width=next->columns; height+=next->rows; if (next->previous != (Image *) NULL) height+=offset; continue; } width+=next->columns; if (next->previous != (Image *) NULL) width+=offset; if (next->rows > height) height=next->rows; } /* Smush images. */ smush_image=CloneImage(image,width,height,MagickTrue,exception); if (smush_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(smush_image,DirectClass,exception) == MagickFalse) { smush_image=DestroyImage(smush_image); return((Image *) NULL); } smush_image->alpha_trait=alpha_trait; (void) SetImageBackgroundColor(smush_image,exception); status=MagickTrue; x_offset=0; y_offset=0; for (n=0; n < (MagickOffsetType) number_images; n++) { SetGeometry(smush_image,&geometry); GravityAdjustGeometry(image->columns,image->rows,image->gravity,&geometry); if (stack != MagickFalse) { x_offset-=geometry.x; y_offset-=SmushYGap(smush_image,image,offset,exception); } else { x_offset-=SmushXGap(smush_image,image,offset,exception); y_offset-=geometry.y; } status=CompositeImage(smush_image,image,OverCompositeOp,MagickTrue,x_offset, y_offset,exception); proceed=SetImageProgress(image,SmushImageTag,n,number_images); if (proceed == MagickFalse) break; if (stack == MagickFalse) { x_offset+=(ssize_t) image->columns; y_offset=0; } else { x_offset=0; y_offset+=(ssize_t) image->rows; } image=GetNextImageInList(image); } if (stack == MagickFalse) smush_image->columns=(size_t) x_offset; else smush_image->rows=(size_t) y_offset; if (status == MagickFalse) smush_image=DestroyImage(smush_image); return(smush_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t r i p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StripImage() strips an image of all profiles and comments. % % The format of the StripImage method is: % % MagickBooleanType StripImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType StripImage(Image *image,ExceptionInfo *exception) { MagickBooleanType status; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); (void) exception; DestroyImageProfiles(image); (void) DeleteImageProperty(image,"comment"); (void) DeleteImageProperty(image,"date:create"); (void) DeleteImageProperty(image,"date:modify"); status=SetImageArtifact(image,"png:exclude-chunk", "bKGD,caNv,cHRM,eXIf,gAMA,iCCP,iTXt,pHYs,sRGB,tEXt,zCCP,zTXt,date"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImage() initializes the red, green, and blue intensities of each pixel % as defined by the colormap index. % % The format of the SyncImage method is: % % MagickBooleanType SyncImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline Quantum PushColormapIndex(Image *image,const Quantum index, MagickBooleanType *range_exception) { if ((size_t) index < image->colors) return(index); *range_exception=MagickTrue; return((Quantum) 0); } MagickExport MagickBooleanType SyncImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType range_exception, status, taint; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (image->ping != MagickFalse) return(MagickTrue); if (image->storage_class != PseudoClass) return(MagickFalse); assert(image->colormap != (PixelInfo *) NULL); range_exception=MagickFalse; status=MagickTrue; taint=image->taint; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(range_exception,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum index; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { index=PushColormapIndex(image,GetPixelIndex(image,q),&range_exception); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); image->taint=taint; if ((image->ping == MagickFalse) && (range_exception != MagickFalse)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"InvalidColormapIndex","`%s'",image->filename); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c I m a g e S e t t i n g s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImageSettings() syncs any image_info global options into per-image % attributes. % % Note: in IMv6 free form 'options' were always mapped into 'artifacts', so % that operations and coders can find such settings. In IMv7 if a desired % per-image artifact is not set, then it will directly look for a global % option as a fallback, as such this copy is no longer needed, only the % link set up. % % The format of the SyncImageSettings method is: % % MagickBooleanType SyncImageSettings(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % MagickBooleanType SyncImagesSettings(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SyncImagesSettings(ImageInfo *image_info, Image *images,ExceptionInfo *exception) { Image *image; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); image=images; for ( ; image != (Image *) NULL; image=GetNextImageInList(image)) (void) SyncImageSettings(image_info,image,exception); (void) DeleteImageOption(image_info,"page"); return(MagickTrue); } MagickExport MagickBooleanType SyncImageSettings(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *option; GeometryInfo geometry_info; MagickStatusType flags; ResolutionType units; /* Sync image options. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); option=GetImageOption(image_info,"background"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->background_color, exception); option=GetImageOption(image_info,"black-point-compensation"); if (option != (const char *) NULL) image->black_point_compensation=(MagickBooleanType) ParseCommandOption( MagickBooleanOptions,MagickFalse,option); option=GetImageOption(image_info,"blue-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y=image->chromaticity.blue_primary.x; } option=GetImageOption(image_info,"bordercolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->border_color, exception); /* FUTURE: do not sync compose to per-image compose setting here */ option=GetImageOption(image_info,"compose"); if (option != (const char *) NULL) image->compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions, MagickFalse,option); /* -- */ option=GetImageOption(image_info,"compress"); if (option != (const char *) NULL) image->compression=(CompressionType) ParseCommandOption( MagickCompressOptions,MagickFalse,option); option=GetImageOption(image_info,"debug"); if (option != (const char *) NULL) image->debug=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions, MagickFalse,option); option=GetImageOption(image_info,"density"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } option=GetImageOption(image_info,"depth"); if (option != (const char *) NULL) image->depth=StringToUnsignedLong(option); option=GetImageOption(image_info,"endian"); if (option != (const char *) NULL) image->endian=(EndianType) ParseCommandOption(MagickEndianOptions, MagickFalse,option); option=GetImageOption(image_info,"filter"); if (option != (const char *) NULL) image->filter=(FilterType) ParseCommandOption(MagickFilterOptions, MagickFalse,option); option=GetImageOption(image_info,"fuzz"); if (option != (const char *) NULL) image->fuzz=StringToDoubleInterval(option,(double) QuantumRange+1.0); option=GetImageOption(image_info,"gravity"); if (option != (const char *) NULL) image->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,option); option=GetImageOption(image_info,"green-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y=image->chromaticity.green_primary.x; } option=GetImageOption(image_info,"intent"); if (option != (const char *) NULL) image->rendering_intent=(RenderingIntent) ParseCommandOption( MagickIntentOptions,MagickFalse,option); option=GetImageOption(image_info,"intensity"); if (option != (const char *) NULL) image->intensity=(PixelIntensityMethod) ParseCommandOption( MagickPixelIntensityOptions,MagickFalse,option); option=GetImageOption(image_info,"interlace"); if (option != (const char *) NULL) image->interlace=(InterlaceType) ParseCommandOption(MagickInterlaceOptions, MagickFalse,option); option=GetImageOption(image_info,"interpolate"); if (option != (const char *) NULL) image->interpolate=(PixelInterpolateMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,option); option=GetImageOption(image_info,"loop"); if (option != (const char *) NULL) image->iterations=StringToUnsignedLong(option); option=GetImageOption(image_info,"mattecolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->matte_color, exception); option=GetImageOption(image_info,"orient"); if (option != (const char *) NULL) image->orientation=(OrientationType) ParseCommandOption( MagickOrientationOptions,MagickFalse,option); option=GetImageOption(image_info,"page"); if (option != (const char *) NULL) { char *geometry; geometry=GetPageGeometry(option); flags=ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); } option=GetImageOption(image_info,"quality"); if (option != (const char *) NULL) image->quality=StringToUnsignedLong(option); option=GetImageOption(image_info,"red-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; image->chromaticity.red_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.red_primary.y=image->chromaticity.red_primary.x; } if (image_info->quality != UndefinedCompressionQuality) image->quality=image_info->quality; option=GetImageOption(image_info,"scene"); if (option != (const char *) NULL) image->scene=StringToUnsignedLong(option); option=GetImageOption(image_info,"taint"); if (option != (const char *) NULL) image->taint=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions, MagickFalse,option); option=GetImageOption(image_info,"tile-offset"); if (option != (const char *) NULL) { char *geometry; geometry=GetPageGeometry(option); flags=ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } option=GetImageOption(image_info,"transparent-color"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->transparent_color, exception); option=GetImageOption(image_info,"type"); if (option != (const char *) NULL) image->type=(ImageType) ParseCommandOption(MagickTypeOptions,MagickFalse, option); option=GetImageOption(image_info,"units"); units=image_info->units; if (option != (const char *) NULL) units=(ResolutionType) ParseCommandOption(MagickResolutionOptions, MagickFalse,option); if (units != UndefinedResolution) { if (image->units != units) switch (image->units) { case PixelsPerInchResolution: { if (units == PixelsPerCentimeterResolution) { image->resolution.x/=2.54; image->resolution.y/=2.54; } break; } case PixelsPerCentimeterResolution: { if (units == PixelsPerInchResolution) { image->resolution.x=(double) ((size_t) (100.0*2.54* image->resolution.x+0.5))/100.0; image->resolution.y=(double) ((size_t) (100.0*2.54* image->resolution.y+0.5))/100.0; } break; } default: break; } image->units=units; option=GetImageOption(image_info,"density"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } } option=GetImageOption(image_info,"virtual-pixel"); if (option != (const char *) NULL) (void) SetImageVirtualPixelMethod(image,(VirtualPixelMethod) ParseCommandOption(MagickVirtualPixelOptions,MagickFalse,option), exception); option=GetImageOption(image_info,"white-point"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y=image->chromaticity.white_point.x; } /* Pointer to allow the lookup of pre-image artifact will fallback to a global option setting/define. This saves a lot of duplication of global options into per-image artifacts, while ensuring only specifically set per-image artifacts are preserved when parenthesis ends. */ if (image->image_info != (ImageInfo *) NULL) image->image_info=DestroyImageInfo(image->image_info); image->image_info=CloneImageInfo(image_info); return(MagickTrue); }
GB_binop__min_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__min_int32) // A.*B function (eWiseMult): GB (_AemultB_08__min_int32) // A.*B function (eWiseMult): GB (_AemultB_02__min_int32) // A.*B function (eWiseMult): GB (_AemultB_04__min_int32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__min_int32) // A*D function (colscale): GB (_AxD__min_int32) // D*A function (rowscale): GB (_DxB__min_int32) // C+=B function (dense accum): GB (_Cdense_accumB__min_int32) // C+=b function (dense accum): GB (_Cdense_accumb__min_int32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__min_int32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__min_int32) // C=scalar+B GB (_bind1st__min_int32) // C=scalar+B' GB (_bind1st_tran__min_int32) // C=A+scalar GB (_bind2nd__min_int32) // C=A'+scalar GB (_bind2nd_tran__min_int32) // C type: int32_t // A type: int32_t // B,b type: int32_t // BinaryOp: cij = GB_IMIN (aij, bij) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ int32_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) \ 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) \ int32_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 = GB_IMIN (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_MIN || GxB_NO_INT32 || GxB_NO_MIN_INT32) //------------------------------------------------------------------------------ // 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__min_int32) ( 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__min_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__min_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 { #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__min_int32) ( 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 int32_t int32_t bwork = (*((int32_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__min_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 int32_t *restrict Cx = (int32_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__min_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 int32_t *restrict Cx = (int32_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__min_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__min_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__min_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__min_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__min_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__min_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 int32_t *Cx = (int32_t *) 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] = GB_IMIN (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__min_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 ; int32_t *Cx = (int32_t *) 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] = GB_IMIN (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] = GB_IMIN (x, aij) ; \ } GrB_Info GB (_bind1st_tran__min_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] = GB_IMIN (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__min_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
prepress.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP RRRR EEEEE PPPP RRRR EEEEE SSSSS SSSSS % % P P R R E P P R R E SS SS % % PPPP RRRR EEE PPPP RRRR EEE SSS SSS % % P R R E P R R E SS SS % % P R R EEEEE P R R EEEEE SSSSS SSSSS % % % % % % MagickCore Prepress Methods % % % % Software Design % % Cristy % % October 2001 % % % % % % Copyright 1999-2018 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://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 "MagickCore/studio.h" #include "MagickCore/cache-view.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/linked-list.h" #include "MagickCore/list.h" #include "MagickCore/memory_.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/prepress.h" #include "MagickCore/resource_.h" #include "MagickCore/registry.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e T o t a l I n k D e n s i t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageTotalInkDensity() returns the total ink density for a CMYK image. % Total Ink Density (TID) is determined by adding the CMYK values in the % darkest shadow area in an image. % % The format of the GetImageTotalInkDensity method is: % % double GetImageTotalInkDensity(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport double GetImageTotalInkDensity(Image *image, ExceptionInfo *exception) { CacheView *image_view; double total_ink_density; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (image->colorspace != CMYKColorspace) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ColorSeparatedImageRequired","`%s'",image->filename); return(0.0); } status=MagickTrue; total_ink_density=0.0; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double density; register const Quantum *p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { density=(double) GetPixelRed(image,p)+GetPixelGreen(image,p)+ GetPixelBlue(image,p)+GetPixelBlack(image,p); if (density > total_ink_density) #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetImageTotalInkDensity) #endif { if (density > total_ink_density) total_ink_density=density; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) total_ink_density=0.0; return(total_ink_density); }
SubTVec.h
#ifndef KRIPKE_SUBTVEC_H__ #define KRIPKE_SUBTVEC_H__ #include <Kripke/Kernel.h> #include <algorithm> #include <vector> #include <stdlib.h> /** * A transport vector (used for Psi and Phi, RHS, etc.) * * This provides the inner most three strides of * Psi[GS][DS][G][D][Z] * but in whatever nesting order is specified. */ struct SubTVec { SubTVec(Nesting_Order nesting, int ngrps, int ndir_mom, int nzones): groups(ngrps), directions(ndir_mom), zones(nzones), elements(groups*directions*zones), data_linear(elements) { setupIndices(nesting, &data_linear[0]); } /** * ALIASING version of constructor. * Use this when you have a data buffer already, and don't want this class * to do any memory management. */ SubTVec(Nesting_Order nesting, int ngrps, int ndir_mom, int nzones, double *ptr): groups(ngrps), directions(ndir_mom), zones(nzones), elements(groups*directions*zones), data_linear(0) { setupIndices(nesting, ptr); } ~SubTVec(){ } void setupIndices(Nesting_Order nesting, double *ptr){ // setup nesting order switch(nesting){ case NEST_GDZ: ext_to_int[0] = 0; ext_to_int[1] = 1; ext_to_int[2] = 2; break; case NEST_GZD: ext_to_int[0] = 0; ext_to_int[2] = 1; ext_to_int[1] = 2; break; case NEST_DZG: ext_to_int[1] = 0; ext_to_int[2] = 1; ext_to_int[0] = 2; break; case NEST_DGZ: ext_to_int[1] = 0; ext_to_int[0] = 1; ext_to_int[2] = 2; break; case NEST_ZDG: ext_to_int[2] = 0; ext_to_int[1] = 1; ext_to_int[0] = 2; break; case NEST_ZGD: ext_to_int[2] = 0; ext_to_int[0] = 1; ext_to_int[1] = 2; break; } // setup dimensionality int size_ext[3]; size_ext[0] = groups; size_ext[1] = directions; size_ext[2] = zones; // map to internal indices for(int i = 0; i < 3; ++i){ size_int[ext_to_int[i]] = size_ext[i]; } data_pointer = ptr; } inline double* ptr(void){ return data_pointer; } inline double* ptr(int g, int d, int z){ return &(*this)(g,d,z); } // These are NOT efficient.. just used to re-stride data for comparisons inline double &operator()(int g, int d, int z) { int idx[3]; idx[ext_to_int[0]] = g; idx[ext_to_int[1]] = d; idx[ext_to_int[2]] = z; int offset = idx[0] * size_int[1]*size_int[2] + idx[1] * size_int[2] + idx[2]; return data_pointer[offset]; } inline double operator()(int g, int d, int z) const { return (*const_cast<SubTVec*>(this))(g,d,z); } inline double sum(void) const { double s = 0.0; for(size_t i = 0;i < elements;++ i){ s+= data_linear[i]; } return s; } inline void clear(double v){ #ifdef KRIPKE_USE_OPENMP #pragma omp parallel for #endif for(int i = 0;i < elements;++ i){ data_linear[i] = v; } } inline void randomizeData(void){ for(int i = 0;i < elements;++ i){ data_linear[i] = drand48(); } } inline void copy(SubTVec const &b){ for(int g = 0;g < groups;++ g){ for(int d = 0;d < directions; ++ d){ for(int z = 0;z < zones;++ z){ // Copy using abstract indexing (*this)(g,d,z) = b(g,d,z); } } } } inline bool compare(std::string const &name, SubTVec const &b, double tol, bool verbose){ bool is_diff = false; int num_wrong = 0; for(int g = 0;g < groups;++ g){ for(int d = 0;d < directions; ++ d){ for(int z = 0;z < zones;++ z){ // Copy using abstract indexing double err = std::abs((*this)(g,d,z) - b(g,d,z)); if(err > tol){ is_diff = true; if(verbose){ printf("%s[g=%d, d=%d, z=%d]: |%e - %e| = %e\n", name.c_str(), g,d,z, (*this)(g,d,z), b(g,d,z), err); num_wrong ++; if(num_wrong > 100){ return true; } } } } } } return is_diff; } int ext_to_int[3]; // external index to internal index mapping int size_int[3]; // size of each dimension in internal indices int groups, directions, zones, elements; double *data_pointer; std::vector<double> data_linear; }; #endif
GB_binop__le_fp32.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_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__le_fp32 // A.*B function (eWiseMult): GB_AemultB__le_fp32 // A*D function (colscale): GB_AxD__le_fp32 // D*A function (rowscale): GB_DxB__le_fp32 // C+=B function (dense accum): GB_Cdense_accumB__le_fp32 // C+=b function (dense accum): GB_Cdense_accumb__le_fp32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__le_fp32 // C=scalar+B GB_bind1st__le_fp32 // C=scalar+B' GB_bind1st_tran__le_fp32 // C=A+scalar GB_bind2nd__le_fp32 // C=A'+scalar GB_bind2nd_tran__le_fp32 // C type: bool // A type: float // B,b type: float // BinaryOp: cij = (aij <= bij) #define GB_ATYPE \ float #define GB_BTYPE \ float #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) \ float aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ float 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 <= 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_LE || GxB_NO_FP32 || GxB_NO_LE_FP32) //------------------------------------------------------------------------------ // 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__le_fp32 ( 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__le_fp32 ( 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__le_fp32 ( 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 float float bwork = (*((float *) 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__le_fp32 ( 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__le_fp32 ( 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 //------------------------------------------------------------------------------ #undef GB_FREE_ALL #define GB_FREE_ALL \ { \ GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \ GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \ GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \ } GrB_Info GB_AaddB__le_fp32 ( 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 *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 C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_add_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__le_fp32 ( 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 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 C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_emult_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__le_fp32 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *GB_RESTRICT Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; float x = (*((float *) x_input)) ; float *Bx = (float *) 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 ; float 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__le_fp32 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *GB_RESTRICT Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; float *Ax = (float *) Ax_input ; float y = (*((float *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; float 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 typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = Ax [pA] ; \ Cx [pC] = (x <= aij) ; \ } GrB_Info GB_bind1st_tran__le_fp32 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_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 \ float #if GB_DISABLE return (GrB_NO_VALUE) ; #else float x = (*((const float *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ float } //------------------------------------------------------------------------------ // 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) \ { \ float aij = Ax [pA] ; \ Cx [pC] = (aij <= y) ; \ } GrB_Info GB_bind2nd_tran__le_fp32 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float y = (*((const float *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
openmp_wrapper.h
/*! * Copyright (c) 2017 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_OPENMP_WRAPPER_H_ #define LIGHTGBM_OPENMP_WRAPPER_H_ #ifdef _OPENMP #include <LightGBM/utils/log.h> #include <omp.h> #include <exception> #include <memory> #include <mutex> #include <stdexcept> #include <vector> inline int OMP_NUM_THREADS() { int ret = 1; #pragma omp parallel #pragma omp master { ret = omp_get_num_threads(); } return ret; } class ThreadExceptionHelper { public: ThreadExceptionHelper() { ex_ptr_ = nullptr; } ~ThreadExceptionHelper() { ReThrow(); } void ReThrow() { if (ex_ptr_ != nullptr) { std::rethrow_exception(ex_ptr_); } } void CaptureException() { // only catch first exception. if (ex_ptr_ != nullptr) { return; } std::unique_lock<std::mutex> guard(lock_); if (ex_ptr_ != nullptr) { return; } ex_ptr_ = std::current_exception(); } private: std::exception_ptr ex_ptr_; std::mutex lock_; }; #define OMP_INIT_EX() ThreadExceptionHelper omp_except_helper #define OMP_LOOP_EX_BEGIN() try { #define OMP_LOOP_EX_END() \ } \ catch (std::exception & ex) { \ Log::Warning(ex.what()); \ omp_except_helper.CaptureException(); \ } \ catch (...) { \ omp_except_helper.CaptureException(); \ } #define OMP_THROW_EX() omp_except_helper.ReThrow() #else #ifdef _MSC_VER #pragma warning(disable : 4068) // disable unknown pragma warning #endif #ifdef __cplusplus extern "C" { #endif /** Fall here if no OPENMP support, so just simulate a single thread running. All #pragma omp should be ignored by the compiler **/ inline void omp_set_num_threads(int) {} inline int omp_get_num_threads() {return 1;} inline int omp_get_max_threads() {return 1;} inline int omp_get_thread_num() {return 0;} inline int OMP_NUM_THREADS() { return 1; } #ifdef __cplusplus } // extern "C" #endif #define OMP_INIT_EX() #define OMP_LOOP_EX_BEGIN() #define OMP_LOOP_EX_END() #define OMP_THROW_EX() #endif #endif /* LIGHTGBM_OPENMP_WRAPPER_H_ */
GB_unop__minv_fp64_fp64.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 Generated/ folder, do not edit it (auto-generated). #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__minv_fp64_fp64) // op(A') function: GB (_unop_tran__minv_fp64_fp64) // C type: double // A type: double // cast: double cij = aij // unaryop: cij = 1./aij #define GB_ATYPE \ double #define GB_CTYPE \ double // 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 = 1./x ; // casting #define GB_CAST(z, aij) \ double z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ double aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ double z = aij ; \ Cx [pC] = 1./z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__minv_fp64_fp64) ( double *Cx, // Cx and Ax may be aliased const double *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 ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (double), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double aij = Ax [p] ; double z = aij ; Cx [p] = 1./z ; } #endif } 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 ; double aij = Ax [p] ; double z = aij ; Cx [p] = 1./z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__minv_fp64_fp64) ( 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
regularisation.h
/* Incremental diffusion regularisation of parametrised transformation using (globally optimal) belief-propagation on minimum spanning tree. Fast distance transform uses squared differences. Similarity cost for each node and label has to be given as input. */ void messageDT(int ind,float* data,short* indout,int len1,float offsetx,float offsety,float offsetz){ //int ind1=get_global_id(0)+start; // int ind=ordered[ind1]; int len2=len1*len1; int len3=len1*len1*len1; float z[len1*2+1]; float* val; float* valout; short* indo; float* valb; float* valb2; float buffer[len3]; float buffer2[len3]; int* indb; int* indb2; int bufferi[len3]; int bufferi2[len3]; for(int i=0;i<len1*2+1;i++){ z[i]=(i-len1+offsety)*(i-len1+offsety); } for(int k1=0;k1<len1;k1++){ for(int j1=0;j1<len1;j1++){ //valb=buffer2+(j1*len1+k1*len1*len1);// val=data+ind*len3+(j1*len1+k1*len1*len1); valb2=buffer+(j1*len1+k1*len1*len1); indb=bufferi+(j1*len1+k1*len1*len1); int num=(j1*len1+k1*len1*len1); for(int i=0;i<len1;i++){ float minval=val[0]+z[i+len1]; int minind=0; for(int j=0;j<len1;j++){ bool b=(val[j]+z[i-j+len1]<minval); minval=b?val[j]+z[i-j+len1]:minval; minind=b?j:minind; } valb2[i]=minval; indb[i]=minind+num; } } } for(int i=0;i<len1*2;i++){ z[i]=(i-len1+offsetx)*(i-len1+offsetx); } for(int k1=0;k1<len1;k1++){ for(int i1=0;i1<len1;i1++){ valb=buffer+(i1+k1*len1*len1); valb2=buffer2+(i1+k1*len1*len1); indb=bufferi+(i1+k1*len1*len1); indb2=bufferi2+(i1+k1*len1*len1); for(int i=0;i<len1;i++){ float minval=valb[0]+z[i+len1]; int minind=0; for(int j=0;j<len1;j++){ bool b=(valb[j*len1]+z[i-j+len1]<minval); minval=b?valb[j*len1]+z[i-j+len1]:minval; minind=b?j:minind; } valb2[i*len1]=minval; indb2[i*len1]=indb[minind*len1]; } } } for(int i=0;i<len1*2;i++){ z[i]=(i-len1+offsetz)*(i-len1+offsetz); } for(int j1=0;j1<len1;j1++){ for(int i1=0;i1<len1;i1++){ valb=buffer2+(i1+j1*len1); //valb2=buffer+(i1+j1*len1); valout=data+ind*len3+(i1+j1*len1); indb=bufferi2+(i1+j1*len1); //indb2=bufferi+(i1+j1*len1); indo=indout+ind*len3+(i1+j1*len1); for(int i=0;i<len1;i++){ float minval=valb[0]+z[i+len1]; int minind=0; for(int j=0;j<len1;j++){ bool b=(valb[j*len2]+z[i-j+len1]<minval); minval=b?valb[j*len2]+z[i-j+len1]:minval; minind=b?j:minind; } valout[i*len2]=minval; indo[i*len2]=indb[minind*len2]; } } } } void regularisationCL(float* costall,float* u0,float* v0,float* w0,float* u1,float* v1,float* w1,int hw,int step1,float quant,int* ordered,int* parents,float* edgemst) { int m2=image_m; int n2=image_n; int o2=image_o; int m=m2/step1; int n=n2/step1; int o=o2/step1; timeval time1,time2; int sz=m*n*o; int len=hw*2+1; int len1=len; int len2=len*len*len; int len3=len*len*len; gettimeofday(&time1, NULL); short *allinds=new short[sz*len2]; float *cost1=new float[len2]; float *vals=new float[len2]; int *inds=new int[len2]; //calculate level boundaries for parallel implementation int* levels=new int[sz]; for(int i=0;i<sz;i++){ levels[i]=0; } for(int i=1;i<sz;i++){ int ochild=ordered[i]; int oparent=parents[ordered[i]]; levels[ochild]=levels[oparent]+1; } int maxlev=1+*max_element(levels,levels+sz); int* numlev=new int[maxlev]; int* startlev=new int[maxlev]; for(int i=0;i<maxlev;i++){ numlev[i]=0; } for(int i=0;i<sz;i++){ numlev[levels[i]]++; } startlev[0]=numlev[0]; for(int i=1;i<maxlev;i++){ //cumulative sum startlev[i]=startlev[i-1]+numlev[i]; } delete[] levels; int xs1,ys1,zs1,xx,yy,zz,xx2,yy2,zz2; for(int i=0;i<len2;i++){ cost1[i]=0; } //MAIN LOOP - TO BE PARALLELISED int frac=(int)(sz/25); int counti=0; int counti2=0; bool* processed=new bool[sz]; for(int i=0;i<sz;i++){ processed[i]=false; } int dblcount=0; float timeCopy=0; float timeMessage=0; //calculate mst-cost for(int lev=maxlev-1;lev>0;lev--){ int start=startlev[lev-1]; int length=numlev[lev]; gettimeofday(&time1, NULL); for(int i=start;i<start+length;i++){ int ochild=ordered[i]; for(int l=0;l<len2;l++){ costall[ochild*len2+l]*=edgemst[ochild]; } } #pragma omp parallel for for(int i=start;i<start+length;i++){ int ochild=ordered[i]; int oparent=parents[ordered[i]]; float offsetx=(u0[oparent]-u0[ochild])/(float)quant; float offsety=(v0[oparent]-v0[ochild])/(float)quant; float offsetz=(w0[oparent]-w0[ochild])/(float)quant; messageDT(ochild,costall,allinds,len1,offsetx,offsety,offsetz); } gettimeofday(&time2, NULL); timeMessage+=time2.tv_sec+time2.tv_usec/1e6-(time1.tv_sec+time1.tv_usec/1e6); gettimeofday(&time1, NULL); //copy necessary if vectorisation is used (otherwise multiple simultaneous +='s) int start0=startlev[lev-1]; int length0=numlev[lev]; for(int i=start0;i<start0+length0;i++){ int ochild=ordered[i]; int oparent=parents[ordered[i]]; float minval=*min_element(costall+ochild*len2,costall+ochild*len2+len3); for(int l=0;l<len2;l++){ costall[oparent*len2+l]+=(costall[ochild*len2+l]-minval);///edgemst[ochild];//transp //edgemst[ochild]* } } gettimeofday(&time2, NULL); timeCopy+=time2.tv_sec+time2.tv_usec/1e6-(time1.tv_sec+time1.tv_usec/1e6); } //dense displacement space float* xs=new float[len*len*len]; float* ys=new float[len*len*len]; float* zs=new float[len*len*len]; for(int i=0;i<len;i++){ for(int j=0;j<len;j++){ for(int k=0;k<len;k++){ xs[i+j*len+k*len*len]=(j-hw)*quant; ys[i+j*len+k*len*len]=(i-hw)*quant; zs[i+j*len+k*len*len]=(k-hw)*quant; } } } int *selected=new int[sz]; //mst-cost & select displacement for root note int i=0; int oroot=ordered[i]; for(int l=0;l<len2;l++){ cost1[l]=costall[oroot*len2+l];//transp } float value=cost1[0]; int index=0; for(int l=0;l<len2;l++){ if(cost1[l]<value){ value=cost1[l]; index=l; } allinds[oroot*len2+l]=l; //transp } selected[oroot]=index; u1[oroot]=xs[index]+u0[oroot]; v1[oroot]=ys[index]+v0[oroot]; w1[oroot]=zs[index]+w0[oroot]; //select displacements and add to previous deformation field for(int i=1;i<sz;i++){ int ochild=ordered[i]; int oparent=parents[ordered[i]]; //select from argmin of based on parent selection //index=allinds[ochild+selected[oparent]*sz]; index=allinds[ochild*len2+selected[oparent]]; //transp selected[ochild]=index; u1[ochild]=xs[index]+u0[ochild]; v1[ochild]=ys[index]+v0[ochild]; w1[ochild]=zs[index]+w0[ochild]; } //cout<<"Deformation field calculated!\n"; delete[] cost1; delete[] vals; delete[] inds; delete[] allinds; delete[] selected; }
irbuilder_nested_openmp_parallel_empty.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py // RUN: %clang_cc1 -no-opaque-pointers -verify -fopenmp -fopenmp-enable-irbuilder -x c++ -emit-llvm %s -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -o - | FileCheck %s --check-prefixes=ALL,IRBUILDER // %clang_cc1 -no-opaque-pointers -fopenmp -fopenmp-enable-irbuilder -x c++ -std=c++11 -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -emit-pch -o /tmp/t1 %s // %clang_cc1 -no-opaque-pointers -fopenmp -fopenmp-enable-irbuilder -x c++ -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -debug-info-kind=limited -std=c++11 -include-pch /tmp/t1 -verify %s -emit-llvm -o - | FileCheck --check-prefixes=ALL-DEBUG,IRBUILDER-DEBUG %s // expected-no-diagnostics // TODO: Teach the update script to check new functions too. #ifndef HEADER #define HEADER // ALL-LABEL: @_Z17nested_parallel_0v( // ALL-NEXT: entry: // ALL-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1:[0-9]+]]) // ALL-NEXT: br label [[OMP_PARALLEL:%.*]] // ALL: omp_parallel: // ALL-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB1]], i32 0, void (i32*, i32*, ...)* bitcast (void (i32*, i32*)* @_Z17nested_parallel_0v..omp_par.1 to void (i32*, i32*, ...)*)) // ALL-NEXT: br label [[OMP_PAR_OUTLINED_EXIT12:%.*]] // ALL: omp.par.outlined.exit12: // ALL-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // ALL: omp.par.exit.split: // ALL-NEXT: ret void // void nested_parallel_0(void) { #pragma omp parallel { #pragma omp parallel { } } } // ALL-LABEL: @_Z17nested_parallel_1Pfid( // ALL-NEXT: entry: // ALL-NEXT: [[STRUCTARG14:%.*]] = alloca { i32*, double*, float** }, align 8 // ALL-NEXT: [[R_ADDR:%.*]] = alloca float*, align 8 // ALL-NEXT: [[A_ADDR:%.*]] = alloca i32, align 4 // ALL-NEXT: [[B_ADDR:%.*]] = alloca double, align 8 // ALL-NEXT: store float* [[R:%.*]], float** [[R_ADDR]], align 8 // ALL-NEXT: store i32 [[A:%.*]], i32* [[A_ADDR]], align 4 // ALL-NEXT: store double [[B:%.*]], double* [[B_ADDR]], align 8 // ALL-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1]]) // ALL-NEXT: br label [[OMP_PARALLEL:%.*]] // ALL: omp_parallel: // ALL-NEXT: [[GEP_A_ADDR15:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG14]], i32 0, i32 0 // ALL-NEXT: store i32* [[A_ADDR]], i32** [[GEP_A_ADDR15]], align 8 // ALL-NEXT: [[GEP_B_ADDR16:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG14]], i32 0, i32 1 // ALL-NEXT: store double* [[B_ADDR]], double** [[GEP_B_ADDR16]], align 8 // ALL-NEXT: [[GEP_R_ADDR17:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG14]], i32 0, i32 2 // ALL-NEXT: store float** [[R_ADDR]], float*** [[GEP_R_ADDR17]], align 8 // ALL-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB1]], i32 1, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, { i32*, double*, float** }*)* @_Z17nested_parallel_1Pfid..omp_par.2 to void (i32*, i32*, ...)*), { i32*, double*, float** }* [[STRUCTARG14]]) // ALL-NEXT: br label [[OMP_PAR_OUTLINED_EXIT13:%.*]] // ALL: omp.par.outlined.exit13: // ALL-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // ALL: omp.par.exit.split: // ALL-NEXT: ret void // void nested_parallel_1(float *r, int a, double b) { #pragma omp parallel { #pragma omp parallel { *r = a + b; } } } // ALL-LABEL: @_Z17nested_parallel_2Pfid( // ALL-NEXT: entry: // ALL-NEXT: [[STRUCTARG:%.*]] = alloca { i32*, double*, float** }, align 8 // ALL-NEXT: [[R_ADDR:%.*]] = alloca float*, align 8 // ALL-NEXT: [[A_ADDR:%.*]] = alloca i32, align 4 // ALL-NEXT: [[B_ADDR:%.*]] = alloca double, align 8 // ALL-NEXT: store float* [[R:%.*]], float** [[R_ADDR]], align 8 // ALL-NEXT: store i32 [[A:%.*]], i32* [[A_ADDR]], align 4 // ALL-NEXT: store double [[B:%.*]], double* [[B_ADDR]], align 8 // ALL-NEXT: [[OMP_GLOBAL_THREAD_NUM:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1]]) // ALL-NEXT: br label [[OMP_PARALLEL:%.*]] // ALL: omp_parallel: // ALL-NEXT: [[GEP_A_ADDR:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG]], i32 0, i32 0 // ALL-NEXT: store i32* [[A_ADDR]], i32** [[GEP_A_ADDR]], align 8 // ALL-NEXT: [[GEP_B_ADDR:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG]], i32 0, i32 1 // ALL-NEXT: store double* [[B_ADDR]], double** [[GEP_B_ADDR]], align 8 // ALL-NEXT: [[GEP_R_ADDR:%.*]] = getelementptr { i32*, double*, float** }, { i32*, double*, float** }* [[STRUCTARG]], i32 0, i32 2 // ALL-NEXT: store float** [[R_ADDR]], float*** [[GEP_R_ADDR]], align 8 // ALL-NEXT: call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB1]], i32 1, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, { i32*, double*, float** }*)* @_Z17nested_parallel_2Pfid..omp_par.5 to void (i32*, i32*, ...)*), { i32*, double*, float** }* [[STRUCTARG]]) // ALL-NEXT: br label [[OMP_PAR_OUTLINED_EXIT55:%.*]] // ALL: omp.par.outlined.exit55: // ALL-NEXT: br label [[OMP_PAR_EXIT_SPLIT:%.*]] // ALL: omp.par.exit.split: // ALL-NEXT: [[TMP0:%.*]] = load i32, i32* [[A_ADDR]], align 4 // ALL-NEXT: [[CONV56:%.*]] = sitofp i32 [[TMP0]] to double // ALL-NEXT: [[TMP1:%.*]] = load double, double* [[B_ADDR]], align 8 // ALL-NEXT: [[ADD57:%.*]] = fadd double [[CONV56]], [[TMP1]] // ALL-NEXT: [[CONV58:%.*]] = fptrunc double [[ADD57]] to float // ALL-NEXT: [[TMP2:%.*]] = load float*, float** [[R_ADDR]], align 8 // ALL-NEXT: store float [[CONV58]], float* [[TMP2]], align 4 // ALL-NEXT: ret void // void nested_parallel_2(float *r, int a, double b) { #pragma omp parallel { *r = a + b; #pragma omp parallel { *r = a + b; #pragma omp parallel { *r = a + b; } *r = a + b; #pragma omp parallel { *r = a + b; } *r = a + b; } *r = a + b; } *r = a + b; } #endif
sparseMatrix.c
/// \File /// Routines for creating and manipulating sparse matrices. #include "sparseMatrix.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <assert.h> #include <omp.h> #include "performance.h" #include "parallel.h" #include "constants.h" /// \details /// Adjust number of non-zeroes int nnzStart(int hsize, int msize) { int M = msize; if (M == 0) M = hsize; if ((M % 32) > 0) M += (32 - (M % 32)); if (M > hsize) M = hsize; if (printRank()) printf("Adjusted M = %d\n", M); return M; } /// \details /// Allocate space for sparse matrix SparseMatrix* initSparseMatrix(int hsize, int msize) { SparseMatrix* spmatrix = (SparseMatrix*)malloc(sizeof(SparseMatrix)); // hsize is number of rows and msize is the max number of non-zeroes per row spmatrix->hsize = hsize; spmatrix->msize = msize; // iia holds the number of non-zeroes in each row spmatrix->iia = (int*)malloc(hsize*sizeof(int)); #ifdef CONTIG_MATRIX spmatrix->jjcontig = (int*)malloc(hsize*msize*sizeof(int)); spmatrix->jja = (int**)malloc(hsize*sizeof(int*)); #pragma omp parallel for for (int i = 0; i < hsize; i++) { spmatrix->jja[i] = &(spmatrix->jjcontig[i*msize]); } // Zero counts of non-zeroes per row and indices memset(spmatrix->jjcontig, 0, hsize*msize*sizeof(int)); spmatrix->valcontig = (real_t*)malloc(hsize*msize*sizeof(real_t)); spmatrix->val = (real_t**)malloc(hsize*sizeof(real_t*)); #pragma omp parallel for for (int i = 0; i < hsize; i++) { spmatrix->val[i] = &(spmatrix->valcontig[i*msize]); } // Zero non-zero values memset(spmatrix->valcontig, ZERO, hsize*msize*sizeof(real_t)); #else // jja contains the column index for each non-zero value spmatrix->jja = (int**)malloc(hsize*sizeof(int*)); for (int i = 0; i < hsize; i++) { spmatrix->jja[i] = (int*)malloc(msize*sizeof(int)); } // val contains the non-zeroes spmatrix->val = (real_t**)malloc(hsize*sizeof(real_t*)); for (int i = 0; i < hsize; i++) { spmatrix->val[i] = (real_t*)malloc(msize*sizeof(real_t)); } #endif // Zero counts of non-zeroes per row memset(spmatrix->iia, 0, hsize*sizeof(int)); // Used for normalization spmatrix->maxEval = ZERO; spmatrix->minEval = ZERO; spmatrix->maxMinusMin = ZERO; // Matrix bandwidth spmatrix->bandwidth = 0; return spmatrix; } /// \details /// Deallocate space for sparse matrix void destroySparseMatrix(struct SparseMatrixSt* spmatrix) { int hsize = spmatrix->hsize; free(spmatrix->iia); #ifdef CONTIG_MATRIX free(spmatrix->jjcontig); free(spmatrix->jja); free(spmatrix->valcontig); free(spmatrix->val); #else for (int i = 0; i < hsize; i++) { //free(spmatrix->jja[i]); } free(spmatrix->jja); for (int i = 0; i < hsize; i++) { free(spmatrix->val[i]); } free(spmatrix->val); #endif spmatrix->hsize = 0; spmatrix->msize = 0; spmatrix->bandwidth = 0; spmatrix->minEval = ZERO; spmatrix->maxEval = ZERO; spmatrix->maxMinusMin = ZERO; } /// \details /// Calculate sparcity statistics for a sparse matrix void sparsity(struct SparseMatrixSt* spmatrix) { int hsize = spmatrix->hsize; int hValCount=0; int hDist[hsize]; memset(hDist, 0, hsize*sizeof(int)); for (int i = 0; i < hsize; i++) { hValCount += spmatrix->iia[i]; if (spmatrix->iia[i] > 0) hDist[spmatrix->iia[i]] += 1; } if (printRank()) { printf("\nSparsity:\nInitial sparsity = %d, fraction = %e, Avg per row = %f\n", hValCount, (real_t)hValCount/(real_t)(hsize*hsize), (real_t)hValCount/(real_t)hsize); int maxRowCount = 0; for (int i = 0; i < hsize; i++) { maxRowCount = MAX(maxRowCount, spmatrix->iia[i]); } printf("Max per row = %d\n", maxRowCount); for (int i = 0; i < hsize; i++) { if (hDist[i] > 0) printf("I = %d, count = %d, fraction = %f\n", i, hDist[i], (real_t)hDist[i]/(real_t)hsize); } } } /// \details /// Calculate gershgorin bounds for sparse matrix void gershgorin(struct SparseMatrixSt* spmatrix, struct DomainSt* domain) { int hsize = spmatrix->hsize; real_t eMin = 10000; real_t eMax = -10000; real_t sumP, sumM, maxMinusMin; #pragma omp parallel for private(sumM,sumP) reduction(max:eMax) reduction(min:eMin) for(int i = 0; i < hsize; i++) { sumM = 0.0; for(int j = 0; j < spmatrix->iia[i]; j++) { real_t hx = ABS(spmatrix->val[i][j]); sumM += hx; if (spmatrix->jja[i][j] == i) { sumP = spmatrix->val[i][j]; sumM -= hx; } } eMax = ((eMax < (sumP + sumM)) ? sumP + sumM : eMax); eMin = ((eMin > (sumP - sumM)) ? sumP - sumM : eMin); } // Determine eMax and eMin across ranks #ifdef DO_MPI if (getNRanks() > 1) { startTimer(reduceCommTimer); // MPI_Allreduce minRealReduce(&eMin); stopTimer(reduceCommTimer); collectCounter(reduceCounter, sizeof(real_t)); startTimer(reduceCommTimer); // MPI_Allreduce maxRealReduce(&eMax); stopTimer(reduceCommTimer); collectCounter(reduceCounter, sizeof(real_t)); } #endif maxMinusMin = eMax-eMin; if (printRank()) printf("\nGershgorin:\nNew eMax, eMin = %e, %e\n", eMax, eMin); // GERSGORIN BOUNDS; spmatrix->maxEval = eMax; spmatrix->minEval = eMin; spmatrix->maxMinusMin = maxMinusMin; } /// \details /// Normalize a matrix in sparse format using the gershgorin estimates void normalize(struct SparseMatrixSt* spmatrix) { int hsize = spmatrix->hsize; int sumIia = 0; int maxIia = 0; #pragma omp parallel for reduction(+:sumIia) reduction(max:maxIia) for(int i = 0; i < hsize; i++) { for(int j = 0; j < spmatrix->iia[i]; j++) { if (spmatrix->jja[i][j] == i) { spmatrix->val[i][j] = (spmatrix->maxEval - spmatrix->val[i][j])/spmatrix->maxMinusMin; } else { spmatrix->val[i][j] = -spmatrix->val[i][j]/spmatrix->maxMinusMin; } } sumIia += spmatrix->iia[i]; maxIia = MAX(maxIia, spmatrix->iia[i]); } // WE NOW HAVE X = (eMax*I-H)/(eMax-eMin) if (printRank() && debug == 1) printf("Initial sparsity normalized = %d, fraction = %e, avg = %g, max = %d\n", sumIia, (real_t)sumIia/(real_t)(hsize*hsize), (real_t)sumIia/(real_t)hsize, maxIia); } /// \details /// Calculate trace and trace^2 for a sparse matrix. void trace(struct SparseMatrixSt* spmatrix, struct DomainSt* domain, real_t* tr, real_t* tr2) { int hsize = spmatrix->hsize; real_t trace = ZERO; real_t trace2 = ZERO; #pragma omp parallel for reduction(+:trace, trace2) for(int i = domain->localRowMin; i < domain->localRowMax; i++) { #ifdef POS1 // Diagonal values are in first position trace += spmatrix->val[i][0]; trace2 += spmatrix->val[i][0] * spmatrix->val[i][0]; #else for(int j = 0; j < spmatrix->iia[i]; j++) { if (i == spmatrix->jja[i][j]) { trace += spmatrix->val[i][j]; trace2 += spmatrix->val[i][j] * spmatrix->val[i][j]; } } #endif } *tr = trace; *tr2 = trace2; }
Example_collapse.1.c
/* * @@name: collapse.1c * @@type: C * @@compilable: yes * @@linkable: no * @@expect: success * @@version: omp_3.0 */ void bar(float *a, int i, int j, int k); int kl, ku, ks, jl, ju, js, il, iu,is; void sub(float *a) { int i, j, k; #pragma omp for collapse(2) private(i, k, j) for (k=kl; k<=ku; k+=ks) for (j=jl; j<=ju; j+=js) for (i=il; i<=iu; i+=is) bar(a,i,j,k); }
shared-clauseModificado.c
#include <stdio.h> #ifdef _OPENMP #include <omp.h> #endif int main() { int i, n = 7; int a[n]; for (i=0; i<n; i++) a[i] = i+1; #pragma omp parallel for default(none) shared(a, n) for (i=0; i<n; i++) a[i] += i; printf("Después de parallel for:\n"); for (i=0; i<n; i++) printf("a[%d] = %d\n",i,a[i]); }
GB_unaryop__identity_int8_fp32.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__identity_int8_fp32 // op(A') function: GB_tran__identity_int8_fp32 // C type: int8_t // A type: float // cast: int8_t cij ; GB_CAST_SIGNED(cij,aij,8) // unaryop: cij = aij #define GB_ATYPE \ float #define GB_CTYPE \ int8_t // 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_CASTING(z, aij) \ int8_t z ; GB_CAST_SIGNED(z,aij,8) ; // 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_IDENTITY || GxB_NO_INT8 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_int8_fp32 ( int8_t *Cx, // Cx and Ax may be aliased float *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__identity_int8_fp32 ( 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
3d25pt.c
/* * Order-2, 3D 25 point stencil * 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) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* 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, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[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] = 16; tile_size[1] = 16; tile_size[2] = 4; tile_size[3] = 64; 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); roc2[i][j][k] = 2.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 const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*( coef0* A[t%2][i ][j ][k ] + coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] + A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] + A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) + coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] + A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] + A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) + coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] + A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] + A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) + coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] + A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] + A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) ); } } } } #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(4, "constant") #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(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
GB_unop__identity_fc64_bool.c
//------------------------------------------------------------------------------ // GB_unop: 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_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__identity_fc64_bool // op(A') function: GB_unop_tran__identity_fc64_bool // C type: GxB_FC64_t // A type: bool // cast: GxB_FC64_t cij = GxB_CMPLX ((double) (aij), 0) // unaryop: cij = aij #define GB_ATYPE \ bool #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ bool aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ bool aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = GxB_CMPLX ((double) (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_FC64 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_fc64_bool ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const bool *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++) { bool aij = Ax [p] ; GxB_FC64_t z = GxB_CMPLX ((double) (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_fc64_bool ( 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_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
radmin_fmt_plug.c
/* RAdmin v2.x cracker patch for JtR. Hacked together during * May of 2012 by Dhiru Kholia <dhiru.kholia at gmail.com>. * * This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com>, * 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. * * Input Format => user:$radmin2$hash */ #if FMT_EXTERNS_H extern struct fmt_main fmt_radmin; #elif FMT_REGISTERS_H john_register_one(&fmt_radmin); #else #include "md5.h" #include <string.h> #include <assert.h> #include <errno.h> #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #ifdef _OPENMP #include <omp.h> // Tuned on core i7 quad HT // 1 7445K // 16 12155K // 32 12470K ** this was chosen. // 64 12608k // 128 12508k #ifndef OMP_SCALE #define OMP_SCALE 32 #endif #endif #include "memdbg.h" #define FORMAT_LABEL "RAdmin" #define FORMAT_NAME "v2.x" #define FORMAT_TAG "$radmin2$" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #define ALGORITHM_NAME "MD5 32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 99 #define CIPHERTEXT_LENGTH 32 #define BINARY_SIZE 16 #define SALT_SIZE 0 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 64 #define BINARY_ALIGN 4 #define SALT_ALIGN 1 static struct fmt_tests radmin_tests[] = { {"$radmin2$B137F09CF92F465CABCA06AB1B283C1F", "lastwolf"}, {"$radmin2$14e897b1a9354f875df51047bb1a0765", "podebradka"}, {"$radmin2$02ba5e187e2589be6f80da0046aa7e3c", "12345678"}, {"$radmin2$b4e13c7149ebde51e510959f30319ac7", "firebaLL"}, {"$radmin2$3d2c8cae4621edf8abb081408569482b", "yamaha12345"}, {"$radmin2$60cb8e411b02c10ecc3c98e29e830de8", "xplicit"}, {"$radmin2$53b1dc4fd27e58a075b196f99b2ac992", "UPPERCASE"}, {"$radmin2$6d0bb00954ceb7fbee436bb55a8397a9", ""}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH+1]; static ARCH_WORD_32 (*crypt_out)[8]; static void init(struct fmt_main *self) { #ifdef _OPENMP int 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 saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); } static void done(void) { MEM_FREE(saved_key); MEM_FREE(crypt_out); } static char *split(char *ciphertext, int index, struct fmt_main *self) { static char buf[CIPHERTEXT_LENGTH + FORMAT_TAG_LEN + 1]; // $radmin2$ is 9 bytes strnzcpy(buf, ciphertext, CIPHERTEXT_LENGTH + FORMAT_TAG_LEN + 1); strlwr(buf); return buf; } static int valid(char *ciphertext, struct fmt_main *self) { char *p; int extra; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN)) return 0; p = ciphertext + FORMAT_TAG_LEN; if (hexlen(p, &extra) != CIPHERTEXT_LENGTH || extra) return 0; return 1; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE+1]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; p = strrchr(ciphertext, '$') + 1; for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index; #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { MD5_CTX ctx; MD5_Init(&ctx); MD5_Update(&ctx, saved_key[index], sizeof(saved_key[index])); MD5_Final((unsigned char *)crypt_out[index], &ctx); } return count; } static int cmp_all(void *binary, int count) { int index; for (index = 0; index < count; index++) if (*(ARCH_WORD_32 *)binary == crypt_out[index][0]) return 1; return 0; } static int cmp_one(void *binary, int index) { return *(ARCH_WORD_32 *)binary == crypt_out[index][0]; } static int cmp_exact(char *source, int index) { void *binary = get_binary(source); return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static void radmin_set_key(char *key, int index) { // this code assures that both saved_key[index] gets null-terminated (without buffer overflow) char *cp = &saved_key[index][strnzcpyn(saved_key[index], key, PLAINTEXT_LENGTH + 1)+1]; // and is null padded up to 100 bytes. We simply clean up prior buffer, up to element 99, but that element will never be written to if (cp < &saved_key[index][99]) while (*cp) *cp++ = 0; } static char *get_key(int index) { // assured null teminated string. Just return it. return saved_key[index]; } struct fmt_main fmt_radmin = { { 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, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_OMP_BAD | FMT_SPLIT_UNIFIES_CASE, { NULL }, { FORMAT_TAG }, radmin_tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, split, get_binary, fmt_default_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, fmt_default_set_salt, radmin_set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
GB_binop__times_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__times_int16) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__times_int16) // A.*B function (eWiseMult): GB (_AemultB_03__times_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__times_int16) // A*D function (colscale): GB (_AxD__times_int16) // D*A function (rowscale): GB (_DxB__times_int16) // C+=B function (dense accum): GB (_Cdense_accumB__times_int16) // C+=b function (dense accum): GB (_Cdense_accumb__times_int16) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__times_int16) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__times_int16) // C=scalar+B GB (_bind1st__times_int16) // C=scalar+B' GB (_bind1st_tran__times_int16) // C=A+scalar GB (_bind2nd__times_int16) // C=A'+scalar GB (_bind2nd_tran__times_int16) // C type: int16_t // A type: int16_t // B,b type: int16_t // 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) \ 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 = (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_TIMES || GxB_NO_INT16 || GxB_NO_TIMES_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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__times_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] = (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_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] = (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 = Ax [pA] ; \ Cx [pC] = (x * aij) ; \ } GrB_Info GB (_bind1st_tran__times_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] = (aij * y) ; \ } GrB_Info GB (_bind2nd_tran__times_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
loadcpu.c
/* | CPU benchmark program | loads all available CPU until Ctrl+C | | compile using: | cc ./loadcpu.c -o loadcpu -fopenmp | | _______________________________________ | | (c) cjayho, 2020+ | | This program is distributed under the terms of | 3-clause BSD license | */ #include <stdio.h> #include <omp.h> int main( void ) { char* banner = "\n\ \ |\n\ | loadCPU simple benchmark\n\ | loads all available cpu cores in parallel\n\ | \n\ | Stop using Ctrl-C\n\ | ______________________________________________\n\ |\n\ | (c) cjayho, 2020+\n\ | This program is distributed under the terms\n\ | of 3-clause BSD license.\n\ |\n"; puts( banner ); #pragma omp parallel while(1) { ; // nop } }
psd.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % Copyright 1999-2020 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Photoshop spec @ https://www.adobe.com/devnet-apps/photoshop/fileformatashtml % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/policy.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/registry.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[257], visible; unsigned short channels; StringInfo *info; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(Image *image) { switch (image->compose) { case ColorBurnCompositeOp: return(image->endian == LSBEndian ? "vidi" : "idiv"); case ColorDodgeCompositeOp: return(image->endian == LSBEndian ? " vid" : "div "); case ColorizeCompositeOp: return(image->endian == LSBEndian ? "rloc" : "colr"); case DarkenCompositeOp: return(image->endian == LSBEndian ? "krad" : "dark"); case DifferenceCompositeOp: return(image->endian == LSBEndian ? "ffid" : "diff"); case DissolveCompositeOp: return(image->endian == LSBEndian ? "ssid" : "diss"); case ExclusionCompositeOp: return(image->endian == LSBEndian ? "dums" : "smud"); case HardLightCompositeOp: return(image->endian == LSBEndian ? "tiLh" : "hLit"); case HardMixCompositeOp: return(image->endian == LSBEndian ? "xiMh" : "hMix"); case HueCompositeOp: return(image->endian == LSBEndian ? " euh" : "hue "); case LightenCompositeOp: return(image->endian == LSBEndian ? "etil" : "lite"); case LinearBurnCompositeOp: return(image->endian == LSBEndian ? "nrbl" : "lbrn"); case LinearDodgeCompositeOp: return(image->endian == LSBEndian ? "gddl" : "lddg"); case LinearLightCompositeOp: return(image->endian == LSBEndian ? "tiLl" : "lLit"); case LuminizeCompositeOp: return(image->endian == LSBEndian ? " mul" : "lum "); case MultiplyCompositeOp: return(image->endian == LSBEndian ? " lum" : "mul "); case OverlayCompositeOp: return(image->endian == LSBEndian ? "revo" : "over"); case PinLightCompositeOp: return(image->endian == LSBEndian ? "tiLp" : "pLit"); case SaturateCompositeOp: return(image->endian == LSBEndian ? " tas" : "sat "); case ScreenCompositeOp: return(image->endian == LSBEndian ? "nrcs" : "scrn"); case SoftLightCompositeOp: return(image->endian == LSBEndian ? "tiLs" : "sLit"); case VividLightCompositeOp: return(image->endian == LSBEndian ? "tiLv" : "vLit"); case OverCompositeOp: default: return(image->endian == LSBEndian ? "mron" : "norm"); } } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image,ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if ((image->alpha_trait != BlendPixelTrait) || (image->colorspace != sRGBColorspace)) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringFalse(option) != MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; register ssize_t i; gamma=QuantumScale*GetPixelAlpha(image, q); if (gamma != 0.0 && gamma != 1.0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); if (channel != AlphaPixelChannel) q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma); } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity, MagickBooleanType revert,ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying layer opacity %.20g", (double) opacity); if (opacity == OpaqueAlpha) return(MagickTrue); if (image->alpha_trait != BlendPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (revert == MagickFalse) SetPixelAlpha(image,(Quantum) (QuantumScale*(GetPixelAlpha(image,q))* opacity),q); else if (opacity > 0) SetPixelAlpha(image,(Quantum) (QuantumRange*(GetPixelAlpha(image,q)/ (MagickRealType) opacity)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; PixelInfo color; ssize_t y; if (image->alpha_trait == UndefinedPixelTrait) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,0,0,MagickTrue,exception); if (complete_mask == (Image *) NULL) return(MagickFalse); complete_mask->alpha_trait=BlendPixelTrait; GetPixelInfo(complete_mask,&color); color.red=(MagickRealType) background; (void) SetImageColor(complete_mask,&color,exception); status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue, mask->page.x-image->page.x,mask->page.y-image->page.y,exception); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register Quantum *p; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=(MagickRealType) GetPixelAlpha(image,q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q); else if (intensity > 0) SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q); q+=GetPixelChannels(image); p+=GetPixelChannels(complete_mask); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info, ExceptionInfo *exception) { char *key; RandomInfo *random_info; StringInfo *key_info; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " preserving opacity mask"); random_info=AcquireRandomInfo(); key_info=GetRandomKey(random_info,2+1); key=(char *) GetStringInfoDatum(key_info); key[8]=(char) layer_info->mask.background; key[9]='\0'; layer_info->mask.image->page.x+=layer_info->page.x; layer_info->mask.image->page.y+=layer_info->page.y; (void) SetImageRegistry(ImageRegistryType,(const char *) key, layer_info->mask.image,exception); (void) SetImageArtifact(layer_info->image,"psd:opacity-mask", (const char *) key); key_info=DestroyStringInfo(key_info); random_info=DestroyRandomInfo(random_info); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(const Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); } if (image->depth > 16) return(4); if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return(((image->columns+7)/8)*GetPSDPacketSize(image)); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception) { ChannelType channel_mask; MagickBooleanType status; channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~ AlphaChannel)); status=NegateImage(image,MagickFalse,exception); (void) SetImageChannelMask(image,channel_mask); return(status); } static StringInfo *ParseImageResourceBlocks(PSDInfo *psd_info,Image *image, const unsigned char *blocks,size_t length) { const unsigned char *p; ssize_t offset; StringInfo *profile; unsigned char name_length; unsigned int count; unsigned short id, short_sans; if (length < 16) return((StringInfo *) NULL); profile=BlobToStringInfo((const unsigned char *) NULL,length); SetStringInfoDatum(profile,blocks); SetStringInfoName(profile,"8bim"); for (p=blocks; (p >= blocks) && (p < (blocks+length-7)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p+=4; p=PushShortPixel(MSBEndian,p,&id); p=PushCharPixel(p,&name_length); if ((name_length % 2) == 0) name_length++; p+=name_length; if (p > (blocks+length-4)) break; p=PushLongPixel(MSBEndian,p,&count); offset=(ssize_t) count; if (((p+offset) < blocks) || ((p+offset) > (blocks+length))) break; switch (id) { case 0x03ed: { unsigned short resolution; /* Resolution info. */ if (offset < 16) break; p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.x=(double) resolution; (void) FormatImageProperty(image,"tiff:XResolution","%*g", GetMagickPrecision(),image->resolution.x); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.y=(double) resolution; (void) FormatImageProperty(image,"tiff:YResolution","%*g", GetMagickPrecision(),image->resolution.y); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if ((offset > 4) && (*(p+4) == 0)) psd_info->has_merged_image=MagickFalse; p+=offset; break; } default: { p+=offset; break; } } if ((offset & 0x01) != 0) p++; } return(profile); } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q, ExceptionInfo *exception) { if (image->storage_class == PseudoClass) { PixelInfo *color; Quantum index; index=pixel; if (packet_size == 1) index=(Quantum) ScaleQuantumToChar(index); index=(Quantum) ConstrainColormapIndex(image,(ssize_t) index, exception); if (type == 0) SetPixelIndex(image,index,q); if ((type == 0) && (channels > 1)) return; color=image->colormap+(ssize_t) GetPixelIndex(image,q); if (type != 0) color->alpha=(MagickRealType) pixel; SetPixelViaPixelInfo(image,color,q); return; } switch (type) { case -1: { SetPixelAlpha(image,pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); break; } case -3: case 1: { SetPixelGreen(image,pixel,q); break; } case -4: case 2: { SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const ssize_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else if (packet_size == 2) { unsigned short nibble; p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } else { MagickFloatType nibble; p=PushFloatPixel(MSBEndian,p,&nibble); pixel=ClampToQuantum((MagickRealType) (QuantumRange*nibble)); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q,exception); q+=GetPixelChannels(image); } else { ssize_t bit, number_bits; number_bits=(ssize_t) image->columns-x; if (number_bits > 8) number_bits=8; for (bit = 0; bit < (ssize_t) number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception); q+=GetPixelChannels(image); x++; } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t row_size; ssize_t count, y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) memset(pixels,0,row_size*sizeof(*pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != (ssize_t) row_size) { status=MagickFalse; break; } status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLESizes(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *sizes; ssize_t y; sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes)); if(sizes != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) sizes[y]=(MagickOffsetType) ReadBlobShort(image); else sizes[y]=(MagickOffsetType) ReadBlobLong(image); } } return sizes; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < sizes[y]) length=(size_t) sizes[y]; if (length > (row_size+2048)) /* arbitrary number */ { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength",image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) memset(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static void Unpredict8Bit(unsigned char *pixels,const size_t count) { register unsigned char *p; size_t remaining; p=pixels; remaining=count; while (--remaining) { *(p+1)+=*p; p++; } } static void Unpredict16Bit(const Image *image,unsigned char *pixels, const size_t count, const size_t row_size) { register unsigned char *p; size_t length, remaining; p=pixels; remaining=count; while (remaining > 0) { length=image->columns; while (--length) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; p+=2; } p+=2; remaining-=row_size; } } static void Unpredict32Bit(const Image *image,unsigned char *pixels, unsigned char *output_pixels,const size_t row_size) { register unsigned char *p, *q; register ssize_t y; size_t offset1, offset2, offset3, remaining; unsigned char *start; offset1=image->columns; offset2=2*offset1; offset3=3*offset1; p=pixels; q=output_pixels; for (y=0; y < (ssize_t) image->rows; y++) { start=p; remaining=row_size; while (--remaining) { *(p+1)+=*p; p++; } p=start; remaining=image->columns; while (remaining--) { *(q++)=*p; *(q++)=*(p+offset1); *(q++)=*(p+offset2); *(q++)=*(p+offset3); p++; } p=start+row_size; } } static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, packet_size, row_size; register ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); if ((MagickSizeType) compact_size > GetBlobSize(image)) ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } memset(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(uInt) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(uInt) count; if (inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream,Z_SYNC_FLUSH); if ((ret != Z_OK) && (ret != Z_STREAM_END)) { (void) inflateEnd(&stream); compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } if (ret == Z_STREAM_END) break; } (void) inflateEnd(&stream); } if (compression == ZipWithPrediction) { if (packet_size == 1) Unpredict8Bit(pixels,count); else if (packet_size == 2) Unpredict16Bit(image,pixels,count,row_size); else if (packet_size == 4) { unsigned char *output_pixels; output_pixels=(unsigned char *) AcquireQuantumMemory(count, sizeof(*output_pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError, "MemoryAllocationFailed",image->filename); } Unpredict32Bit(image,pixels,output_pixels,row_size); pixels=(unsigned char *) RelinquishMagickMemory(pixels); pixels=output_pixels; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { (void) SeekBlob(image,(MagickOffsetType) layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { (void) ResetImagePixels(mask,exception); (void) SetImageType(mask,GrayscaleType,exception); channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, (ssize_t) layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, (ssize_t) layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, (ssize_t) layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } (void) SeekBlob(image,offset+layer_info->channel_info[channel].size-2, SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) (void) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } if (mask != (Image *) NULL) { if (layer_info->mask.image != (Image *) NULL) layer_info->mask.image=DestroyImage(layer_info->mask.image); layer_info->mask.image=mask; } return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception) { char message[MagickPathExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); if (psd_info->mode != IndexedMode) (void) SetImageBackgroundColor(layer_info->image,exception); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) layer_info->image->compose=NoCompositeOp; /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name, exception); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->alpha_trait=BlendPixelTrait; status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info, (size_t) j,compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } static MagickBooleanType CheckPSDChannels(const PSDInfo *psd_info, LayerInfo *layer_info) { int channel_type; register ssize_t i; if (layer_info->channels < psd_info->min_channels) return(MagickFalse); channel_type=RedChannel; if (psd_info->min_channels >= 3) channel_type|=(GreenChannel | BlueChannel); if (psd_info->min_channels >= 4) channel_type|=BlackChannel; for (i=0; i < (ssize_t) layer_info->channels; i++) { short type; type=layer_info->channel_info[i].type; if ((i == 0) && (psd_info->mode == IndexedMode) && (type != 0)) return(MagickFalse); if (type == -1) { channel_type|=AlphaChannel; continue; } if (type < -1) continue; if (type == 0) channel_type&=~RedChannel; else if (type == 1) channel_type&=~GreenChannel; else if (type == 2) channel_type&=~BlueChannel; else if (type == 3) channel_type&=~BlackChannel; } if (channel_type == 0) return(MagickTrue); if ((channel_type == AlphaChannel) && (layer_info->channels >= psd_info->min_channels + 1)) return(MagickTrue); return(MagickFalse); } static void AttachPSDLayers(Image *image,LayerInfo *layer_info, ssize_t number_layers) { register ssize_t i; ssize_t j; for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers == 0) { layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); return; } for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } static inline MagickBooleanType PSDSkipImage(const PSDInfo *psd_info, const ImageInfo *image_info,const size_t index) { if (psd_info->has_merged_image == MagickFalse) return(MagickFalse); if (image_info->number_scenes == 0) return(MagickFalse); if (index < image_info->scene) return(MagickTrue); if (index > image_info->scene+image_info->number_scenes-1) return(MagickTrue); return(MagickFalse); } static void CheckMergedImageAlpha(const PSDInfo *psd_info,Image *image) { /* The number of layers cannot be used to determine if the merged image contains an alpha channel. So we enable it when we think we should. */ if (((psd_info->mode == GrayscaleMode) && (psd_info->channels > 1)) || ((psd_info->mode == RGBMode) && (psd_info->channels > 3)) || ((psd_info->mode == CMYKMode) && (psd_info->channels > 4))) image->alpha_trait=BlendPixelTrait; } static void ParseAdditionalInfo(LayerInfo *layer_info) { char key[5]; size_t remaining_length; unsigned char *p; unsigned int size; p=GetStringInfoDatum(layer_info->info); remaining_length=GetStringInfoLength(layer_info->info); while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(char) (*p++); key[1]=(char) (*p++); key[2]=(char) (*p++); key[3]=(char) (*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) break; if (LocaleNCompare(key,"luni",sizeof(key)) == 0) { unsigned char *name; unsigned int length; length=(unsigned int) (*p++) << 24; length|=(unsigned int) (*p++) << 16; length|=(unsigned int) (*p++) << 8; length|=(unsigned int) (*p++); if (length * 2 > size - 4) break; if (sizeof(layer_info->name) <= length) break; name=layer_info->name; while (length > 0) { /* Only ASCII strings are supported */ if (*p++ != '\0') break; *name++=*p++; length--; } if (length == 0) *name='\0'; break; } else p+=size; remaining_length-=(size_t) size; } } static MagickBooleanType ReadPSDLayersInternal(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, index, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); if (count == 4) ReversePSDString(image,type,(size_t) count); if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0)) { CheckMergedImageAlpha(psd_info,image); return(MagickTrue); } else { count=ReadBlob(image,4,(unsigned char *) type); if (count == 4) ReversePSDString(image,type,4); if ((count == 4) && ((LocaleNCompare(type,"Lr16",4) == 0) || (LocaleNCompare(type,"Lr32",4) == 0))) size=GetPSDSize(psd_info,image); else { CheckMergedImageAlpha(psd_info,image); return(MagickTrue); } } } if (size == 0) return(MagickTrue); layer_info=(LayerInfo *) NULL; number_layers=(ssize_t) ReadBlobSignedShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) memset(layer_info,0,(size_t) number_layers*sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t top, left, bottom, right; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); top=(ssize_t) ReadBlobSignedLong(image); left=(ssize_t) ReadBlobSignedLong(image); bottom=(ssize_t) ReadBlobSignedLong(image); right=(ssize_t) ReadBlobSignedLong(image); if ((right < left) || (bottom < top)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } layer_info[i].page.y=top; layer_info[i].page.x=left; layer_info[i].page.width=(size_t) (right-left); layer_info[i].page.height=(size_t) (bottom-top); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); if ((layer_info[i].channel_info[j].type < -4) || (layer_info[i].channel_info[j].type > 4)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"NoSuchImageChannel", image->filename); } layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } if (CheckPSDChannels(psd_info,&layer_info[i]) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) type); if (count == 4) ReversePSDString(image,type,4); if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); if (count != 4) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=(ssize_t) ReadBlobSignedLong(image); layer_info[i].mask.page.x=(ssize_t) ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobSignedLong(image)-layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) ( ReadBlobSignedLong(image)-layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,(double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } /* Layer name. */ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; if (length > GetBlobSize(image)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "InsufficientImageDataInFile",image->filename); } layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); ParseAdditionalInfo(&layer_info[i]); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info,exception); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping != MagickFalse) { AttachPSDLayers(image,layer_info,number_layers); return(MagickTrue); } status=MagickTrue; index=0; for (i=0; i < number_layers; i++) { if ((layer_info[i].image == (Image *) NULL) || (PSDSkipImage(psd_info, image_info,++index) != MagickFalse)) { for (j=0; j < (ssize_t) layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i, (MagickSizeType) number_layers); if (status == MagickFalse) break; } if (status != MagickFalse) AttachPSDLayers(image,layer_info,number_layers); else layer_info=DestroyLayerInfo(layer_info,number_layers); return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception) { PolicyDomain domain; PolicyRights rights; domain=CoderPolicyDomain; rights=ReadPolicyRights; if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse) return(MagickTrue); return(ReadPSDLayersInternal(image,image_info,psd_info,MagickFalse, exception)); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image *image,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickOffsetType *sizes; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; if ((image_info->number_scenes != 0) && (image_info->scene != 0)) return(MagickTrue); compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } sizes=(MagickOffsetType *) NULL; if (compression == RLE) { sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { ssize_t type; type=i; if ((type == 1) && (psd_info->channels == 2)) type=-1; if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,type,sizes+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,type,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i, psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateCMYK(image,exception); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; size_t imageListLength; ssize_t count; StringInfo *profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count != 4) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels < 1) ThrowReaderException(CorruptImageError,"MissingImageChannel"); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16) && (psd_info.depth != 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if ((psd_info.mode == IndexedMode) && (psd_info.channels > 3)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); status=ResetImagePixels(image,exception); if (status == MagickFalse) return(DestroyImageList(image)); psd_info.min_channels=3; if (psd_info.mode == LabMode) (void) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { psd_info.min_channels=4; (void) SetImageColorspace(image,CMYKColorspace,exception); } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { if (psd_info.depth != 32) { status=AcquireImageColormap(image,MagickMin((size_t) (psd_info.depth < 16 ? 256 : 65536), MaxColormapSize),exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); } psd_info.min_channels=1; (void) SetImageColorspace(image,GRAYColorspace,exception); } else if (psd_info.mode == IndexedMode) psd_info.min_channels=1; if (psd_info.channels < psd_info.min_channels) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if ((psd_info.mode == IndexedMode) && (length < 3)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if ((psd_info.mode == DuotoneMode) || (psd_info.depth == 32)) { /* Duotone image data; the format of this data is undocumented. 32 bits per pixel; the colormap is ignored. */ (void) SeekBlob(image,(const MagickOffsetType) length,SEEK_CUR); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=(size_t) length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); psd_info.has_merged_image=MagickTrue; profile=(StringInfo *) NULL; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } profile=ParseImageResourceBlocks(&psd_info,image,blocks,(size_t) length); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (psd_info.has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayersInternal(image,image_info,&psd_info,skip_layers, exception) != MagickTrue) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ (void) SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (EOFBlob(image) != MagickFalse) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } if (image_info->ping != MagickFalse) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); imageListLength=GetImageListLength(image); if ((psd_info.has_merged_image != MagickFalse) || (imageListLength == 1)) psd_info.has_merged_image=(MagickBooleanType) ReadPSDMergedImage( image_info,image,&psd_info,exception); if ((psd_info.has_merged_image == MagickFalse) && (imageListLength == 1) && (length != 0)) { (void) SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayersInternal(image,image_info,&psd_info,MagickFalse, exception); if (status != MagickTrue) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if (psd_info.has_merged_image == MagickFalse) { Image *merged; if (imageListLength == 1) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); } image->background_color.alpha=(MagickRealType) TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; (void) SetImageBackgroundColor(image,exception); merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } if (profile != (StringInfo *) NULL) { Image *next; i=0; next=image; while (next != (Image *) NULL) { if (PSDSkipImage(&psd_info,image_info,i++) == MagickFalse) (void) SetImageProfile(next,GetStringInfoName(profile),profile, exception); next=next->next; } profile=DestroyStringInfo(profile); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned int) offset)); } static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickOffsetType offset) { MagickOffsetType current_offset; ssize_t result; current_offset=TellBlob(image); (void) SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBShort(image,(unsigned short) size); else result=WriteBlobMSBLong(image,(unsigned int) size); (void) SeekBlob(image,current_offset,SEEK_SET); return(result); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobLong(image,(unsigned int) size)); return(WriteBlobLongLong(image,size)); } static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickOffsetType offset) { MagickOffsetType current_offset; ssize_t result; current_offset=TellBlob(image); (void) SeekBlob(image,offset,SEEK_SET); result=SetPSDSize(psd_info,image,size); (void) SeekBlob(image,current_offset,SEEK_SET); return(result); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels, ExceptionInfo *exception) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); assert(compact_pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image, const Image *next_image,const CompressionType compression, const ssize_t channels) { size_t length; ssize_t i, y; if (compression == RLECompression) { length=(size_t) WriteBlobShort(image,RLE); for (i=0; i < channels; i++) for (y=0; y < (ssize_t) next_image->rows; y++) length+=SetPSDOffset(psd_info,image,0); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (compression == ZipCompression) length=(size_t) WriteBlobShort(image,ZipWithoutPrediction); #endif else length=(size_t) WriteBlobShort(image,Raw); return(length); } static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate, const CompressionType compression,ExceptionInfo *exception) { MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t count, length; ssize_t y; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,compression,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory( MagickMinBufferExtent,sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } memset(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) MagickMinBufferExtent; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) MagickMinBufferExtent-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } static unsigned char *AcquireCompactPixels(const Image *image, ExceptionInfo *exception) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); } return(compact_pixels); } static size_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { CompressionType compression; Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; compression=next_image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; if (compression == RLECompression) { compact_pixels=AcquireCompactPixels(next_image,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if ((next_image->storage_class != PseudoClass) || (IsImageGray(next_image) != MagickFalse)) { if (IsImageGray(next_image) == MagickFalse) channels=(size_t) (next_image->colorspace == CMYKColorspace ? 4 : 3); if (next_image->alpha_trait != UndefinedPixelTrait) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,compression, (ssize_t) channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if ((next_image->storage_class == PseudoClass) && (IsImageGray(next_image) == MagickFalse)) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsImageGray(next_image) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->alpha_trait != UndefinedPixelTrait) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, exception); if (mask != (Image *) NULL) { if (compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue,compression, exception); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } static size_t WritePascalString(Image *image,const char *value,size_t padding) { size_t count, length; register ssize_t i; /* Max length is 255. */ count=0; length=(strlen(value) > 255UL ) ? 255UL : strlen(value); if (length == 0) count+=WriteBlobByte(image,0); else { count+=WriteBlobByte(image,(unsigned char) length); count+=WriteBlob(image,length,(const unsigned char *) value); } length++; if ((length % padding) == 0) return(count); for (i=0; i < (ssize_t) (padding-(length % padding)); i++) count+=WriteBlobByte(image,0); return(count); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->resolution.x+0.5; y_resolution=2.54*65536.0*image->resolution.y+0.5; units=2; } else { x_resolution=65536.0*image->resolution.x+0.5; y_resolution=65536.0*image->resolution.y+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image, const signed short channel) { size_t count; count=(size_t) WriteBlobShort(image,(const unsigned short) channel); count+=SetPSDSize(psd_info,image,0); return(count); } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) memmove(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)) && ((ssize_t) length-(cnt+12)-(q-datum)) > 0) { (void) memmove(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { #define PSDKeySize 5 #define PSDAllowedLength 36 char key[PSDKeySize]; /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */ const char allowed[PSDAllowedLength][PSDKeySize] = { "blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk", "GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr", "lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl", "post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA" }, *option; const StringInfo *info; MagickBooleanType found; register size_t i; size_t remaining_length, length; StringInfo *profile; unsigned char *p; unsigned int size; info=GetImageProfile(image,"psd:additional-info"); if (info == (const StringInfo *) NULL) return((const StringInfo *) NULL); option=GetImageOption(image_info,"psd:additional-info"); if (LocaleCompare(option,"all") == 0) return(info); if (LocaleCompare(option,"selective") != 0) { profile=RemoveImageProfile(image,"psd:additional-info"); return(DestroyStringInfo(profile)); } length=GetStringInfoLength(info); p=GetStringInfoDatum(info); remaining_length=length; length=0; while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(char) (*p++); key[1]=(char) (*p++); key[2]=(char) (*p++); key[3]=(char) (*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) return((const StringInfo *) NULL); found=MagickFalse; for (i=0; i < PSDAllowedLength; i++) { if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0) continue; found=MagickTrue; break; } remaining_length-=(size_t) size; if (found == MagickFalse) { if (remaining_length > 0) p=(unsigned char *) memmove(p-12,p+size,remaining_length); continue; } length+=(size_t) size+12; p+=size; } profile=RemoveImageProfile(image,"psd:additional-info"); if (length == 0) return(DestroyStringInfo(profile)); SetStringInfoLength(profile,(const size_t) length); (void) SetImageProfile(image,"psd:additional-info",info,exception); return(profile); } static MagickBooleanType WritePSDLayersInternal(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,size_t *layers_size, ExceptionInfo *exception) { char layer_name[MagickPathExtent]; const char *property; const StringInfo *info; Image *base_image, *next_image; MagickBooleanType status; MagickOffsetType *layer_size_offsets, size_offset; register ssize_t i; size_t layer_count, layer_index, length, name_length, rounded_size, size; status=MagickTrue; base_image=GetNextImageInList(image); if (base_image == (Image *) NULL) base_image=image; size=0; size_offset=TellBlob(image); (void) SetPSDSize(psd_info,image,0); layer_count=0; for (next_image=base_image; next_image != NULL; ) { layer_count++; next_image=GetNextImageInList(next_image); } if (image->alpha_trait != UndefinedPixelTrait) size+=WriteBlobShort(image,-(unsigned short) layer_count); else size+=WriteBlobShort(image,(unsigned short) layer_count); layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory( (size_t) layer_count,sizeof(MagickOffsetType)); if (layer_size_offsets == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); layer_index=0; for (next_image=base_image; next_image != NULL; ) { Image *mask; unsigned char default_color; unsigned short channels, total_channels; mask=(Image *) NULL; property=GetImageArtifact(next_image,"psd:opacity-mask"); default_color=0; if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception); default_color=(unsigned char) (strlen(property) == 9 ? 255 : 0); } size+=WriteBlobSignedLong(image,(signed int) next_image->page.y); size+=WriteBlobSignedLong(image,(signed int) next_image->page.x); size+=WriteBlobSignedLong(image,(signed int) (next_image->page.y+ next_image->rows)); size+=WriteBlobSignedLong(image,(signed int) (next_image->page.x+ next_image->columns)); channels=1; if ((next_image->storage_class != PseudoClass) && (IsImageGray(next_image) == MagickFalse)) channels=(unsigned short) (next_image->colorspace == CMYKColorspace ? 4 : 3); total_channels=channels; if (next_image->alpha_trait != UndefinedPixelTrait) total_channels++; if (mask != (Image *) NULL) total_channels++; size+=WriteBlobShort(image,total_channels); layer_size_offsets[layer_index++]=TellBlob(image); for (i=0; i < (ssize_t) channels; i++) size+=WriteChannelSize(psd_info,image,(signed short) i); if (next_image->alpha_trait != UndefinedPixelTrait) size+=WriteChannelSize(psd_info,image,-1); if (mask != (Image *) NULL) size+=WriteChannelSize(psd_info,image,-2); size+=WriteBlobString(image,image->endian == LSBEndian ? "MIB8" :"8BIM"); size+=WriteBlobString(image,CompositeOperatorToPSDBlendMode(next_image)); property=GetImageArtifact(next_image,"psd:layer.opacity"); if (property != (const char *) NULL) { Quantum opacity; opacity=(Quantum) StringToInteger(property); size+=WriteBlobByte(image,ScaleQuantumToChar(opacity)); (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception); } else size+=WriteBlobByte(image,255); size+=WriteBlobByte(image,0); size+=WriteBlobByte(image,(const unsigned char) (next_image->compose == NoCompositeOp ? 1 << 0x02 : 1)); /* layer properties - visible, etc. */ size+=WriteBlobByte(image,0); info=GetAdditionalInformation(image_info,next_image,exception); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) { (void) FormatLocaleString(layer_name,MagickPathExtent,"L%.20g", (double) layer_index); property=layer_name; } name_length=strlen(property)+1; if ((name_length % 4) != 0) name_length+=(4-(name_length % 4)); if (info != (const StringInfo *) NULL) name_length+=GetStringInfoLength(info); name_length+=8; if (mask != (Image *) NULL) name_length+=20; size+=WriteBlobLong(image,(unsigned int) name_length); if (mask == (Image *) NULL) size+=WriteBlobLong(image,0); else { if (mask->compose != NoCompositeOp) (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum( default_color),MagickTrue,exception); mask->page.y+=image->page.y; mask->page.x+=image->page.x; size+=WriteBlobLong(image,20); size+=WriteBlobSignedLong(image,(const signed int) mask->page.y); size+=WriteBlobSignedLong(image,(const signed int) mask->page.x); size+=WriteBlobSignedLong(image,(const signed int) (mask->rows+ mask->page.y)); size+=WriteBlobSignedLong(image,(const signed int) (mask->columns+ mask->page.x)); size+=WriteBlobByte(image,default_color); size+=WriteBlobByte(image,(const unsigned char) (mask->compose == NoCompositeOp ? 2 : 0)); size+=WriteBlobMSBShort(image,0); } size+=WriteBlobLong(image,0); size+=WritePascalString(image,property,4); if (info != (const StringInfo *) NULL) size+=WriteBlob(image,GetStringInfoLength(info), GetStringInfoDatum(info)); next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; layer_index=0; while (next_image != NULL) { length=WritePSDChannels(psd_info,image_info,image,next_image, layer_size_offsets[layer_index++],MagickTrue,exception); if (length == 0) { status=MagickFalse; break; } size+=length; next_image=GetNextImageInList(next_image); } /* Write the total size */ if (layers_size != (size_t*) NULL) *layers_size=size; if ((size/2) != ((size+1)/2)) rounded_size=size+1; else rounded_size=size; (void) WritePSDSize(psd_info,image,rounded_size,size_offset); layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory( layer_size_offsets); /* Remove the opacity mask from the registry */ next_image=base_image; while (next_image != (Image *) NULL) { property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) (void) DeleteImageRegistry(property); next_image=GetNextImageInList(next_image); } return(status); } ModuleExport MagickBooleanType WritePSDLayers(Image * image, const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception) { PolicyDomain domain; PolicyRights rights; domain=CoderPolicyDomain; rights=WritePolicyRights; if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse) return(MagickTrue); return WritePSDLayersInternal(image,image_info,psd_info,(size_t*) NULL, exception); } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const StringInfo *icc_profile; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; size_t length, num_channels, packet_size; StringInfo *bim_profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->alpha_trait != UndefinedPixelTrait) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ /* When the image has a color profile it won't be converted to gray scale */ if ((GetImageProfile(image,"icc") == (StringInfo *) NULL) && (SetImageGray(image,exception) != MagickFalse)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType) && (image->storage_class == PseudoClass)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass,exception); if (image->colorspace != CMYKColorspace) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL); else num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsImageGray(image) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsImageGray(image) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].red))); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].green))); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].blue))); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((ssize_t) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } if (status != MagickFalse) { MagickOffsetType size_offset; size_t size; size_offset=TellBlob(image); (void) SetPSDSize(&psd_info,image,0); status=WritePSDLayersInternal(image,image_info,&psd_info,&size, exception); size_offset+=WritePSDSize(&psd_info,image,size+ (psd_info.version == 1 ? 8 : 12),size_offset); } (void) WriteBlobMSBLong(image,0); /* user mask data */ /* Write composite image. */ if (status != MagickFalse) { CompressionType compression; compression=image->compression; if (image_info->compression != UndefinedCompression) image->compression=image_info->compression; if (image->compression == ZipCompression) image->compression=RLECompression; if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse, exception) == 0) status=MagickFalse; image->compression=compression; } (void) CloseBlob(image); return(status); }
GB_unop__exp2_fc32_fc32.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__exp2_fc32_fc32) // op(A') function: GB (_unop_tran__exp2_fc32_fc32) // C type: GxB_FC32_t // A type: GxB_FC32_t // cast: GxB_FC32_t cij = aij // unaryop: cij = GB_cexp2f (aij) #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_t // 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 = GB_cexp2f (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] = GB_cexp2f (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_EXP2 || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__exp2_fc32_fc32) ( GxB_FC32_t *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] = GB_cexp2f (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] = GB_cexp2f (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__exp2_fc32_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
sumProductSparseC.c
#include <mex.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <omp.h> void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double* prediction = mxGetPr(prhs[0]); /* containts evaluated appearance models for all pixel in that BScan and all boundary models */ double* mu = mxGetPr(prhs[1]); double* WML = mxGetPr(prhs[2]); double sigmaML = (double) mxGetScalar(prhs[3]); int* idxA = (int*) mxGetData(prhs[4]); double *hashTable = mxGetPr(prhs[5]); int* boundsPred = (int*) mxGetData(prhs[6]); /* int* idxRows = (int*) mxGetPr(prhs[4]); */ int M = mxGetN(prhs[2]); /* number of eigenmodes of the shape prior */ int N = mxGetM(prhs[2]); /* number of rows in WML */ int numColumns = mxGetNumberOfElements(prhs[4]); /* for each column in the shape prior model there is one index */ const int* dims = mxGetDimensions(prhs[0]); int numBounds = dims[1]; /* number of columns of pObs */ int numRows = mxGetM(prhs[0]); /* number of rows of pObs */ int numColumnsShape = (int) (double)N/(double)numBounds; /* for each column in the shape prior model there is one index */ /* only calculate pairiwse probabilities up to this precision */ double eps = pow(10,-25); double* gamma = NULL; /* return the probabilities for this B-Scan column */ int dimArray[3] = {numRows,numBounds,numColumns}; plhs[0] = mxCreateNumericArray(3,dimArray,mxDOUBLE_CLASS,mxREAL); gamma = mxGetPr(plhs[0]); #pragma omp parallel { double var_a_b, factor, mu_a, mu_b, prec_a_b, prec_a_a, evalDens, aTilde; double variance, varInv; double* prec = malloc(2*(numBounds-1)*sizeof(double)); double var1, var2, var3; double* alpha = malloc(numBounds*numRows*sizeof(double)); double* beta = malloc(numBounds*numRows*sizeof(double)); double* c = malloc(numBounds*sizeof(double)); double cInv, cTmp; double* prodTmp = malloc(numRows*sizeof(double)); int rowStart, rowEnd; int boundA, boundB; int numNotZero; int i,k,idx,column,predOffset; int muFloor, startVal, stopVal; double mu_b_a, mu_a_b, tmpVal, prec_a_aaTilde; #pragma omp for for (column=0; column < numColumns; column++) { /* for (column = 0; column < 1; column++) {*/ rowStart = boundsPred[column*2]; rowEnd = boundsPred[column*2+1]; memset(alpha,0,numRows*numBounds*sizeof(double)); memset(beta,0,numRows*numBounds*sizeof(double)); predOffset = numBounds*numRows*column; /* shifts the pointer inside the prediction matrix to the next BScan column */ /* calculate for the first boundary; calculate the 1-d shape marginal p(a) for column j on the fly */ /* calculate the variance for the shape prior density: \Sigma = WW^T + sigma^2I */ variance = 0; for (i=0; i < M; i++) { variance += WML[idxA[column] + i*N]*WML[idxA[column] + i*N]; } variance += sigmaML; varInv = -0.5/variance; factor = 1/sqrt(2*3.1415926535897*variance); cTmp = 0; for (i=rowStart; i < rowEnd+1; i++) { alpha[i] = factor*exp(varInv*(i+1 - mu[idxA[column]])*(i+1-mu[idxA[column]]))*prediction[i + predOffset]; cTmp += alpha[i]; } c[0] = cTmp; cInv = 1/cTmp; for (i=rowStart; i < rowEnd+1; i++) { alpha[i] = alpha[i]*cInv; } /* calculate the precision matrices required for conditional densities p(a|b) */ for (k=0; k < numBounds-1; k++) { var1 = 0; var2 = 0; var3 = 0; for (i=0; i < M; i++) { var1 += WML[idxA[column] + numColumnsShape*k + i*N]*WML[idxA[column] + numColumnsShape*k + i*N]; var2 += WML[idxA[column] + numColumnsShape*k + i*N]*WML[idxA[column] + numColumnsShape*(k+1) + i*N]; var3 += WML[idxA[column] + numColumnsShape*(k+1) + i*N]*WML[idxA[column] + numColumnsShape*(k+1) + i*N]; } var1 += sigmaML; var3 += sigmaML; factor = 1/(var1*var3 - var2*var2); prec[0 + k*2] = factor*(-var2); prec[1 + k*2] = factor*var1; } /* calculate the remaining boundaries */ for (k=1; k < numBounds; k++) { /* calculate parameters of distribution p(b|a); b is the boundary k-1; a is boundary k */ var_a_b = 1/prec[1 + (k-1)*2]; /* for the conditional density, variance is given by the inverse precision matrix */ factor = 1/sqrt(2*3.1415926535897*var_a_b); /* calulate the number of elements larger than eps for each row */ cTmp = 0; mu_b = mu[idxA[column] + numColumnsShape*(k-1)]; mu_a = mu[idxA[column] + numColumnsShape*k]; prec_a_b = prec[0 + (k-1)*2]; prec_a_a = prec[1 + (k-1)*2]; aTilde = prec_a_b/prec_a_a; prec_a_aaTilde = 0.5*(1/prec_a_a)*prec_a_b*prec_a_b; numNotZero = (int) ceil(abs(sqrt(-log(eps*factor)*2*var_a_b)/aTilde)); /* value of boundary k */ for (boundA = rowStart+1; boundA <= rowEnd; boundA++) { mu_b_a = ((mu_a - boundA)/aTilde + mu_b); muFloor = (int) mu_b_a; /* the position of boundary k-1 can lie between 1 and boundary k and is constrained to lie within 2*numNotZero + 1 around its mean mu_b_a */ startVal = (muFloor-numNotZero < rowStart+1) ? rowStart+1 : muFloor - numNotZero; stopVal = (muFloor+numNotZero > boundA) ? boundA : muFloor + numNotZero; tmpVal = 0; /* value of boundary k-1 */ for (boundB = startVal; boundB <= stopVal; boundB++) { /* evaluate the conditional density; but only the part inside the exp function */ evalDens = -(boundB-mu_b_a)*(boundB-mu_b_a)*prec_a_aaTilde; evalDens = hashTable[(int)(-evalDens*1000 + 0.5)]; tmpVal += factor*evalDens*alpha[boundB-1+numRows*(k-1)]; } alpha[boundA-1+numRows*k] = tmpVal*prediction[boundA-1+numRows*k + predOffset]; cTmp += alpha[boundA-1+numRows*k]; } /* normalize alpha */ c[k] = cTmp; cInv = 1/cTmp; for (i=rowStart; i < rowEnd+1; i++) { alpha[i+numRows*k] = alpha[i+numRows*k]*cInv; } } /* initialize beta */ for (i=rowStart; i < rowEnd+1; i++) { idx = (numBounds-1)*numRows+i; beta[idx] = 1; gamma[idx + predOffset] = alpha[idx]*beta[idx]; } for (k=numBounds-1; k > 0; k--) { /* precalculate the product of pObs*beta(z_{n+1}) */ cInv = 1/c[k]; for (i=rowStart; i < rowEnd+1; i++) { prodTmp[i] = cInv*prediction[numRows*k+i + predOffset]*beta[numRows*k+i]; } var_a_b = 1/prec[1 + (k-1)*2]; /* for the conditional density, variance is given by the inverse precision matrix */ factor = 1/sqrt(2*3.1415926535897*var_a_b); /* calulate the number of elements larger than eps for each row */ numNotZero = (int) ceil(sqrt(-log(eps*factor)*2*var_a_b)); cTmp = 0; mu_b = mu[idxA[column] + numColumnsShape*(k-1)]; mu_a = mu[idxA[column] + numColumnsShape*k]; prec_a_b = prec[0 + (k-1)*2]; prec_a_a = prec[1 + (k-1)*2]*0.5; for (boundB = rowStart+1; boundB <= rowEnd; boundB++) { mu_a_b = mu_a - var_a_b*prec_a_b*(boundB-mu_b); muFloor = (int) mu_a_b; /* position of boundary k (called here boundA) */ /* check for all possible values of boundB in this row: has to be at least boundA, can be at most numRows and we limit it to be not further away from muFloor than numNotZero */ startVal = (muFloor-numNotZero < boundB) ? boundB : muFloor - numNotZero; stopVal = (muFloor+numNotZero > rowEnd) ? rowEnd : muFloor + numNotZero; tmpVal = 0; for (boundA = startVal; boundA <= stopVal; boundA++) { evalDens = -(boundA-mu_a_b)*(boundA-mu_a_b)*prec_a_a; evalDens = hashTable[(int)(-evalDens*1000 + 0.5)]; tmpVal += factor*evalDens*prodTmp[boundA-1]; } idx = boundB-1+numRows*(k-1); beta[idx] = tmpVal; gamma[idx + predOffset] = beta[idx]*alpha[idx]; } } } free(alpha); free(beta); free(prodTmp); free(prec); free(c); } }
3d25pt_var.c
/* * Order-1, 3D 25 point stencil with axis-symmetric ariable 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])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } 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***)*13); for(m=0; m<13;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] = 16; tile_size[1] = 16; tile_size[2] = 24; tile_size[3] = 1024; 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<13; 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; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; 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 ] + A[(t)%2][i+1][j ][k ]) + coef[2][i][j][k] * (A[(t)%2][i ][j-1][k ] + A[(t)%2][i ][j+1][k ]) + coef[3][i][j][k] * (A[(t)%2][i ][j ][k-1] + A[(t)%2][i ][j ][k+1]) + coef[4][i][j][k] * (A[(t)%2][i-2][j ][k ] + A[(t)%2][i+2][j ][k ]) + coef[5][i][j][k] * (A[(t)%2][i ][j-2][k ] + A[(t)%2][i ][j+2][k ]) + coef[6][i][j][k] * (A[(t)%2][i ][j ][k-2] + A[(t)%2][i ][j ][k+2]) + coef[7][i][j][k] * (A[(t)%2][i-3][j ][k ] + A[(t)%2][i+3][j ][k ]) + coef[8][i][j][k] * (A[(t)%2][i ][j-3][k ] + A[(t)%2][i ][j+3][k ]) + coef[9][i][j][k] * (A[(t)%2][i ][j ][k-3] + A[(t)%2][i ][j ][k+3]) + coef[10][i][j][k]* (A[(t)%2][i-4][j ][k ] + A[(t)%2][i+4][j ][k ]) + coef[11][i][j][k]* (A[(t)%2][i ][j-4][k ] + A[(t)%2][i ][j+4][k ]) + coef[12][i][j][k]* (A[(t)%2][i ][j ][k-4] + A[(t)%2][i ][j ][k+4]) ; } } } } #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(4, "variable axis-symmetric") #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<13;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; }
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 <random> #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, std::mt19937 &rnd_engine) { // NOLINT(runtime/references) 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; 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) { std::uniform_real_distribution<float> distribution(0, 1); for (index_t j = 0; j < T * N * H * D; j++) { if (distribution(rnd_engine) < 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, std::mt19937 &rnd_engine) { // NOLINT(runtime/references) 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; 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) { std::uniform_real_distribution<float> distribution(0, 1); for (index_t i = 0; i < T * N * I; i++) { if (distribution(rnd_engine) < 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, std::mt19937 &rnd_engine) { // NOLINT(runtime/references) 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(); 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) { std::uniform_real_distribution<float> distribution(0, 1); for (index_t i = 0; i < T * N * I; i++) { if (distribution(rnd_engine) < 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_
critical-2.c
int i; void foo (int j) { #pragma omp critical (foo) hint (j + 1) /* { dg-error "constant integer expression" } */ i = i + 1; #pragma omp critical (foo),hint(j) /* { dg-error "constant integer expression" } */ i = i + 1; }
omp-task.simple.c
#include <stdio.h> int main() { int x = 10, i = 0; #pragma omp parallel { printf("x par = %d\n", x); printf("i par = %d\n", i); } printf("final x = %d\n", x); return 0; }
tasker.h
#pragma once #include <string> #include <omp.h> #include "momentum-solvers/amr_momentum_solver.h" #include "spatial-solvers/amr_spatial_solver.h" namespace vlv{ inline void step_location( corgi::Grid<1>& grid ) { #pragma omp parallel { #pragma omp single { for(auto cid : grid.get_tile_ids() ){ #pragma omp task { auto& tile = dynamic_cast<vlv::Tile<1>&>(grid.get_tile( cid )); //vlasov::AmrSpatialLagrangianSolver<Realf> ssol; //ssol.solve(tile, grid); tile.step_location(grid); }// end of omp task } }// end of omp single }// end of omp parallel } template<int V> void initial_step( corgi::Grid<1>& grid ) { vlv::AmrMomentumLagrangianSolver<Realf,1,V> vsol; #pragma omp parallel { #pragma omp single { for(auto cid : grid.get_tile_ids() ){ #pragma omp task firstprivate(vsol) { auto& tile = dynamic_cast<vlv::Tile<1>&>(grid.get_tile( cid )); vsol.solve(tile, -0.5); }// end of omp task } }// end of omp single #pragma omp taskwait }// end of omp parallel } template<int V> void step_velocity( corgi::Grid<1>& grid ) { vlv::AmrMomentumLagrangianSolver<Realf,1,V> vsol; #pragma omp parallel { #pragma omp single { for(auto cid : grid.get_tile_ids() ){ #pragma omp task firstprivate(vsol) { auto& tile = dynamic_cast<vlv::Tile<1>&>(grid.get_tile( cid )); vsol.solve(tile); }// end of omp task } }// end of omp single }// end of omp parallel } template<int V> void step_velocity_with_gravity( corgi::Grid<1>& grid, Realf g0, Realf Lx ) { vlv::GravityAmrMomentumLagrangianSolver<Realf,1,V> vsol(g0, Lx); #pragma omp parallel { #pragma omp single { for(auto cid : grid.get_tile_ids() ){ #pragma omp task firstprivate(vsol) { auto& tile = dynamic_cast<vlv::Tile<1>&>(grid.get_tile( cid )); vsol.solve(tile); }// end of omp task } }// end of omp single }// end of omp parallel } //inline void analyze( corgi::Grid<1>& grid ) //{ // vlv::Analyzator<Realf> analyzator; // // #pragma omp parallel // { // #pragma omp single // { // // for(auto cid : grid.get_local_tiles()) { // #pragma omp task firstprivate(analyzator) // { // auto& tile // = dynamic_cast<vlv::Tile<1>&>(grid.get_tile( cid )); // analyzator.analyze(tile); // }// end of omp task // } // // // }// end of omp single // }// end of omp parallel // //} }// end of namespace vlv
filter.c
/* Copyright (c) 2016, NVIDIA CORPORATION. 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 NVIDIA 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 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. */ #define MAX(X,Y) ((X>Y) ? X:Y) #define MIN(X,Y) ((X<Y) ? X:Y) void blur5(unsigned restrict char *imgData, unsigned restrict char *out, long w, long h, long ch, long step) { long x, y; const int filtersize = 5; double filter[5][5] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 2, 3, 2, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1 }; // The denominator for scale should be the sum // of non-zero elements in the filter. float scale = 1.0 / 35.0; #pragma acc parallel loop collapse(2) gang vector copyin(imgData[0:w * h * ch]) copyout(out[0:w * h * ch]) for ( y = 0; y < h; y++ ) { for ( x = 0; x < w; x++ ) { float blue = 0.0, green = 0.0, red = 0.0; for ( int fy = 0; fy < filtersize; fy++ ) { long iy = y - (filtersize/2) + fy; for ( int fx = 0; fx < filtersize; fx++ ) { long ix = x - (filtersize/2) + fx; if ( (iy<0) || (ix<0) || (iy>=h) || (ix>=w) ) continue; blue += filter[fy][fx] * (float)imgData[iy * step + ix * ch]; green += filter[fy][fx] * (float)imgData[iy * step + ix * ch + 1]; red += filter[fy][fx] * (float)imgData[iy * step + ix * ch + 2]; } } out[y * step + x * ch] = 255 - (scale * blue); out[y * step + x * ch + 1 ] = 255 - (scale * green); out[y * step + x * ch + 2 ] = 255 - (scale * red); } } } void blur5_blocked(unsigned restrict char *imgData, unsigned restrict char *out, long w, long h, long ch, long step) { long x, y; const int filtersize = 5, nblocks = 8; double filter[5][5] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 2, 3, 2, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1 }; // The denominator for scale should be the sum // of non-zero elements in the filter. float scale = 1.0 / 35.0; long blocksize = h/ nblocks; #pragma acc data copyin(imgData[:w*h*ch],filter)copyout(out[:w*h*ch]) for ( long blocky = 0; blocky < nblocks; blocky++) { // For data copies we need to include the ghost zones for the filter long starty = blocky * blocksize; long endy = starty + blocksize; #pragma acc parallel loop collapse(2) gang vector for ( y = starty; y < endy; y++ ) { for ( x = 0; x < w; x++ ) { float blue = 0.0, green = 0.0, red = 0.0; for ( int fy = 0; fy < filtersize; fy++ ) { long iy = y - (filtersize/2) + fy; for ( int fx = 0; fx < filtersize; fx++ ) { long ix = x - (filtersize/2) + fx; if ( (iy<0) || (ix<0) || (iy>=h) || (ix>=w) ) continue; blue += filter[fy][fx] * (float)imgData[iy * step + ix * ch]; green += filter[fy][fx] * (float)imgData[iy * step + ix * ch + 1]; red += filter[fy][fx] * (float)imgData[iy * step + ix * ch + 2]; } } out[y * step + x * ch] = 255 - (scale * blue); out[y * step + x * ch + 1 ] = 255 - (scale * green); out[y * step + x * ch + 2 ] = 255 - (scale * red); } } } } void blur5_update(unsigned restrict char *imgData, unsigned restrict char *out, long w, long h, long ch, long step) { long x, y; const int filtersize = 5, nblocks = 8; double filter[5][5] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 2, 3, 2, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1 }; // The denominator for scale should be the sum // of non-zero elements in the filter. float scale = 1.0 / 35.0; long blocksize = h/ nblocks; #pragma acc data create(imgData[w*step],out[w*step]) copyin(filter) { for ( long blocky = 0; blocky < nblocks; blocky++) { // For data copies we need to include the ghost zones for the filter long starty = MAX(0,blocky * blocksize - filtersize/2); long endy = MIN(h,starty + blocksize + filtersize/2); #pragma acc update device(imgData[starty*step:(endy-starty)*step]) starty = blocky * blocksize; endy = starty + blocksize; #pragma acc parallel loop collapse(2) gang vector for ( y = starty; y < endy; y++ ) { for ( x = 0; x < w; x++ ) { float blue = 0.0, green = 0.0, red = 0.0; for ( int fy = 0; fy < filtersize; fy++ ) { long iy = y - (filtersize/2) + fy; for ( int fx = 0; fx < filtersize; fx++ ) { long ix = x - (filtersize/2) + fx; if ( (iy<0) || (ix<0) || (iy>=h) || (ix>=w) ) continue; blue += filter[fy][fx] * (float)imgData[iy * step + ix * ch]; green += filter[fy][fx] * (float)imgData[iy * step + ix * ch + 1]; red += filter[fy][fx] * (float)imgData[iy * step + ix * ch + 2]; } } out[y * step + x * ch] = 255 - (scale * blue); out[y * step + x * ch + 1 ] = 255 - (scale * green); out[y * step + x * ch + 2 ] = 255 - (scale * red); } } #pragma acc update self(out[starty*step:blocksize*step]) } } } void blur5_pipelined(unsigned restrict char *imgData, unsigned restrict char *out, long w, long h, long ch, long step) { long x, y; const int filtersize = 5, nblocks = 8; double filter[5][5] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 2, 3, 2, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1 }; // The denominator for scale should be the sum // of non-zero elements in the filter. float scale = 1.0 / 35.0; long blocksize = h/ nblocks; #pragma acc data create(imgData[w*step],out[w*step]) { for ( long blocky = 0; blocky < nblocks; blocky++) { // For data copies we need to include the ghost zones for the filter long starty = MAX(0,blocky * blocksize - filtersize/2); long endy = MIN(h,starty + blocksize + filtersize/2); #pragma acc update device(imgData[starty*step:(endy-starty)*step]) async(blocky%3+1) starty = blocky * blocksize; endy = starty + blocksize; #pragma acc parallel loop collapse(2) gang vector async(blocky%3+1) for ( y = starty; y < endy; y++ ) { for ( x = 0; x < w; x++ ) { float blue = 0.0, green = 0.0, red = 0.0; for ( int fy = 0; fy < filtersize; fy++ ) { long iy = y - (filtersize/2) + fy; for ( int fx = 0; fx < filtersize; fx++ ) { long ix = x - (filtersize/2) + fx; if ( (iy<0) || (ix<0) || (iy>=h) || (ix>=w) ) continue; blue += filter[fy][fx] * (float)imgData[iy * step + ix * ch]; green += filter[fy][fx] * (float)imgData[iy * step + ix * ch + 1]; red += filter[fy][fx] * (float)imgData[iy * step + ix * ch + 2]; } } out[y * step + x * ch] = 255 - (scale * blue); out[y * step + x * ch + 1 ] = 255 - (scale * green); out[y * step + x * ch + 2 ] = 255 - (scale * red); } } #pragma acc update self(out[starty*step:blocksize*step]) async(blocky%3+1) } #pragma acc wait } } #include <openacc.h> #include <omp.h> void blur5_pipelined_multi(unsigned restrict char *imgData, unsigned restrict char *out, long w, long h, long ch, long step) { const int filtersize = 5, nblocks = 32; double filter[5][5] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 2, 3, 2, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1 }; // The denominator for scale should be the sum // of non-zero elements in the filter. float scale = 1.0 / 35.0; long blocksize = h/ nblocks; #pragma omp parallel num_threads(acc_get_num_devices(acc_device_nvidia)) { int myid = omp_get_thread_num(); acc_set_device_num(myid,acc_device_nvidia); int queue = 1; #pragma acc data create(imgData[w*h*ch],out[w*h*ch]) { #pragma omp for schedule(static) for ( long blocky = 0; blocky < nblocks; blocky++) { // For data copies we need to include the ghost zones for the filter long starty = MAX(0,blocky * blocksize - filtersize/2); long endy = MIN(h,starty + blocksize + filtersize/2); #pragma acc update device(imgData[starty*step:(endy-starty)*step]) async(queue) starty = blocky * blocksize; endy = starty + blocksize; #pragma acc parallel loop collapse(2) gang vector async(queue) for ( long y = starty; y < endy; y++ ) { for ( long x = 0; x < w; x++ ) { float blue = 0.0, green = 0.0, red = 0.0; for ( int fy = 0; fy < filtersize; fy++ ) { long iy = y - (filtersize/2) + fy; for ( int fx = 0; fx < filtersize; fx++ ) { long ix = x - (filtersize/2) + fx; if ( (iy<0) || (ix<0) || (iy>=h) || (ix>=w) ) continue; blue += filter[fy][fx] * (float)imgData[iy * step + ix * ch]; green += filter[fy][fx] * (float)imgData[iy * step + ix * ch + 1]; red += filter[fy][fx] * (float)imgData[iy * step + ix * ch + 2]; } } out[y * step + x * ch] = 255 - (scale * blue); out[y * step + x * ch + 1 ] = 255 - (scale * green); out[y * step + x * ch + 2 ] = 255 - (scale * red); } } #pragma acc update self(out[starty*step:blocksize*step]) async(queue) queue = (queue%3)+1; } #pragma acc wait } } }
filter.c
/* Copyright 2015-2017. The Regents of the University of California. * Copyright 2016-2017. Martin Uecker. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. * * Authors: * 2012-2017 Martin Uecker <martin.uecker@med.uni-goettingen.de> * 2017 Jon Tamir <jtamir@eecs.berkeley.edu> */ #include <assert.h> #include <stdlib.h> #include <complex.h> #include <math.h> #include <strings.h> #include "num/multind.h" #include "num/flpmath.h" #include "num/loop.h" #include "misc/misc.h" #include "misc/nested.h" #include "filter.h" static int cmp_float(const void* a, const void* b) { return (*(float*)a - *(float*)b > 0.) ? 1. : -1.; } static int cmp_complex_float(const void* a, const void* b) // gives sign for 0. (not 0) { return (cabsf(*(complex float*)a) - cabsf(*(complex float*)b) > 0.) ? 1. : -1.; } static void sort_floats(int N, float ar[N]) { qsort((void*)ar, N, sizeof(float), cmp_float); } static void sort_complex_floats(int N, complex float ar[N]) { qsort((void*)ar, N, sizeof(complex float), cmp_complex_float); } float median_float(int N, const float ar[N]) { float tmp[N]; memcpy(tmp, ar, N * sizeof(float)); sort_floats(N, tmp); return (1 == N % 2) ? tmp[(N - 1) / 2] : ((tmp[(N - 1) / 2 + 0] + tmp[(N - 1) / 2 + 1]) / 2.); } complex float median_complex_float(int N, const complex float ar[N]) { complex float tmp[N]; memcpy(tmp, ar, N * sizeof(complex float)); sort_complex_floats(N, tmp); return (1 == N % 2) ? tmp[(N - 1) / 2] : ((tmp[(N - 1) / 2 + 0] + tmp[(N - 1) / 2 + 1]) / 2.); } void md_medianz2(int D, int M, const long dim[D], const long ostr[D], complex float* optr, const long istr[D], const complex float* iptr) { assert(M < D); const long* nstr[2] = { ostr, istr }; void* nptr[2] = { optr, (void*)iptr }; long length = dim[M]; long stride = istr[M]; long dim2[D]; for (int i = 0; i < D; i++) dim2[i] = dim[i]; dim2[M] = 1; NESTED(void, nary_medianz, (void* ptr[])) { complex float tmp[length]; for (long i = 0; i < length; i++) tmp[i] = *((complex float*)(ptr[1] + i * stride)); *(complex float*)ptr[0] = median_complex_float(length, tmp); }; md_nary(2, D, dim2, nstr, nptr, nary_medianz); } void md_medianz(int D, int M, const long dim[D], complex float* optr, const complex float* iptr) { assert(M < D); long dim2[D]; for (int i = 0; i < D; i++) dim2[i] = dim[i]; dim2[M] = 1; long istr[D]; long ostr[D]; md_calc_strides(D, istr, dim, 8); md_calc_strides(D, ostr, dim2, 8); md_medianz2(D, M, dim, ostr, optr, istr, iptr); } void centered_gradient(unsigned int N, const long dims[N], const complex float grad[N], complex float* out) { md_zgradient(N, dims, out, grad); long dims0[N]; md_singleton_dims(N, dims0); long strs0[N]; md_calc_strides(N, strs0, dims0, CFL_SIZE); complex float cn = 0.; for (unsigned int n = 0; n < N; n++) cn -= grad[n] * (float)dims[n] / 2.; long strs[N]; md_calc_strides(N, strs, dims, CFL_SIZE); md_zadd2(N, dims, strs, out, strs, out, strs0, &cn); } void linear_phase(unsigned int N, const long dims[N], const float pos[N], complex float* out) { complex float grad[N]; for (unsigned int n = 0; n < N; n++) grad[n] = 2.i * M_PI * (float)(pos[n]) / ((float)dims[n]); centered_gradient(N, dims, grad, out); md_zmap(N, dims, out, out, cexpf); } void klaplace_scaled(unsigned int N, const long dims[N], unsigned int flags, const float sc[N], complex float* out) { unsigned int flags2 = flags; complex float* tmp = md_alloc(N, dims, CFL_SIZE); md_clear(N, dims, out, CFL_SIZE); for (unsigned int i = 0; i < bitcount(flags); i++) { unsigned int lsb = ffs(flags2) - 1; flags2 = MD_CLEAR(flags2, lsb); complex float grad[N]; for (unsigned int j = 0; j < N; j++) grad[j] = 0.; grad[lsb] = sc[lsb]; centered_gradient(N, dims, grad, tmp); md_zspow(N, dims, tmp, tmp, 2.); md_zadd(N, dims, out, out, tmp); } md_free(tmp); } void klaplace(unsigned int N, const long dims[N], unsigned int flags, complex float* out) { float sc[N]; for (unsigned int j = 0; j < N; j++) sc[j] = 1. / (float)dims[j]; klaplace_scaled(N, dims, flags, sc, out); } static void nary_zwindow(const long N, const float alpha, const float beta, complex float* ptr) { if (1 == N) { ptr[0] = 1.; return; } #pragma omp parallel for for (long i = 0; i < N; i++) ptr[i] = alpha - beta * cosf(2. * M_PI * i / (N - 1)); } static void nary_zhamming(const long N, complex float* ptr) { #if 0 const float alpha = 0.53836; const float beta = 0.46164; #else const float alpha = 0.54; const float beta = 0.46; #endif return nary_zwindow(N, alpha, beta, ptr); } static void nary_zhann(const long N, complex float* ptr) { const float alpha = 0.5; const float beta = 0.5; return nary_zwindow(N, alpha, beta, ptr); } enum window_type { WINDOW_HAMMING, WINDOW_HANN }; static void md_zwindow2(unsigned int D, const long dims[D], unsigned int flags, const long ostrs[D], complex float* optr, const long istrs[D], const complex float* iptr, enum window_type wt) { if (0 == flags) { md_copy2(D, dims, ostrs, optr, istrs, iptr, CFL_SIZE); return; } // process first flagged dimension unsigned int lsb = ffs(flags) - 1; long win_dims[D]; long win_strs[D]; md_select_dims(D, MD_BIT(lsb), win_dims, dims); md_calc_strides(D, win_strs, win_dims, CFL_SIZE); complex float* win = md_alloc_sameplace(D, win_dims, CFL_SIZE, iptr); switch (wt) { case WINDOW_HAMMING: nary_zhamming(dims[lsb], win); break; case WINDOW_HANN: nary_zhann(dims[lsb], win); break; }; md_zmul2(D, dims, ostrs, optr, istrs, iptr, win_strs, win); md_free(win); flags = MD_CLEAR(flags, lsb); // process other dimensions if (0 != flags) md_zwindow2(D, dims, flags, ostrs, optr, ostrs, optr, wt); return; } #if 0 static void md_zwindow(const unsigned int D, const long dims[D], const long flags, complex float* optr, const complex float* iptr, bool hamming) { long strs[D]; md_calc_strides(D, strs, dims, CFL_SIZE); md_zwindow2(D, dims, flags, strs, optr, strs, iptr, hamming); } #endif /* * Apply Hamming window to iptr along flags */ void md_zhamming(const unsigned int D, const long dims[D], const long flags, complex float* optr, const complex float* iptr) { long strs[D]; md_calc_strides(D, strs, dims, CFL_SIZE); return md_zhamming2(D, dims, flags, strs, optr, strs, iptr); } /* * Apply Hamming window to iptr along flags (with strides) */ void md_zhamming2(const unsigned int D, const long dims[D], const long flags, const long ostrs[D], complex float* optr, const long istrs[D], const complex float* iptr) { return md_zwindow2(D, dims, flags, ostrs, optr, istrs, iptr, WINDOW_HAMMING); } /* * Apply Hann window to iptr along flags */ void md_zhann(const unsigned int D, const long dims[D], const long flags, complex float* optr, const complex float* iptr) { long strs[D]; md_calc_strides(D, strs, dims, CFL_SIZE); return md_zhann2(D, dims, flags, strs, optr, strs, iptr); } /* * Apply Hann window to iptr along flags (with strides) */ void md_zhann2(const unsigned int D, const long dims[D], const long flags, const long ostrs[D], complex float* optr, const long istrs[D], const complex float* iptr) { return md_zwindow2(D, dims, flags, ostrs, optr, istrs, iptr, WINDOW_HANN); }
mg.c
/*-------------------------------------------------------------------- NAS Parallel Benchmarks 3.0 structured OpenMP C versions - MG This benchmark is an OpenMP C version of the NPB MG code. The OpenMP C 2.3 versions are derived by RWCP from the serial Fortran versions in "NPB 2.3-serial" developed by NAS. 3.0 translation is performed by the UVSQ. 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 OpenMP activities at RWCP is available at: http://pdplab.trc.rwcp.or.jp/pdperf/Omni/ Information on NAS Parallel Benchmarks 2.3 is available at: http://www.nas.nasa.gov/NAS/NPB/ --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- Authors: E. Barszcz P. Frederickson A. Woo M. Yarrow OpenMP C version: S. Satoh 3.0 structure translation: F. Conti --------------------------------------------------------------------*/ #include "npb-C.h" #include "globals.h" /* parameters */ #define T_BENCH 1 #define T_INIT 2 /* global variables */ /* common /grid/ */ static int is1, is2, is3, ie1, ie2, ie3; /* functions prototypes */ static void setup(int *n1, int *n2, int *n3, int lt); static void mg3P(double ****u, double ***v, double ****r, double a[4], double c[4], int n1, int n2, int n3, int k); static void psinv( double ***r, double ***u, int n1, int n2, int n3, double c[4], int k); static void resid( double ***u, double ***v, double ***r, int n1, int n2, int n3, double a[4], int k ); static void rprj3( double ***r, int m1k, int m2k, int m3k, double ***s, int m1j, int m2j, int m3j, int k ); static void interp( double ***z, int mm1, int mm2, int mm3, double ***u, int n1, int n2, int n3, int k ); static void norm2u3(double ***r, int n1, int n2, int n3, double *rnm2, double *rnmu, int nx, int ny, int nz); static void rep_nrm(double ***u, int n1, int n2, int n3, char *title, int kk); static void comm3(double ***u, int n1, int n2, int n3, int kk); static void zran3(double ***z, int n1, int n2, int n3, int nx, int ny, int k); static void showall(double ***z, int n1, int n2, int n3); static double power( double a, int n ); static void bubble( double ten[M][2], int j1[M][2], int j2[M][2], int j3[M][2], int m, int ind ); static void zero3(double ***z, int n1, int n2, int n3); static void nonzero(double ***z, int n1, int n2, int n3); /*-------------------------------------------------------------------- program mg c-------------------------------------------------------------------*/ int main(int argc, char *argv[]) { /*------------------------------------------------------------------------- c k is the current level. It is passed down through subroutine args c and is NOT global. it is the current iteration c------------------------------------------------------------------------*/ int k, it; double t, tinit, mflops; int nthreads = 1; /*------------------------------------------------------------------------- c These arrays are in common because they are quite large c and probably shouldn't be allocated on the stack. They c are always passed as subroutine args. c------------------------------------------------------------------------*/ double ****u, ***v, ****r; double a[4], c[4]; double rnm2, rnmu; double epsilon = 1.0e-8; int n1, n2, n3, nit; double verify_value; boolean verified; int i, j, l; FILE *fp; timer_clear(T_BENCH); timer_clear(T_INIT); timer_start(T_INIT); /*---------------------------------------------------------------------- c Read in and broadcast input data c---------------------------------------------------------------------*/ printf("\n\n NAS Parallel Benchmarks 3.0 structured OpenMP C version" " - MG Benchmark\n\n"); fp = fopen("mg.input", "r"); if (fp != NULL) { printf(" Reading from input file mg.input\n"); fscanf(fp, "%d", &lt); while(fgetc(fp) != '\n'); fscanf(fp, "%d%d%d", &nx[lt], &ny[lt], &nz[lt]); while(fgetc(fp) != '\n'); fscanf(fp, "%d", &nit); while(fgetc(fp) != '\n'); for (i = 0; i <= 7; i++) { fscanf(fp, "%d", &debug_vec[i]); } fclose(fp); } else { printf(" No input file. Using compiled defaults\n"); lt = LT_DEFAULT; nit = NIT_DEFAULT; nx[lt] = NX_DEFAULT; ny[lt] = NY_DEFAULT; nz[lt] = NZ_DEFAULT; for (i = 0; i <= 7; i++) { debug_vec[i] = DEBUG_DEFAULT; } } if ( (nx[lt] != ny[lt]) || (nx[lt] != nz[lt]) ) { Class = 'U'; } else if( nx[lt] == 32 && nit == 4 ) { Class = 'S'; } else if( nx[lt] == 64 && nit == 40 ) { Class = 'W'; } else if( nx[lt] == 256 && nit == 20 ) { Class = 'B'; } else if( nx[lt] == 512 && nit == 20 ) { Class = 'C'; } else if( nx[lt] == 256 && nit == 4 ) { Class = 'A'; } else { Class = 'U'; } /*-------------------------------------------------------------------- c Use these for debug info: c--------------------------------------------------------------------- c debug_vec(0) = 1 !=> report all norms c debug_vec(1) = 1 !=> some setup information c debug_vec(1) = 2 !=> more setup information c debug_vec(2) = k => at level k or below, show result of resid c debug_vec(3) = k => at level k or below, show result of psinv c debug_vec(4) = k => at level k or below, show result of rprj c debug_vec(5) = k => at level k or below, show result of interp c debug_vec(6) = 1 => (unused) c debug_vec(7) = 1 => (unused) c-------------------------------------------------------------------*/ a[0] = -8.0/3.0; a[1] = 0.0; a[2] = 1.0/6.0; a[3] = 1.0/12.0; if (Class == 'A' || Class == 'S' || Class =='W') { /*-------------------------------------------------------------------- c Coefficients for the S(a) smoother c-------------------------------------------------------------------*/ c[0] = -3.0/8.0; c[1] = 1.0/32.0; c[2] = -1.0/64.0; c[3] = 0.0; } else { /*-------------------------------------------------------------------- c Coefficients for the S(b) smoother c-------------------------------------------------------------------*/ c[0] = -3.0/17.0; c[1] = 1.0/33.0; c[2] = -1.0/61.0; c[3] = 0.0; } lb = 1; setup(&n1,&n2,&n3,lt); u = (double ****)malloc((lt+1)*sizeof(double ***)); for (l = lt; l >=1; l--) { u[l] = (double ***)malloc(m3[l]*sizeof(double **)); for (k = 0; k < m3[l]; k++) { u[l][k] = (double **)malloc(m2[l]*sizeof(double *)); for (j = 0; j < m2[l]; j++) { u[l][k][j] = (double *)malloc(m1[l]*sizeof(double)); } } } v = (double ***)malloc(m3[lt]*sizeof(double **)); for (k = 0; k < m3[lt]; k++) { v[k] = (double **)malloc(m2[lt]*sizeof(double *)); for (j = 0; j < m2[lt]; j++) { v[k][j] = (double *)malloc(m1[lt]*sizeof(double)); } } r = (double ****)malloc((lt+1)*sizeof(double ***)); for (l = lt; l >=1; l--) { r[l] = (double ***)malloc(m3[l]*sizeof(double **)); for (k = 0; k < m3[l]; k++) { r[l][k] = (double **)malloc(m2[l]*sizeof(double *)); for (j = 0; j < m2[l]; j++) { r[l][k][j] = (double *)malloc(m1[l]*sizeof(double)); } } } zero3(u[lt],n1,n2,n3); zran3(v,n1,n2,n3,nx[lt],ny[lt],lt); norm2u3(v,n1,n2,n3,&rnm2,&rnmu,nx[lt],ny[lt],nz[lt]); /* printf("\n norms of random v are\n"); printf(" %4d%19.12e%19.12e\n", 0, rnm2, rnmu); printf(" about to evaluate resid, k= %d\n", lt);*/ printf(" Size: %3dx%3dx%3d (class %1c)\n", nx[lt], ny[lt], nz[lt], Class); printf(" Iterations: %3d\n", nit); resid(u[lt],v,r[lt],n1,n2,n3,a,lt); norm2u3(r[lt],n1,n2,n3,&rnm2,&rnmu,nx[lt],ny[lt],nz[lt]); /*c--------------------------------------------------------------------- c One iteration for startup c---------------------------------------------------------------------*/ mg3P(u,v,r,a,c,n1,n2,n3,lt); resid(u[lt],v,r[lt],n1,n2,n3,a,lt); setup(&n1,&n2,&n3,lt); zero3(u[lt],n1,n2,n3); zran3(v,n1,n2,n3,nx[lt],ny[lt],lt); timer_stop(T_INIT); timer_start(T_BENCH); resid(u[lt],v,r[lt],n1,n2,n3,a,lt); norm2u3(r[lt],n1,n2,n3,&rnm2,&rnmu,nx[lt],ny[lt],nz[lt]); for ( it = 1; it <= nit; it++) { mg3P(u,v,r,a,c,n1,n2,n3,lt); resid(u[lt],v,r[lt],n1,n2,n3,a,lt); } norm2u3(r[lt],n1,n2,n3,&rnm2,&rnmu,nx[lt],ny[lt],nz[lt]); #pragma omp parallel { #if defined(_OPENMP) #pragma omp master nthreads = omp_get_num_threads(); #endif /* _OPENMP */ } /* end parallel */ timer_stop(T_BENCH); t = timer_read(T_BENCH); tinit = timer_read(T_INIT); verified = FALSE; verify_value = 0.0; printf(" Initialization time: %15.3f seconds\n", tinit); printf(" Benchmark completed\n"); if (Class != 'U') { if (Class == 'S') { verify_value = 0.530770700573e-04; } else if (Class == 'W') { verify_value = 0.250391406439e-17; /* 40 iterations*/ /* 0.183103168997d-044 iterations*/ } else if (Class == 'A') { verify_value = 0.2433365309e-5; } else if (Class == 'B') { verify_value = 0.180056440132e-5; } else if (Class == 'C') { verify_value = 0.570674826298e-06; } if ( fabs( rnm2 - verify_value ) <= epsilon ) { verified = TRUE; printf(" VERIFICATION SUCCESSFUL\n"); printf(" L2 Norm is %20.12e\n", rnm2); printf(" Error is %20.12e\n", rnm2 - verify_value); } else { verified = FALSE; printf(" VERIFICATION FAILED\n"); printf(" L2 Norm is %20.12e\n", rnm2); printf(" The correct L2 Norm is %20.12e\n", verify_value); } } else { verified = FALSE; printf(" Problem size unknown\n"); printf(" NO VERIFICATION PERFORMED\n"); } if ( t != 0.0 ) { int nn = nx[lt]*ny[lt]*nz[lt]; mflops = 58.*nit*nn*1.0e-6 / t; } else { mflops = 0.0; } c_print_results("MG", Class, nx[lt], ny[lt], nz[lt], nit, nthreads, t, mflops, " floating point", verified, NPBVERSION, COMPILETIME, CS1, CS2, CS3, CS4, CS5, CS6, CS7); } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void setup(int *n1, int *n2, int *n3, int lt) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ int k; for ( k = lt-1; k >= 1; k--) { nx[k] = nx[k+1]/2; ny[k] = ny[k+1]/2; nz[k] = nz[k+1]/2; } for (k = 1; k <= lt; k++) { m1[k] = nx[k]+2; m2[k] = nz[k]+2; m3[k] = ny[k]+2; } is1 = 1; ie1 = nx[lt]; *n1 = nx[lt]+2; is2 = 1; ie2 = ny[lt]; *n2 = ny[lt]+2; is3 = 1; ie3 = nz[lt]; *n3 = nz[lt]+2; if (debug_vec[1] >= 1 ) { printf(" in setup, \n"); printf(" lt nx ny nz n1 n2 n3 is1 is2 is3 ie1 ie2 ie3\n"); printf("%4d%4d%4d%4d%4d%4d%4d%4d%4d%4d%4d%4d%4d\n", lt,nx[lt],ny[lt],nz[lt],*n1,*n2,*n3,is1,is2,is3,ie1,ie2,ie3); } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void mg3P(double ****u, double ***v, double ****r, double a[4], double c[4], int n1, int n2, int n3, int k) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c multigrid V-cycle routine c-------------------------------------------------------------------*/ int j; /*-------------------------------------------------------------------- c down cycle. c restrict the residual from the find grid to the coarse c-------------------------------------------------------------------*/ for (k = lt; k >= lb+1; k--) { j = k-1; rprj3(r[k], m1[k], m2[k], m3[k], r[j], m1[j], m2[j], m3[j], k); } k = lb; /*-------------------------------------------------------------------- c compute an approximate solution on the coarsest grid c-------------------------------------------------------------------*/ zero3(u[k], m1[k], m2[k], m3[k]); psinv(r[k], u[k], m1[k], m2[k], m3[k], c, k); for (k = lb+1; k <= lt-1; k++) { j = k-1; /*-------------------------------------------------------------------- c prolongate from level k-1 to k c-------------------------------------------------------------------*/ zero3(u[k], m1[k], m2[k], m3[k]); interp(u[j], m1[j], m2[j], m3[j], u[k], m1[k], m2[k], m3[k], k); /*-------------------------------------------------------------------- c compute residual for level k c-------------------------------------------------------------------*/ resid(u[k], r[k], r[k], m1[k], m2[k], m3[k], a, k); /*-------------------------------------------------------------------- c apply smoother c-------------------------------------------------------------------*/ psinv(r[k], u[k], m1[k], m2[k], m3[k], c, k); } j = lt - 1; k = lt; interp(u[j], m1[j], m2[j], m3[j], u[lt], n1, n2, n3, k); resid(u[lt], v, r[lt], n1, n2, n3, a, k); psinv(r[lt], u[lt], n1, n2, n3, c, k); } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void psinv( double ***r, double ***u, int n1, int n2, int n3, double c[4], int k) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c psinv applies an approximate inverse as smoother: u = u + Cr c c This implementation costs 15A + 4M per result, where c A and M denote the costs of Addition and Multiplication. c Presuming coefficient c(3) is zero (the NPB assumes this, c but it is thus not a general case), 2A + 1M may be eliminated, c resulting in 13A + 3M. c Note that this vectorizes, and is also fine for cache c based machines. c-------------------------------------------------------------------*/ int i3, i2, i1; double r1[M], r2[M]; #pragma omp parallel for default(shared) private(i1,i2,i3,r1,r2) for (i3 = 1; i3 < n3-1; i3++) { for (i2 = 1; i2 < n2-1; i2++) { for (i1 = 0; i1 < n1; i1++) { r1[i1] = r[i3][i2-1][i1] + r[i3][i2+1][i1] + r[i3-1][i2][i1] + r[i3+1][i2][i1]; r2[i1] = r[i3-1][i2-1][i1] + r[i3-1][i2+1][i1] + r[i3+1][i2-1][i1] + r[i3+1][i2+1][i1]; } for (i1 = 1; i1 < n1-1; i1++) { u[i3][i2][i1] = u[i3][i2][i1] + c[0] * r[i3][i2][i1] + c[1] * ( r[i3][i2][i1-1] + r[i3][i2][i1+1] + r1[i1] ) + c[2] * ( r2[i1] + r1[i1-1] + r1[i1+1] ); /*-------------------------------------------------------------------- c Assume c(3) = 0 (Enable line below if c(3) not= 0) c--------------------------------------------------------------------- c > + c(3) * ( r2(i1-1) + r2(i1+1) ) c-------------------------------------------------------------------*/ } } } /*-------------------------------------------------------------------- c exchange boundary points c-------------------------------------------------------------------*/ comm3(u,n1,n2,n3,k); if (debug_vec[0] >= 1 ) { rep_nrm(u,n1,n2,n3," psinv",k); } if ( debug_vec[3] >= k ) { showall(u,n1,n2,n3); } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void resid( double ***u, double ***v, double ***r, int n1, int n2, int n3, double a[4], int k ) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c resid computes the residual: r = v - Au c c This implementation costs 15A + 4M per result, where c A and M denote the costs of Addition (or Subtraction) and c Multiplication, respectively. c Presuming coefficient a(1) is zero (the NPB assumes this, c but it is thus not a general case), 3A + 1M may be eliminated, c resulting in 12A + 3M. c Note that this vectorizes, and is also fine for cache c based machines. c-------------------------------------------------------------------*/ int i3, i2, i1; double u1[M], u2[M]; #pragma omp parallel for default(shared) private(i1,i2,i3,u1,u2) for (i3 = 1; i3 < n3-1; i3++) { for (i2 = 1; i2 < n2-1; i2++) { for (i1 = 0; i1 < n1; i1++) { u1[i1] = u[i3][i2-1][i1] + u[i3][i2+1][i1] + u[i3-1][i2][i1] + u[i3+1][i2][i1]; u2[i1] = u[i3-1][i2-1][i1] + u[i3-1][i2+1][i1] + u[i3+1][i2-1][i1] + u[i3+1][i2+1][i1]; } for (i1 = 1; i1 < n1-1; i1++) { r[i3][i2][i1] = v[i3][i2][i1] - a[0] * u[i3][i2][i1] /*-------------------------------------------------------------------- c Assume a(1) = 0 (Enable 2 lines below if a(1) not= 0) c--------------------------------------------------------------------- c > - a(1) * ( u(i1-1,i2,i3) + u(i1+1,i2,i3) c > + u1(i1) ) c-------------------------------------------------------------------*/ - a[2] * ( u2[i1] + u1[i1-1] + u1[i1+1] ) - a[3] * ( u2[i1-1] + u2[i1+1] ); } } } /*-------------------------------------------------------------------- c exchange boundary data c--------------------------------------------------------------------*/ comm3(r,n1,n2,n3,k); if (debug_vec[0] >= 1 ) { rep_nrm(r,n1,n2,n3," resid",k); } if ( debug_vec[2] >= k ) { showall(r,n1,n2,n3); } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void rprj3( double ***r, int m1k, int m2k, int m3k, double ***s, int m1j, int m2j, int m3j, int k ) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c rprj3 projects onto the next coarser grid, c using a trilinear Finite Element projection: s = r' = P r c c This implementation costs 20A + 4M per result, where c A and M denote the costs of Addition and Multiplication. c Note that this vectorizes, and is also fine for cache c based machines. c-------------------------------------------------------------------*/ int j3, j2, j1, i3, i2, i1, d1, d2, d3; double x1[M], y1[M], x2, y2; if (m1k == 3) { d1 = 2; } else { d1 = 1; } if (m2k == 3) { d2 = 2; } else { d2 = 1; } if (m3k == 3) { d3 = 2; } else { d3 = 1; } #pragma omp parallel for default(shared) private(j1,j2,j3,i1,i2,i3,x1,y1,x2,y2) for (j3 = 1; j3 < m3j-1; j3++) { i3 = 2*j3-d3; /*C i3 = 2*j3-1*/ for (j2 = 1; j2 < m2j-1; j2++) { i2 = 2*j2-d2; /*C i2 = 2*j2-1*/ for (j1 = 1; j1 < m1j; j1++) { i1 = 2*j1-d1; /*C i1 = 2*j1-1*/ x1[i1] = r[i3+1][i2][i1] + r[i3+1][i2+2][i1] + r[i3][i2+1][i1] + r[i3+2][i2+1][i1]; y1[i1] = r[i3][i2][i1] + r[i3+2][i2][i1] + r[i3][i2+2][i1] + r[i3+2][i2+2][i1]; } for (j1 = 1; j1 < m1j-1; j1++) { i1 = 2*j1-d1; /*C i1 = 2*j1-1*/ y2 = r[i3][i2][i1+1] + r[i3+2][i2][i1+1] + r[i3][i2+2][i1+1] + r[i3+2][i2+2][i1+1]; x2 = r[i3+1][i2][i1+1] + r[i3+1][i2+2][i1+1] + r[i3][i2+1][i1+1] + r[i3+2][i2+1][i1+1]; s[j3][j2][j1] = 0.5 * r[i3+1][i2+1][i1+1] + 0.25 * ( r[i3+1][i2+1][i1] + r[i3+1][i2+1][i1+2] + x2) + 0.125 * ( x1[i1] + x1[i1+2] + y2) + 0.0625 * ( y1[i1] + y1[i1+2] ); } } } comm3(s,m1j,m2j,m3j,k-1); if (debug_vec[0] >= 1 ) { rep_nrm(s,m1j,m2j,m3j," rprj3",k-1); } if (debug_vec[4] >= k ) { showall(s,m1j,m2j,m3j); } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void interp( double ***z, int mm1, int mm2, int mm3, double ***u, int n1, int n2, int n3, int k ) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c interp adds the trilinear interpolation of the correction c from the coarser grid to the current approximation: u = u + Qu' c c Observe that this implementation costs 16A + 4M, where c A and M denote the costs of Addition and Multiplication. c Note that this vectorizes, and is also fine for cache c based machines. Vector machines may get slightly better c performance however, with 8 separate "do i1" loops, rather than 4. c-------------------------------------------------------------------*/ int i3, i2, i1, d1, d2, d3, t1, t2, t3; /* c note that m = 1037 in globals.h but for this only need to be c 535 to handle up to 1024^3 c integer m c parameter( m=535 ) */ double z1[M], z2[M], z3[M]; if ( n1 != 3 && n2 != 3 && n3 != 3 ) { #pragma omp parallel for default(shared) private(i1,i2,i3,z1,z2,z3) for (i3 = 0; i3 < mm3-1; i3++) { for (i2 = 0; i2 < mm2-1; i2++) { for (i1 = 0; i1 < mm1; i1++) { z1[i1] = z[i3][i2+1][i1] + z[i3][i2][i1]; z2[i1] = z[i3+1][i2][i1] + z[i3][i2][i1]; z3[i1] = z[i3+1][i2+1][i1] + z[i3+1][i2][i1] + z1[i1]; } for (i1 = 0; i1 < mm1-1; i1++) { u[2*i3][2*i2][2*i1] = u[2*i3][2*i2][2*i1] +z[i3][i2][i1]; u[2*i3][2*i2][2*i1+1] = u[2*i3][2*i2][2*i1+1] +0.5*(z[i3][i2][i1+1]+z[i3][i2][i1]); } for (i1 = 0; i1 < mm1-1; i1++) { u[2*i3][2*i2+1][2*i1] = u[2*i3][2*i2+1][2*i1] +0.5 * z1[i1]; u[2*i3][2*i2+1][2*i1+1] = u[2*i3][2*i2+1][2*i1+1] +0.25*( z1[i1] + z1[i1+1] ); } for (i1 = 0; i1 < mm1-1; i1++) { u[2*i3+1][2*i2][2*i1] = u[2*i3+1][2*i2][2*i1] +0.5 * z2[i1]; u[2*i3+1][2*i2][2*i1+1] = u[2*i3+1][2*i2][2*i1+1] +0.25*( z2[i1] + z2[i1+1] ); } for (i1 = 0; i1 < mm1-1; i1++) { u[2*i3+1][2*i2+1][2*i1] = u[2*i3+1][2*i2+1][2*i1] +0.25* z3[i1]; u[2*i3+1][2*i2+1][2*i1+1] = u[2*i3+1][2*i2+1][2*i1+1] +0.125*( z3[i1] + z3[i1+1] ); } } } } else { if (n1 == 3) { d1 = 2; t1 = 1; } else { d1 = 1; t1 = 0; } if (n2 == 3) { d2 = 2; t2 = 1; } else { d2 = 1; t2 = 0; } if (n3 == 3) { d3 = 2; t3 = 1; } else { d3 = 1; t3 = 0; } #pragma omp parallel default(shared) private(i1,i2,i3) { #pragma omp for for ( i3 = d3; i3 <= mm3-1; i3++) { for ( i2 = d2; i2 <= mm2-1; i2++) { for ( i1 = d1; i1 <= mm1-1; i1++) { u[2*i3-d3-1][2*i2-d2-1][2*i1-d1-1] = u[2*i3-d3-1][2*i2-d2-1][2*i1-d1-1] +z[i3-1][i2-1][i1-1]; } for ( i1 = 1; i1 <= mm1-1; i1++) { u[2*i3-d3-1][2*i2-d2-1][2*i1-t1-1] = u[2*i3-d3-1][2*i2-d2-1][2*i1-t1-1] +0.5*(z[i3-1][i2-1][i1]+z[i3-1][i2-1][i1-1]); } } for ( i2 = 1; i2 <= mm2-1; i2++) { for ( i1 = d1; i1 <= mm1-1; i1++) { u[2*i3-d3-1][2*i2-t2-1][2*i1-d1-1] = u[2*i3-d3-1][2*i2-t2-1][2*i1-d1-1] +0.5*(z[i3-1][i2][i1-1]+z[i3-1][i2-1][i1-1]); } for ( i1 = 1; i1 <= mm1-1; i1++) { u[2*i3-d3-1][2*i2-t2-1][2*i1-t1-1] = u[2*i3-d3-1][2*i2-t2-1][2*i1-t1-1] +0.25*(z[i3-1][i2][i1]+z[i3-1][i2-1][i1] +z[i3-1][i2][i1-1]+z[i3-1][i2-1][i1-1]); } } } #pragma omp for nowait for ( i3 = 1; i3 <= mm3-1; i3++) { for ( i2 = d2; i2 <= mm2-1; i2++) { for ( i1 = d1; i1 <= mm1-1; i1++) { u[2*i3-t3-1][2*i2-d2-1][2*i1-d1-1] = u[2*i3-t3-1][2*i2-d2-1][2*i1-d1-1] +0.5*(z[i3][i2-1][i1-1]+z[i3-1][i2-1][i1-1]); } for ( i1 = 1; i1 <= mm1-1; i1++) { u[2*i3-t3-1][2*i2-d2-1][2*i1-t1-1] = u[2*i3-t3-1][2*i2-d2-1][2*i1-t1-1] +0.25*(z[i3][i2-1][i1]+z[i3][i2-1][i1-1] +z[i3-1][i2-1][i1]+z[i3-1][i2-1][i1-1]); } } for ( i2 = 1; i2 <= mm2-1; i2++) { for ( i1 = d1; i1 <= mm1-1; i1++) { u[2*i3-t3-1][2*i2-t2-1][2*i1-d1-1] = u[2*i3-t3-1][2*i2-t2-1][2*i1-d1-1] +0.25*(z[i3][i2][i1-1]+z[i3][i2-1][i1-1] +z[i3-1][i2][i1-1]+z[i3-1][i2-1][i1-1]); } for ( i1 = 1; i1 <= mm1-1; i1++) { u[2*i3-t3-1][2*i2-t2-1][2*i1-t1-1] = u[2*i3-t3-1][2*i2-t2-1][2*i1-t1-1] +0.125*(z[i3][i2][i1]+z[i3][i2-1][i1] +z[i3][i2][i1-1]+z[i3][i2-1][i1-1] +z[i3-1][i2][i1]+z[i3-1][i2-1][i1] +z[i3-1][i2][i1-1]+z[i3-1][i2-1][i1-1]); } } } } }//end #pragma omp parallel if (debug_vec[0] >= 1 ) { rep_nrm(z,mm1,mm2,mm3,"z: inter",k-1); rep_nrm(u,n1,n2,n3,"u: inter",k); } if ( debug_vec[5] >= k ) { showall(z,mm1,mm2,mm3); showall(u,n1,n2,n3); } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void norm2u3(double ***r, int n1, int n2, int n3, double *rnm2, double *rnmu, int nx, int ny, int nz) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c norm2u3 evaluates approximations to the L2 norm and the c uniform (or L-infinity or Chebyshev) norm, under the c assumption that the boundaries are periodic or zero. Add the c boundaries in with half weight (quarter weight on the edges c and eighth weight at the corners) for inhomogeneous boundaries. c-------------------------------------------------------------------*/ double s = 0.0; int i3, i2, i1, n; double a = 0.0, tmp = 0.0; n = nx*ny*nz; #pragma omp parallel for default(shared) private(i1,i2,i3,a) reduction(+:s) reduction(max:tmp) for (i3 = 1; i3 < n3-1; i3++) { for (i2 = 1; i2 < n2-1; i2++) { for (i1 = 1; i1 < n1-1; i1++) { s = s + r[i3][i2][i1] * r[i3][i2][i1]; a = fabs(r[i3][i2][i1]); if (a > tmp) tmp = a; } } } *rnmu = tmp; *rnm2 = sqrt(s/(double)n); } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void rep_nrm(double ***u, int n1, int n2, int n3, char *title, int kk) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c report on norm c-------------------------------------------------------------------*/ double rnm2, rnmu; norm2u3(u,n1,n2,n3,&rnm2,&rnmu,nx[kk],ny[kk],nz[kk]); printf(" Level%2d in %8s: norms =%21.14e%21.14e\n", kk, title, rnm2, rnmu); } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void comm3(double ***u, int n1, int n2, int n3, int kk) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c comm3 organizes the communication on all borders c-------------------------------------------------------------------*/ int i1, i2, i3; /* axis = 1 */ #pragma omp parallel default(shared) private(i1,i2,i3) { #pragma omp for for ( i3 = 1; i3 < n3-1; i3++) { for ( i2 = 1; i2 < n2-1; i2++) { u[i3][i2][n1-1] = u[i3][i2][1]; u[i3][i2][0] = u[i3][i2][n1-2]; } // } /* axis = 2 */ //#pragma omp for // for ( i3 = 1; i3 < n3-1; i3++) { for ( i1 = 0; i1 < n1; i1++) { u[i3][n2-1][i1] = u[i3][1][i1]; u[i3][0][i1] = u[i3][n2-2][i1]; } } /* axis = 3 */ #pragma omp for nowait for ( i2 = 0; i2 < n2; i2++) { for ( i1 = 0; i1 < n1; i1++) { u[n3-1][i2][i1] = u[1][i2][i1]; u[0][i2][i1] = u[n3-2][i2][i1]; } } }//end #pragma omp parallel } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void zran3(double ***z, int n1, int n2, int n3, int nx, int ny, int k) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c zran3 loads +1 at ten randomly chosen points, c loads -1 at a different ten random points, c and zero elsewhere. c-------------------------------------------------------------------*/ #define MM 10 #define A pow(5.0,13) #define X 314159265.e0 int i0, m0, m1; int i1, i2, i3, d1, e1, e2, e3; double xx, x0, x1, a1, a2, ai; double ten[MM][2], best; int i, j1[MM][2], j2[MM][2], j3[MM][2]; int jg[4][MM][2]; double rdummy; a1 = power( A, nx ); a2 = power( A, nx*ny ); zero3(z,n1,n2,n3); i = is1-1+nx*(is2-1+ny*(is3-1)); ai = power( A, i ); d1 = ie1 - is1 + 1; e1 = ie1 - is1 + 2; e2 = ie2 - is2 + 2; e3 = ie3 - is3 + 2; x0 = X; rdummy = randlc( &x0, ai ); for (i3 = 1; i3 < e3; i3++) { x1 = x0; for (i2 = 1; i2 < e2; i2++) { xx = x1; vranlc( d1, &xx, A, &(z[i3][i2][0])); rdummy = randlc( &x1, a1 ); } rdummy = randlc( &x0, a2 ); } /*-------------------------------------------------------------------- c call comm3(z,n1,n2,n3) c call showall(z,n1,n2,n3) c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c each processor looks for twenty candidates c-------------------------------------------------------------------*/ for (i = 0; i < MM; i++) { ten[i][1] = 0.0; j1[i][1] = 0; j2[i][1] = 0; j3[i][1] = 0; ten[i][0] = 1.0; j1[i][0] = 0; j2[i][0] = 0; j3[i][0] = 0; } for (i3 = 1; i3 < n3-1; i3++) { for (i2 = 1; i2 < n2-1; i2++) { for (i1 = 1; i1 < n1-1; i1++) { if ( z[i3][i2][i1] > ten[0][1] ) { ten[0][1] = z[i3][i2][i1]; j1[0][1] = i1; j2[0][1] = i2; j3[0][1] = i3; bubble( ten, j1, j2, j3, MM, 1 ); } if ( z[i3][i2][i1] < ten[0][0] ) { ten[0][0] = z[i3][i2][i1]; j1[0][0] = i1; j2[0][0] = i2; j3[0][0] = i3; bubble( ten, j1, j2, j3, MM, 0 ); } } } } /*-------------------------------------------------------------------- c Now which of these are globally best? c-------------------------------------------------------------------*/ i1 = MM - 1; i0 = MM - 1; for (i = MM - 1 ; i >= 0; i--) { best = z[j3[i1][1]][j2[i1][1]][j1[i1][1]]; if (best == z[j3[i1][1]][j2[i1][1]][j1[i1][1]]) { jg[0][i][1] = 0; jg[1][i][1] = is1 - 1 + j1[i1][1]; jg[2][i][1] = is2 - 1 + j2[i1][1]; jg[3][i][1] = is3 - 1 + j3[i1][1]; i1 = i1-1; } else { jg[0][i][1] = 0; jg[1][i][1] = 0; jg[2][i][1] = 0; jg[3][i][1] = 0; } ten[i][1] = best; best = z[j3[i0][0]][j2[i0][0]][j1[i0][0]]; if (best == z[j3[i0][0]][j2[i0][0]][j1[i0][0]]) { jg[0][i][0] = 0; jg[1][i][0] = is1 - 1 + j1[i0][0]; jg[2][i][0] = is2 - 1 + j2[i0][0]; jg[3][i][0] = is3 - 1 + j3[i0][0]; i0 = i0-1; } else { jg[0][i][0] = 0; jg[1][i][0] = 0; jg[2][i][0] = 0; jg[3][i][0] = 0; } ten[i][0] = best; } m1 = i1+1; m0 = i0+1; /* printf(" negative charges at"); for (i = 0; i < MM; i++) { if (i%5 == 0) printf("\n"); printf(" (%3d,%3d,%3d)", jg[1][i][0], jg[2][i][0], jg[3][i][0]); } printf("\n positive charges at"); for (i = 0; i < MM; i++) { if (i%5 == 0) printf("\n"); printf(" (%3d,%3d,%3d)", jg[1][i][1], jg[2][i][1], jg[3][i][1]); } printf("\n small random numbers were\n"); for (i = MM-1; i >= 0; i--) { printf(" %15.8e", ten[i][0]); } printf("\n and they were found on processor number\n"); for (i = MM-1; i >= 0; i--) { printf(" %4d", jg[0][i][0]); } printf("\n large random numbers were\n"); for (i = MM-1; i >= 0; i--) { printf(" %15.8e", ten[i][1]); } printf("\n and they were found on processor number\n"); for (i = MM-1; i >= 0; i--) { printf(" %4d", jg[0][i][1]); } printf("\n");*/ #pragma omp parallel for private(i2, i1) for (i3 = 0; i3 < n3; i3++) { for (i2 = 0; i2 < n2; i2++) { for (i1 = 0; i1 < n1; i1++) { z[i3][i2][i1] = 0.0; } } } for (i = MM-1; i >= m0; i--) { z[j3[i][0]][j2[i][0]][j1[i][0]] = -1.0; } for (i = MM-1; i >= m1; i--) { z[j3[i][1]][j2[i][1]][j1[i][1]] = 1.0; } comm3(z,n1,n2,n3,k); /*-------------------------------------------------------------------- c call showall(z,n1,n2,n3) c-------------------------------------------------------------------*/ } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void showall(double ***z, int n1, int n2, int n3) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ int i1,i2,i3; int m1, m2, m3; m1 = min(n1,18); m2 = min(n2,14); m3 = min(n3,18); printf("\n"); for (i3 = 0; i3 < m3; i3++) { for (i1 = 0; i1 < m1; i1++) { for (i2 = 0; i2 < m2; i2++) { printf("%6.3f", z[i3][i2][i1]); } printf("\n"); } printf(" - - - - - - - \n"); } printf("\n"); } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static double power( double a, int n ) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c power raises an integer, disguised as a double c precision real, to an integer power c-------------------------------------------------------------------*/ double aj; int nj; double rdummy; double power; power = 1.0; nj = n; aj = a; while (nj != 0) { if( (nj%2) == 1 ) rdummy = randlc( &power, aj ); rdummy = randlc( &aj, aj ); nj = nj/2; } return (power); } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void bubble( double ten[M][2], int j1[M][2], int j2[M][2], int j3[M][2], int m, int ind ) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c bubble does a bubble sort in direction dir c-------------------------------------------------------------------*/ double temp; int i, j_temp; if ( ind == 1 ) { for (i = 0; i < m-1; i++) { if ( ten[i][ind] > ten[i+1][ind] ) { temp = ten[i+1][ind]; ten[i+1][ind] = ten[i][ind]; ten[i][ind] = temp; j_temp = j1[i+1][ind]; j1[i+1][ind] = j1[i][ind]; j1[i][ind] = j_temp; j_temp = j2[i+1][ind]; j2[i+1][ind] = j2[i][ind]; j2[i][ind] = j_temp; j_temp = j3[i+1][ind]; j3[i+1][ind] = j3[i][ind]; j3[i][ind] = j_temp; } else { return; } } } else { for (i = 0; i < m-1; i++) { if ( ten[i][ind] < ten[i+1][ind] ) { temp = ten[i+1][ind]; ten[i+1][ind] = ten[i][ind]; ten[i][ind] = temp; j_temp = j1[i+1][ind]; j1[i+1][ind] = j1[i][ind]; j1[i][ind] = j_temp; j_temp = j2[i+1][ind]; j2[i+1][ind] = j2[i][ind]; j2[i][ind] = j_temp; j_temp = j3[i+1][ind]; j3[i+1][ind] = j3[i][ind]; j3[i][ind] = j_temp; } else { return; } } } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void zero3(double ***z, int n1, int n2, int n3) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ int i1, i2, i3; #pragma omp parallel for private(i1,i2,i3) for (i3 = 0;i3 < n3; i3++) { for (i2 = 0; i2 < n2; i2++) { for (i1 = 0; i1 < n1; i1++) { z[i3][i2][i1] = 0.0; } } } } /*---- end of program ------------------------------------------------*/
nested_par3.c
#include <stdio.h> #define N 10 int main (void) { long int aa=0; int res = 0; int ng =12; int cmom = 14; int nxyz = 5; #pragma omp target teams distribute num_teams(nxyz) thread_limit(4) map(tofrom:aa) for (int gid = 0; gid < nxyz; gid++) { #pragma omp parallel for collapse(2) for (unsigned int g = 0; g < ng; g++) { for (unsigned int l = 0; l < cmom-1; l++) { int a = 0; for (int ii = 0; ii < N+2; ii++) { #pragma omp parallel for reduction(+:a) for (int i = 0; i < N; i++) { a += i; } } #pragma omp atomic aa += a; } } } long exp = (long)ng*(cmom-1)*nxyz*(N*(N-1)/2)*(N+2); fprintf (stderr, "The result is = %ld exp:%ld!\n", aa,exp); if (aa != exp) { fprintf(stderr, "Failed %ld\n",aa); return 1; } aa = 0; #pragma omp target teams distribute num_teams(nxyz) thread_limit(4) map(tofrom:aa) for (int gid = 0; gid < nxyz; gid++) { for (unsigned int g = 0; g < ng; g++) { for (unsigned int l = 0; l < cmom-1; l++) { int a = 0; for (int ii = 0; ii < N+2; ii++) { #pragma omp parallel for reduction(+:a) for (int i = 0; i < N; i++) { a += i; } } #pragma omp atomic aa += a; } } } exp = (long)ng*(cmom-1)*nxyz*(N*(N-1)/2)*(N+2); fprintf (stderr, "The result is = %ld exp:%ld!\n", aa,exp); if (aa != exp) { fprintf(stderr, "Failed %ld\n",aa); return 1; } aa = 0; #pragma omp target teams distribute num_teams(nxyz) thread_limit(4) map(tofrom:aa) for (int gid = 0; gid < nxyz; gid++) { #pragma omp parallel for for (unsigned int g = 0; g < ng; g++) { #pragma omp parallel for for (unsigned int l = 0; l < cmom-1; l++) { int a = 0; #pragma omp parallel for for (int ii = 0; ii < N+2; ii++) { #pragma omp parallel for reduction(+:a) for (int i = 0; i < N; i++) { a += i; } } #pragma omp atomic aa += a; } } } exp = (long)ng*(cmom-1)*nxyz*(N*(N-1)/2)*(N+2); fprintf (stderr, "The result is = %ld exp:%ld!\n", aa,exp); if (aa != exp) { fprintf(stderr, "Failed %ld\n",aa); return 1; } aa = 0; #pragma omp target teams distribute num_teams(nxyz) thread_limit(7) map(tofrom:aa) for (int gid = 0; gid < nxyz; gid++) { #pragma omp parallel for collapse(2) for (unsigned int g = 0; g < ng; g++) { for (unsigned int l = 0; l < cmom-1; l++) { int a = 0; #pragma omp parallel for for (int ii = 0; ii < N+2; ii++) { #pragma omp parallel for reduction(+:a) for (int i = 0; i < N; i++) { a += i; } } #pragma omp atomic aa += a; } } } fprintf (stderr, "The result is = %ld exp:%ld!\n", aa,exp); if (aa != exp) { fprintf(stderr, "Failed %ld\n",aa); return 1; } return 0; }
omp_dtrsm_batch.c
/** * @file omp_dtrsm_batch.c * * @brief BBLAS omp_dtrsm_batch double routine. * * BBLAS is a software package provided by Univ. of Manchester, * Univ. of Tennessee. * * @version 1.0.0 * @author Samuel D. Relton * @author Pedro V. Lara * @author Mawussi Zounon * @date 2016-02-20 * **/ #ifndef DOXYGEN_SHOULD_SKIP_THIS /** * Code generation * @generated from ./bblas_omp/omp_ztrsm_batch.c normal z -> d, Mon Jun 6 09:44:13 2016 **/ #endif #include<cblas.h> #include "bblas_omp.h" #include "bblas.h" #include <omp.h> #define REAL /** Purpose ------- <b>dtrsm_batch</b> is an OpenMP version of dtrsm_batch. It solves for X in one of the matrix equations op( arrayA[i] )*X = alpha*arrayB[i], or X*op( arrayA[i] ) = alpha[i]*arrayB[i], where op( X ) is one of - op( X ) = X or - op( X ) = X**T or - op( X ) = X**H, alpha[i] is a scalar, X and B are M[i] by N[i] matrices, and arrayA[i] is a unit or non-unit, upper or lower triangular matrix. The solution matrix X overwrites arrayB[i] on exit. Fixed and Variable Batch Operations ----------------------------------- Two types of batch operation are supported depending upon the value of batch_opts. When <tt>batch_opts = BBLAS_VARIABLE</tt> - all parameters that are arrays must have length at least batch_count. - all parameters that are arrays must have all values set. When <tt>batch_opts = BBLAS_FIXED</tt> - all parameters that are arrays (except for arrayA, arrayB, and info) must have length at least one. - all parameters that are arrays (except for arrayA, arrayB, and info) need only to have their first value set. This means that for a <tt>BBLAS_FIXED</tt> batch, the values of side[0], uplo[0], transA[0], diag[0], M[0], N[0], alpha[0], lda[0], and ldb[0] are used for all computations. Parameters ---------- @param[in] side Array of <tt>enum BBLAS_SIDE</tt>. Each element side[i] specifies whether op( arrayA[i] ) appears on the left or right side of the operation as follows: - = 'BblasLeft' op( arrayA[i] )*X = alpha[i]*arrayB[i]. - = 'BblasRight' X*op( arrayA[i] ) = alpha[i]*arrayB[i]. @param[in] uplo Array of <tt>enum BBLAS_UPLO</tt>. On entry, uplo[i] specifies whether the matrix arrayA[i] is upper or lower triangular as follows: - = 'BblasUpper' arrayA[i] is an upper triangular matrix. - = 'BblasLower' arrayA[i] is a lower triangular matrix. @param[in] transA Array of <tt>enum BBLAS_TRANS</tt>. On entry, trans[i] specifies the form of op( arrayA[i] ) to be used in the operation as follows: - = 'BblasNoTrans' op( arrayA[i] ) = arrayA[i]. - = 'BblasTrans' op( arrayA[i] ) = arrayA[i]**T. - = 'BblasConjTrans' op( arrayA[i] ) = arrayA'[i]**H. @param[in] diag - Array of <tt>enum BBLAS_DIAG</tt>. On entry, diag[i] specifies whether or not arrayA[i] is unit triangular as follows: - = 'BblasUnit' arrayA[i] is assumed to be unit triangular. - = 'BblasNonUnit' arrayA[i] is not assumed to be unit triangular. @param[in] M Array of <tt>int</tt>. Each element M[i] specifies the number of rows of the matrix arrayB[i]. M[i] must be greater than zero. @param[in] N Array of <tt>int</tt>. Each element N[i] specifies the number of columns of the matrix arrayB[i]. N[i] must be greater than zero. @param[in] alpha Array of DOUBLE PRECISION When alpha[i] is set to zero arrayA[i] is not referenced and arrayB[i] need not be set before entry. @param[in] arrayA Array of pointers. Each element arrayA[i] is a pointer to a DOUBLE PRECISION matrix of dimension lda[i] by Ka[i], where Ka[i] = M[i] when side[i] = BblasLeft and is N[i] otherwise. When using side[i] = BblasLeft the M[i] by M[i] part of arrayA[i] must contain the triangular matrix: when uplo[i] = BblasUpper, the upper triangular part of arrayA[i] must contain the matrix whilst the strictly lower triangular part is not used; similarly when uplo[i] = BblasLower, the lower triangular part of arrayA[i] must contain the matrix whilst the strictly upper triangular part is not used. When using side[i] = BblasRight the N[i] by N[i] part of arrayA[i] must contain the symmetric matrix: when uplo[i] = BblasUpper, the upper triangular part of arrayA[i] must contain the matrix whilst the strictly lower triangular part is not used; similarly when uplo[i] = BblasLower, the lower triangular part of arrayA[i] must contain the matrix whilst the strictly upper triangular part is not used. Note that when diag = BblasUnit the diagonal elements of arrayA[i] are not used either, they are assumed to be equal to one. @param[in] lda Array of <tt>int</tt>. On entry, lda[i] specifies the first dimension of arrayA[i] as declared in the calling (sub) program. When side[i] = BblasLeft then lda[i] must be at least max( 1, M[i] ), otherwise lda[i] must be at least max( 1, N[i] ). @param[in,out] arrayB Array of pointers. Each element arrayB[i] is a pointer to a DOUBLE PRECISION matrix of dimension ldb[i] by N[i]. The leading M[i] by N[i] part of arrayB[i] must contain the matrix elements. On exit is arrayB[i] overwritten by the solution matrix X. @param[in] ldb Array of <tt>int</tt>. Each element ldb[i] specifies the first dimension of arrayB[i] as declared in the calling (sub) program. Each element ldb[i] must be at least max( 1, M[i] ). @param[in] batch_count <tt>int</tt> The number of matrices to operate on. @param[in] batch_opts <tt>enum BBLAS_OPTS</tt> One of BBLAS_FIXED or BBLAS_VARIABLE depending upon the type of batch operation required. @param[out] info Array of <tt>int</tt>. Each element info[i] is the error return code of the ith dtrsm in the batch, these need not be set on entry. The error codes can be found in bblas_macros.h. **/ void omp_dtrsm_batch( const enum BBLAS_SIDE *side, const enum BBLAS_UPLO *uplo, const enum BBLAS_TRANS *transA, const enum BBLAS_DIAG *diag, const int *M, const int *N, const double *alpha, const double **arrayA, const int *lda, double **arrayB, const int *ldb, const int batch_count, enum BBLAS_OPTS batch_opts, int *info) { /*Local variables */ int first_index = 0; int batch_iter; int LDA; char func_name[15] = "dtrsm_batch"; /* Check input arguments */ if (batch_count < 0) { xerbla_batch(func_name, BBLAS_ERR_BATCH_COUNT, -1); } if (batch_opts == BBLAS_FIXED) { if ((side[first_index] != BblasLeft) && (side[first_index] != BblasRight)) { xerbla_batch(func_name, BBLAS_ERR_SIDE, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_SIDE; } return; } if ((uplo[first_index] != BblasUpper) && (uplo[first_index] != BblasLower)) { xerbla_batch(func_name, BBLAS_ERR_UPLO, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_UPLO; } return; } if ((transA[first_index] != BblasNoTrans) && (transA[first_index] != BblasTrans) && (transA[first_index] != BblasConjTrans)) { xerbla_batch(func_name, BBLAS_ERR_TRANSA, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_TRANSA; } return; } if ((diag[first_index] != BblasNonUnit) && (diag[first_index] != BblasUnit)) { xerbla_batch(func_name, BBLAS_ERR_DIAG, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_DIAG; } return; } if (M[first_index] < 0) { xerbla_batch(func_name, BBLAS_ERR_M, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_M; } return; } if (N[first_index] < 0) { xerbla_batch(func_name, BBLAS_ERR_N, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_N; } return; } if (side[first_index] == BblasLeft) { LDA = M[first_index]; } else { LDA = N[first_index]; } if (lda[first_index] < max(1, LDA)) { xerbla_batch(func_name, BBLAS_ERR_LDA, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_LDA; } return; } if (ldb[first_index] < max(1, M[first_index])) { xerbla_batch(func_name, BBLAS_ERR_LDB, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_LDB; } return; } /* particular case */ if (min(M[first_index], N[first_index]) == 0) { for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_SUCCESS; } return; } #pragma omp parallel for private(batch_iter) for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { /*Call to cblas_dtrsm */ cblas_dtrsm( BblasColMajor, side[first_index], uplo[first_index], transA[first_index], diag[first_index], M[first_index], N[first_index], (alpha[first_index]), arrayA[batch_iter], lda[first_index], arrayB[batch_iter], ldb[first_index]); /* Successful */ info[batch_iter] = BBLAS_SUCCESS; } /*END FIXED SIZE FOR LOOP */ }else if (batch_opts == BBLAS_VARIABLE) { #pragma omp parallel for private(batch_iter,LDA) for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { /* Check input arguments */ if ((side[batch_iter] != BblasLeft) && (side[batch_iter] != BblasRight)) { xerbla_batch(func_name, BBLAS_ERR_SIDE, batch_iter); info[batch_iter] = BBLAS_ERR_SIDE; continue; } if ((uplo[batch_iter] != BblasUpper) && (uplo[batch_iter] != BblasLower)) { xerbla_batch(func_name, BBLAS_ERR_UPLO, batch_iter); info[batch_iter] = BBLAS_ERR_UPLO; continue; } if ((transA[batch_iter] != BblasNoTrans) && (transA[batch_iter] != BblasTrans) && (transA[batch_iter] != BblasConjTrans)) { xerbla_batch(func_name, BBLAS_ERR_TRANSA, batch_iter); info[batch_iter] = BBLAS_ERR_TRANSA; continue; } if (M[batch_iter] < 0) { xerbla_batch(func_name, BBLAS_ERR_M, batch_iter); info[batch_iter] = BBLAS_ERR_M; continue; } if (N[batch_iter] < 0) { xerbla_batch(func_name, BBLAS_ERR_N, batch_iter); info[batch_iter] = BBLAS_ERR_N; continue; } if (side[batch_iter] == BblasLeft) { LDA = M[batch_iter]; } else { LDA = N[batch_iter]; } if (lda[batch_iter] < max(1, LDA)) { xerbla_batch(func_name, BBLAS_ERR_LDA, batch_iter); info[batch_iter] = BBLAS_ERR_LDA; continue; } if (ldb[batch_iter] < max(1, M[batch_iter])) { xerbla_batch(func_name, BBLAS_ERR_LDC, batch_iter); info[batch_iter] = BBLAS_ERR_LDC; continue; } /* particular case */ if (min(M[batch_iter], N[batch_iter]) == 0) { info[batch_iter] = BBLAS_SUCCESS; continue; } cblas_dtrsm( BblasColMajor, side[batch_iter], uplo[batch_iter], transA[batch_iter], diag[batch_iter], M[batch_iter], N[batch_iter], (alpha[batch_iter]), arrayA[batch_iter], lda[batch_iter], arrayB[batch_iter], ldb[batch_iter]); /* Successful */ info[batch_iter] = BBLAS_SUCCESS; } } else { xerbla_batch(func_name, BBLAS_ERR_BATCH_OPTS, -1); } } #undef REAL
3d25pt_var.c
/* * Order-1, 3D 25 point stencil with axis-symmetric ariable 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])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } 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***)*13); for(m=0; m<13;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] = 8; tile_size[3] = 2048; 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<13; 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; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; 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 ] + A[(t)%2][i+1][j ][k ]) + coef[2][i][j][k] * (A[(t)%2][i ][j-1][k ] + A[(t)%2][i ][j+1][k ]) + coef[3][i][j][k] * (A[(t)%2][i ][j ][k-1] + A[(t)%2][i ][j ][k+1]) + coef[4][i][j][k] * (A[(t)%2][i-2][j ][k ] + A[(t)%2][i+2][j ][k ]) + coef[5][i][j][k] * (A[(t)%2][i ][j-2][k ] + A[(t)%2][i ][j+2][k ]) + coef[6][i][j][k] * (A[(t)%2][i ][j ][k-2] + A[(t)%2][i ][j ][k+2]) + coef[7][i][j][k] * (A[(t)%2][i-3][j ][k ] + A[(t)%2][i+3][j ][k ]) + coef[8][i][j][k] * (A[(t)%2][i ][j-3][k ] + A[(t)%2][i ][j+3][k ]) + coef[9][i][j][k] * (A[(t)%2][i ][j ][k-3] + A[(t)%2][i ][j ][k+3]) + coef[10][i][j][k]* (A[(t)%2][i-4][j ][k ] + A[(t)%2][i+4][j ][k ]) + coef[11][i][j][k]* (A[(t)%2][i ][j-4][k ] + A[(t)%2][i ][j+4][k ]) + coef[12][i][j][k]* (A[(t)%2][i ][j ][k-4] + A[(t)%2][i ][j ][k+4]) ; } } } } #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(4, "variable axis-symmetric") #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<13;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; }
atomic_messages.c
// RUN: %clang_cc1 -verify -fopenmp -ferror-limit 100 %s int foo() { L1: foo(); #pragma omp atomic // expected-error@+2 {{the statement for 'atomic' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}} // expected-note@+1 {{expected an expression statement}} { foo(); goto L1; // expected-error {{use of undeclared label 'L1'}} } goto L2; // expected-error {{use of undeclared label 'L2'}} #pragma omp atomic // expected-error@+2 {{the statement for 'atomic' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}} // expected-note@+1 {{expected an expression statement}} { foo(); L2: foo(); } return 0; } struct S { int a; }; int readint() { int a = 0, b = 0; // Test for atomic read #pragma omp atomic read // expected-error@+2 {{the statement for 'atomic read' must be an expression statement of form 'v = x;', where v and x are both lvalue expressions with scalar type}} // expected-note@+1 {{expected an expression statement}} ; #pragma omp atomic read // expected-error@+2 {{the statement for 'atomic read' must be an expression statement of form 'v = x;', where v and x are both lvalue expressions with scalar type}} // expected-note@+1 {{expected built-in assignment operator}} foo(); #pragma omp atomic read // expected-error@+2 {{the statement for 'atomic read' must be an expression statement of form 'v = x;', where v and x are both lvalue expressions with scalar type}} // expected-note@+1 {{expected built-in assignment operator}} a += b; #pragma omp atomic read // expected-error@+2 {{the statement for 'atomic read' must be an expression statement of form 'v = x;', where v and x are both lvalue expressions with scalar type}} // expected-note@+1 {{expected lvalue expression}} a = 0; #pragma omp atomic read a = b; // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'read' clause}} #pragma omp atomic read read a = b; return 0; } int readS() { struct S a, b; // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'read' clause}} #pragma omp atomic read read // expected-error@+2 {{the statement for 'atomic read' must be an expression statement of form 'v = x;', where v and x are both lvalue expressions with scalar type}} // expected-note@+1 {{expected expression of scalar type}} a = b; return a.a; } int writeint() { int a = 0, b = 0; // Test for atomic write #pragma omp atomic write // expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}} // expected-note@+1 {{expected an expression statement}} ; #pragma omp atomic write // expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}} // expected-note@+1 {{expected built-in assignment operator}} foo(); #pragma omp atomic write // expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}} // expected-note@+1 {{expected built-in assignment operator}} a += b; #pragma omp atomic write a = 0; #pragma omp atomic write a = b; // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'write' clause}} #pragma omp atomic write write a = b; return 0; } int writeS() { struct S a, b; // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'write' clause}} #pragma omp atomic write write // expected-error@+2 {{the statement for 'atomic write' must be an expression statement of form 'x = expr;', where x is a lvalue expression with scalar type}} // expected-note@+1 {{expected expression of scalar type}} a = b; return a.a; } int updateint() { int a = 0, b = 0; // Test for atomic update #pragma omp atomic update // expected-error@+2 {{the statement for 'atomic update' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}} // expected-note@+1 {{expected an expression statement}} ; #pragma omp atomic // expected-error@+2 {{the statement for 'atomic' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}} // expected-note@+1 {{expected built-in binary or unary operator}} foo(); #pragma omp atomic // expected-error@+2 {{the statement for 'atomic' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}} // expected-note@+1 {{expected built-in binary operator}} a = b; #pragma omp atomic update // expected-error@+2 {{the statement for 'atomic update' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}} // expected-note@+1 {{expected one of '+', '*', '-', '/', '&', '^', '|', '<<', or '>>' built-in operations}} a = b || a; #pragma omp atomic update // expected-error@+2 {{the statement for 'atomic update' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}} // expected-note@+1 {{expected one of '+', '*', '-', '/', '&', '^', '|', '<<', or '>>' built-in operations}} a = a && b; #pragma omp atomic update // expected-error@+2 {{the statement for 'atomic update' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}} // expected-note@+1 {{expected in right hand side of expression}} a = (float)a + b; #pragma omp atomic // expected-error@+2 {{the statement for 'atomic' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}} // expected-note@+1 {{expected in right hand side of expression}} a = 2 * b; #pragma omp atomic // expected-error@+2 {{the statement for 'atomic' must be an expression statement of form '++x;', '--x;', 'x++;', 'x--;', 'x binop= expr;', 'x = x binop expr' or 'x = expr binop x', where x is an l-value expression with scalar type}} // expected-note@+1 {{expected in right hand side of expression}} a = b + *&a; #pragma omp atomic update *&a = *&a + 2; #pragma omp atomic update a++; #pragma omp atomic ++a; #pragma omp atomic update a--; #pragma omp atomic --a; #pragma omp atomic update a += b; #pragma omp atomic a %= b; #pragma omp atomic update a *= b; #pragma omp atomic a -= b; #pragma omp atomic update a /= b; #pragma omp atomic a &= b; #pragma omp atomic update a ^= b; #pragma omp atomic a |= b; #pragma omp atomic update a <<= b; #pragma omp atomic a >>= b; #pragma omp atomic update a = b + a; #pragma omp atomic a = a * b; #pragma omp atomic update a = b - a; #pragma omp atomic a = a / b; #pragma omp atomic update a = b & a; #pragma omp atomic a = a ^ b; #pragma omp atomic update a = b | a; #pragma omp atomic a = a << b; #pragma omp atomic a = b >> a; // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'update' clause}} #pragma omp atomic update update a /= b; return 0; } int captureint() { int a = 0, b = 0, c = 0; // Test for atomic capture #pragma omp atomic capture // expected-error@+2 {{the statement for 'atomic capture' must be a compound statement of form '{v = x; x binop= expr;}', '{x binop= expr; v = x;}', '{v = x; x = x binop expr;}', '{v = x; x = expr binop x;}', '{x = x binop expr; v = x;}', '{x = expr binop x; v = x;}' or '{v = x; x = expr;}', '{v = x; x++;}', '{v = x; ++x;}', '{++x; v = x;}', '{x++; v = x;}', '{v = x; x--;}', '{v = x; --x;}', '{--x; v = x;}', '{x--; v = x;}' where x is an l-value expression with scalar type}} // expected-note@+1 {{expected compound statement}} ; #pragma omp atomic capture // expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}} // expected-note@+1 {{expected assignment expression}} foo(); #pragma omp atomic capture // expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}} // expected-note@+1 {{expected built-in binary or unary operator}} a = b; #pragma omp atomic capture // expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}} // expected-note@+1 {{expected assignment expression}} a = b || a; #pragma omp atomic capture // expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}} // expected-note@+1 {{expected one of '+', '*', '-', '/', '&', '^', '|', '<<', or '>>' built-in operations}} b = a = a && b; #pragma omp atomic capture // expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}} // expected-note@+1 {{expected assignment expression}} a = (float)a + b; #pragma omp atomic capture // expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}} // expected-note@+1 {{expected assignment expression}} a = 2 * b; #pragma omp atomic capture // expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}} // expected-note@+1 {{expected assignment expression}} a = b + *&a; #pragma omp atomic capture // expected-error@+2 {{the statement for 'atomic capture' must be a compound statement of form '{v = x; x binop= expr;}', '{x binop= expr; v = x;}', '{v = x; x = x binop expr;}', '{v = x; x = expr binop x;}', '{x = x binop expr; v = x;}', '{x = expr binop x; v = x;}' or '{v = x; x = expr;}', '{v = x; x++;}', '{v = x; ++x;}', '{++x; v = x;}', '{x++; v = x;}', '{v = x; x--;}', '{v = x; --x;}', '{--x; v = x;}', '{x--; v = x;}' where x is an l-value expression with scalar type}} // expected-note@+1 {{expected exactly two expression statements}} { a = b; } #pragma omp atomic capture // expected-error@+2 {{the statement for 'atomic capture' must be a compound statement of form '{v = x; x binop= expr;}', '{x binop= expr; v = x;}', '{v = x; x = x binop expr;}', '{v = x; x = expr binop x;}', '{x = x binop expr; v = x;}', '{x = expr binop x; v = x;}' or '{v = x; x = expr;}', '{v = x; x++;}', '{v = x; ++x;}', '{++x; v = x;}', '{x++; v = x;}', '{v = x; x--;}', '{v = x; --x;}', '{--x; v = x;}', '{x--; v = x;}' where x is an l-value expression with scalar type}} // expected-note@+1 {{expected exactly two expression statements}} {} #pragma omp atomic capture // expected-error@+2 {{the statement for 'atomic capture' must be a compound statement of form '{v = x; x binop= expr;}', '{x binop= expr; v = x;}', '{v = x; x = x binop expr;}', '{v = x; x = expr binop x;}', '{x = x binop expr; v = x;}', '{x = expr binop x; v = x;}' or '{v = x; x = expr;}', '{v = x; x++;}', '{v = x; ++x;}', '{++x; v = x;}', '{x++; v = x;}', '{v = x; x--;}', '{v = x; --x;}', '{--x; v = x;}', '{x--; v = x;}' where x is an l-value expression with scalar type}} // expected-note@+1 {{expected in right hand side of the first expression}} {a = b;a = b;} #pragma omp atomic capture // expected-error@+2 {{the statement for 'atomic capture' must be a compound statement of form '{v = x; x binop= expr;}', '{x binop= expr; v = x;}', '{v = x; x = x binop expr;}', '{v = x; x = expr binop x;}', '{x = x binop expr; v = x;}', '{x = expr binop x; v = x;}' or '{v = x; x = expr;}', '{v = x; x++;}', '{v = x; ++x;}', '{++x; v = x;}', '{x++; v = x;}', '{v = x; x--;}', '{v = x; --x;}', '{--x; v = x;}', '{x--; v = x;}' where x is an l-value expression with scalar type}} // expected-note@+1 {{expected in right hand side of the first expression}} {a = b; a = b || a;} #pragma omp atomic capture {b = a; a = a && b;} #pragma omp atomic capture // expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}} // expected-note@+1 {{expected in right hand side of expression}} b = a = (float)a + b; #pragma omp atomic capture // expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}} // expected-note@+1 {{expected in right hand side of expression}} b = a = 2 * b; #pragma omp atomic capture // expected-error@+2 {{the statement for 'atomic capture' must be an expression statement of form 'v = ++x;', 'v = --x;', 'v = x++;', 'v = x--;', 'v = x binop= expr;', 'v = x = x binop expr' or 'v = x = expr binop x', where x and v are both l-value expressions with scalar type}} // expected-note@+1 {{expected in right hand side of expression}} b = a = b + *&a; #pragma omp atomic capture c = *&a = *&a + 2; #pragma omp atomic capture c = a++; #pragma omp atomic capture c = ++a; #pragma omp atomic capture c = a--; #pragma omp atomic capture c = --a; #pragma omp atomic capture c = a += b; #pragma omp atomic capture c = a %= b; #pragma omp atomic capture c = a *= b; #pragma omp atomic capture c = a -= b; #pragma omp atomic capture c = a /= b; #pragma omp atomic capture c = a &= b; #pragma omp atomic capture c = a ^= b; #pragma omp atomic capture c = a |= b; #pragma omp atomic capture c = a <<= b; #pragma omp atomic capture c = a >>= b; #pragma omp atomic capture c = a = b + a; #pragma omp atomic capture c = a = a * b; #pragma omp atomic capture c = a = b - a; #pragma omp atomic capture c = a = a / b; #pragma omp atomic capture c = a = b & a; #pragma omp atomic capture c = a = a ^ b; #pragma omp atomic capture c = a = b | a; #pragma omp atomic capture c = a = a << b; #pragma omp atomic capture c = a = b >> a; #pragma omp atomic capture { c = *&a; *&a = *&a + 2;} #pragma omp atomic capture { *&a = *&a + 2; c = *&a;} #pragma omp atomic capture {c = a; a++;} #pragma omp atomic capture {++a;c = a;} #pragma omp atomic capture {c = a;a--;} #pragma omp atomic capture {--a;c = a;} #pragma omp atomic capture {c = a; a += b;} #pragma omp atomic capture {a %= b; c = a;} #pragma omp atomic capture {c = a; a *= b;} #pragma omp atomic capture {a -= b;c = a;} #pragma omp atomic capture {c = a; a /= b;} #pragma omp atomic capture {a &= b; c = a;} #pragma omp atomic capture {c = a; a ^= b;} #pragma omp atomic capture {a |= b; c = a;} #pragma omp atomic capture {c = a; a <<= b;} #pragma omp atomic capture {a >>= b; c = a;} #pragma omp atomic capture {c = a; a = b + a;} #pragma omp atomic capture {a = a * b; c = a;} #pragma omp atomic capture {c = a; a = b - a;} #pragma omp atomic capture {a = a / b; c = a;} #pragma omp atomic capture {c = a; a = b & a;} #pragma omp atomic capture {a = a ^ b; c = a;} #pragma omp atomic capture {c = a; a = b | a;} #pragma omp atomic capture {a = a << b; c = a;} #pragma omp atomic capture {c = a; a = b >> a;} #pragma omp atomic capture {c = a; a = foo();} // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'capture' clause}} #pragma omp atomic capture capture b = a /= b; return 0; }
comm.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 */ #ifndef MXNET_KVSTORE_COMM_H_ #define MXNET_KVSTORE_COMM_H_ #include <dmlc/omp.h> #include <string> #include <algorithm> #include <utility> #include <limits> #include <vector> #include <tuple> #include <thread> #include "mxnet/ndarray.h" #include "gradient_compression.h" #include "../ndarray/ndarray_function.h" #include "../operator/tensor/sparse_retain-inl.h" #include "./kvstore_utils.h" namespace mxnet { namespace kvstore { /** * \brief multiple device commmunication */ class Comm { public: Comm() { pinned_ctx_ = Context::CPUPinned(0); } virtual ~Comm() { } /** * \brief init key with the data shape and storage shape */ virtual void Init(int key, const NDArrayStorageType stype, const TShape& shape, int dtype = mshadow::kFloat32) = 0; /** * \brief returns src[0] + .. + src[src.size()-1] */ virtual const NDArray& Reduce( int key, const std::vector<NDArray>& src, int priority) = 0; /** * \brief copy from src to dst[i] for every i */ virtual void Broadcast( int key, const NDArray& src, const std::vector<NDArray*> dst, int priority) = 0; /** * \brief broadcast src to dst[i] with target row_ids for every i * \param key the identifier key for the stored ndarray * \param src the source row_sparse ndarray to broadcast * \param dst a list of destination row_sparse NDArray and its target row_ids to broadcast, where the row_ids are expected to be unique and sorted in row_id.data() * \param priority the priority of the operation */ virtual void BroadcastRowSparse(int key, const NDArray& src, const std::vector<std::pair<NDArray*, NDArray>>& dst, const int priority) = 0; /** * \brief return a pinned contex */ Context pinned_ctx() const { return pinned_ctx_; } /** * \brief Sets gradient compression parameters to be able to * perform reduce with compressed gradients */ void SetGradientCompression(std::shared_ptr<GradientCompression> gc) { gc_ = gc; } protected: Context pinned_ctx_; std::shared_ptr<GradientCompression> gc_; }; /** * \brief an implemention of Comm that first copy data to CPU memeory, and then * reduce there */ class CommCPU : public Comm { public: CommCPU() { nthread_reduction_ = dmlc::GetEnv("MXNET_KVSTORE_REDUCTION_NTHREADS", 4); bigarray_bound_ = dmlc::GetEnv("MXNET_KVSTORE_BIGARRAY_BOUND", 1000 * 1000); // TODO(junwu) delete the following data member, now for benchmark only is_serial_push_ = dmlc::GetEnv("MXNET_KVSTORE_SERIAL_PUSH", 0); } virtual ~CommCPU() { } void Init(int key, const NDArrayStorageType stype, const TShape& shape, int type = mshadow::kFloat32) override { if (stype == kDefaultStorage) { merge_buf_[key].merged = NDArray(shape, pinned_ctx_, false, type); } else { merge_buf_[key].merged = NDArray(stype, shape, pinned_ctx_, true, type); } } const NDArray& Reduce(int key, const std::vector<NDArray>& src, int priority) override { auto& buf = merge_buf_[key]; // avoid extra copy for single device, but it may bring problems for // abnormal usage of kvstore if (src.size() == 1) { if (src[0].storage_type() == kDefaultStorage) { return src[0]; } else { // if sparse and only one GPU, always update weight on CPU CopyFromTo(src[0], &buf.merged, priority); return buf.merged; } } if (buf.merged.storage_type() == kDefaultStorage) { std::vector<Engine::VarHandle> const_vars(src.size() - 1); std::vector<NDArray> reduce(src.size()); CopyFromTo(src[0], &buf.merged, priority); reduce[0] = buf.merged; if (buf.copy_buf.empty()) { buf.copy_buf.resize(src.size()-1); for (size_t j = 0; j < src.size() - 1; ++j) { // allocate NDArray based on storage type buf.copy_buf[j] = NDArray( src[0].shape(), pinned_ctx_, false, src[0].dtype()); } } for (size_t i = 1; i < src.size(); ++i) { CopyFromTo(src[i], &(buf.copy_buf[i-1]), priority); reduce[i] = buf.copy_buf[i-1]; const_vars[i-1] = reduce[i].var(); } Engine::Get()->PushAsync( [reduce, this](RunContext rctx, Engine::CallbackOnComplete on_complete) { ReduceSumCPU(reduce); on_complete(); }, Context::CPU(), const_vars, {reduce[0].var()}, FnProperty::kCPUPrioritized, priority, PROFILER_MESSAGE("KVStoreReduce")); } else { // buf.merged is a sparse ndarray. std::vector<Engine::VarHandle> const_vars(src.size()); std::vector<NDArray> reduce(src.size()); if (buf.copy_buf.empty()) { buf.copy_buf.resize(src.size()); for (size_t j = 0; j < src.size(); ++j) { buf.copy_buf[j] = NDArray( src[0].storage_type(), src[0].shape(), pinned_ctx_, true, src[0].dtype()); } } for (size_t i = 0; i < src.size(); ++i) { CopyFromTo(src[i], &(buf.copy_buf[i]), priority); reduce[i] = buf.copy_buf[i]; const_vars[i] = reduce[i].var(); } NDArray result = buf.merged; Resource rsc = ResourceManager::Get()->Request(result.ctx(), ResourceRequest(ResourceRequest::kTempSpace)); Engine::Get()->PushAsync( [reduce, result, rsc, this](RunContext rctx, Engine::CallbackOnComplete on_complete) { NDArray out = result; is_serial_push_? ReduceSumCPUExSerial(reduce, &out) : mxnet::ndarray::ElementwiseSum(rctx.get_stream<cpu>(), rsc, reduce, &out); on_complete(); }, Context::CPU(), const_vars, {result.var(), rsc.var}, FnProperty::kCPUPrioritized, priority, PROFILER_MESSAGE("KVStoreReduce")); } return buf.merged; } void Broadcast(int key, const NDArray& src, const std::vector<NDArray*> dst, int priority) override { int mask = src.ctx().dev_mask(); if (mask == Context::kCPU) { for (auto d : dst) CopyFromTo(src, d, priority); } else { // first copy data to cpu, then broadcast auto& buf = merge_buf_[key]; CopyFromTo(src, &buf.merged, priority); for (auto d : dst) CopyFromTo(buf.merged, d, priority); } } void BroadcastRowSparse(int key, const NDArray& src, const std::vector<std::pair<NDArray*, NDArray>>& dst, const int priority) override { using namespace mshadow; CHECK_EQ(src.storage_type(), kRowSparseStorage) << "BroadcastRowSparse expects row-sparse src NDArray"; CHECK_EQ(src.ctx().dev_mask(), Context::kCPU) << "BroadcastRowSparse with src on gpu context not supported"; for (size_t i = 0; i < dst.size(); ++i) { NDArray* out = dst[i].first; NDArray row_id = dst[i].second; CHECK_EQ(out->storage_type(), kRowSparseStorage) << "BroadcastRowSparse expects row_sparse dst NDArray"; CHECK_EQ(row_id.ctx().dev_mask(), Context::kCPU) << "BroadcastRowSparse with row_indices on gpu context not supported"; // retain according to unique indices const bool is_to_gpu = out->ctx().dev_mask() == Context::kGPU; NDArray retained_cpu = is_to_gpu ? NDArray(kRowSparseStorage, src.shape(), src.ctx(), true, src.dtype(), src.aux_types()) : *out; Engine::Get()->PushAsync( [=](RunContext rctx, Engine::CallbackOnComplete on_complete) { const TBlob& indices = row_id.data(); NDArray temp = retained_cpu; // get rid the of const qualifier op::SparseRetainOpForwardRspImpl<cpu>(rctx.get_stream<cpu>(), src, indices, kWriteTo, &temp); on_complete(); }, Context::CPU(), {src.var(), row_id.var()}, {retained_cpu.var()}, FnProperty::kNormal, priority, PROFILER_MESSAGE("KVStoreSparseRetain")); // if retained_cpu == out, CopyFromTo will ignore the copy operation CopyFromTo(retained_cpu, out, priority); } } private: // reduce sum into val[0] inline void ReduceSumCPU(const std::vector<NDArray> &in_data) { MSHADOW_TYPE_SWITCH(in_data[0].dtype(), DType, { std::vector<DType*> dptr(in_data.size()); for (size_t i = 0; i < in_data.size(); ++i) { TBlob data = in_data[i].data(); CHECK(data.CheckContiguous()); dptr[i] = data.FlatTo2D<cpu, DType>().dptr_; } size_t total = in_data[0].shape().Size(); ReduceSumCPUImpl(dptr, total); }); } // serial implementation of reduce sum for row sparse NDArray. inline void ReduceSumCPUExSerial(const std::vector<NDArray> &in, NDArray *out) { using namespace rowsparse; using namespace mshadow; auto stype = out->storage_type(); CHECK_EQ(stype, kRowSparseStorage) << "Unexpected storage type " << stype; size_t total_num_rows = 0; size_t num_in = in.size(); // skip the ones with empty indices and values std::vector<bool> skip(num_in, false); // the values tensor of the inputs MSHADOW_TYPE_SWITCH(out->dtype(), DType, { MSHADOW_IDX_TYPE_SWITCH(out->aux_type(kIdx), IType, { std::vector<Tensor<cpu, 2, DType>> in_vals(num_in); std::vector<Tensor<cpu, 1, IType>> in_indices(num_in); // offset to the values tensor of all inputs std::vector<size_t> offsets(num_in, 0); std::vector<size_t> num_rows(num_in, 0); for (size_t i = 0; i < num_in; i++) { if (!in[i].storage_initialized()) { skip[i] = true; continue; } auto size = in[i].aux_shape(kIdx).Size(); num_rows[i] = size; total_num_rows += size; in_vals[i] = in[i].data().FlatTo2D<cpu, DType>(); in_indices[i] = in[i].aux_data(kIdx).FlatTo1D<cpu, IType>(); } std::vector<IType> indices; indices.reserve(total_num_rows); // gather indices from all inputs for (size_t i = 0; i < num_in; i++) { for (size_t j = 0; j < num_rows[i]; j++) { indices.emplace_back(in_indices[i][j]); } } CHECK_EQ(indices.size(), total_num_rows); // dedup indices std::sort(indices.begin(), indices.end()); indices.resize(std::unique(indices.begin(), indices.end()) - indices.begin()); // the one left are unique non-zero rows size_t nnr = indices.size(); // allocate memory for output out->CheckAndAlloc({Shape1(nnr)}); auto idx_data = out->aux_data(kIdx).FlatTo1D<cpu, IType>(); auto val_data = out->data().FlatTo2D<cpu, DType>(); for (size_t i = 0; i < nnr; i++) { // copy indices back idx_data[i] = indices[i]; bool zeros = true; for (size_t j = 0; j < num_in; j++) { if (skip[j]) continue; size_t offset = offsets[j]; if (offset < num_rows[j]) { if (indices[i] == in_indices[j][offset]) { if (zeros) { Copy(val_data[i], in_vals[j][offset], nullptr); zeros = false; } else { val_data[i] += in_vals[j][offset]; } offsets[j] += 1; } } } } }); }); } template<typename DType> inline static void ReduceSumCPU( const std::vector<DType*> &dptr, size_t offset, index_t size) { using namespace mshadow; // NOLINT(*) Tensor<cpu, 1, DType> in_0(dptr[0] + offset, Shape1(size)); for (size_t i = 1; i < dptr.size(); i+=4) { switch (dptr.size() - i) { case 1: { Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size)); in_0 += in_1; break; } case 2: { Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_2(dptr[i+1] + offset, Shape1(size)); in_0 += in_1 + in_2; break; } case 3: { Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_2(dptr[i+1] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_3(dptr[i+2] + offset, Shape1(size)); in_0 += in_1 + in_2 + in_3; break; } default: { Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_2(dptr[i+1] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_3(dptr[i+2] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_4(dptr[i+3] + offset, Shape1(size)); in_0 += in_1 + in_2 + in_3 + in_4; break; } } } } template<typename DType> inline void ReduceSumCPUImpl(std::vector<DType*> dptr, size_t total) { const size_t step = std::min(bigarray_bound_, static_cast<size_t>(4 << 10)); long ntask = (total + step - 1) / step; // NOLINT(*) if (total < bigarray_bound_ || nthread_reduction_ <= 1) { ReduceSumCPU(dptr, 0, total); } else { #pragma omp parallel for schedule(static) num_threads(nthread_reduction_) for (long j = 0; j < ntask; ++j) { // NOLINT(*) size_t k = static_cast<size_t>(j); size_t begin = std::min(k * step, total); size_t end = std::min((k + 1) * step, total); if (j == ntask - 1) CHECK_EQ(end, total); ReduceSumCPU(dptr, begin, static_cast<index_t>(end - begin)); } } } /// \brief temporal space for pushing and pulling struct BufferEntry { /// \brief the merged value NDArray merged; /// \brief the cpu buffer for gpu data std::vector<NDArray> copy_buf; }; std::unordered_map<int, BufferEntry> merge_buf_; size_t bigarray_bound_; int nthread_reduction_; bool is_serial_push_; }; /** * \brief an implementation of Comm that performs reduction on device * directly. * * It is faster if the total device-to-device bandwidths is larger than * device-to-cpu, which is often true for 4 or 8 GPUs. But it uses more device * memory. */ class CommDevice : public Comm { public: CommDevice() { inited_ = false; } virtual ~CommDevice() { } void Init(int key, const NDArrayStorageType stype, const TShape& shape, int dtype = mshadow::kFloat32) override { sorted_key_attrs_.emplace_back(key, shape, dtype, stype); } void InitBuffersAndComm(const std::vector<NDArray>& src) { if (!inited_) { std::vector<Context> devs; for (const auto& a : src) { devs.push_back(a.ctx()); } InitMergeBuffer(devs); if (dmlc::GetEnv("MXNET_ENABLE_GPU_P2P", 1)) { EnableP2P(devs); } } } const NDArray& Reduce(int key, const std::vector<NDArray>& src, int priority) override { // when this reduce is called from kvstore_dist, gc is not set // we don't do compression twice in dist_sync_device if ((gc_ != nullptr) && (gc_->get_type() != CompressionType::kNone)) { return ReduceCompressed(key, src, priority); } // avoid extra copy for single device, but it may bring problems for // abnormal usage of kvstore if (src.size() == 1) { return src[0]; } InitBuffersAndComm(src); auto& buf = merge_buf_[key]; std::vector<NDArray> reduce(src.size()); const NDArrayStorageType stype = buf.merged.storage_type(); if (stype == kDefaultStorage) { CopyFromTo(src[0], &(buf.merged), priority); reduce[0] = buf.merged; if (buf.copy_buf.empty()) { // TODO(mli) this results in large device memory usage for huge ndarray, // such as the largest fullc in VGG. consider to do segment reduce with // NDArray.Slice or gpu direct memory access. for the latter, we need to // remove some ctx check, and also it reduces 20% perf buf.copy_buf.resize(src.size()-1); for (size_t i = 0; i < src.size()-1; ++i) { buf.copy_buf[i] = NDArray( buf.merged.shape(), buf.merged.ctx(), false, buf.merged.dtype()); } } for (size_t i = 0; i < src.size()-1; ++i) { CopyFromTo(src[i+1], &(buf.copy_buf[i]), priority); reduce[i+1] = buf.copy_buf[i]; } } else { if (buf.copy_buf.empty()) { buf.copy_buf.resize(src.size()); for (size_t j = 0; j < src.size(); ++j) { buf.copy_buf[j] = NDArray( buf.merged.storage_type(), buf.merged.shape(), buf.merged.ctx(), true, buf.merged.dtype()); } } for (size_t i = 0; i < src.size(); ++i) { CopyFromTo(src[i], &(buf.copy_buf[i]), priority); reduce[i] = buf.copy_buf[i]; } } ElementwiseSum(reduce, &buf.merged, priority); return buf.merged; } const NDArray& ReduceCompressed(int key, const std::vector<NDArray>& src, int priority) { InitBuffersAndComm(src); auto& buf = merge_buf_[key]; std::vector<NDArray> reduce(src.size()); if (buf.copy_buf.empty()) { // one buf for each context buf.copy_buf.resize(src.size()); buf.compressed_recv_buf.resize(src.size()); buf.compressed_send_buf.resize(src.size()); buf.residual.resize(src.size()); for (size_t i = 0; i < src.size(); ++i) { buf.copy_buf[i] = NDArray(buf.merged.shape(), buf.merged.ctx(), false, buf.merged.dtype()); buf.residual[i] = NDArray(buf.merged.shape(), src[i].ctx(), false, buf.merged.dtype()); buf.residual[i] = 0; int64_t small_size = gc_->GetCompressedSize(buf.merged.shape().Size()); buf.compressed_recv_buf[i] = NDArray(TShape{small_size}, buf.merged.ctx(), false, buf.merged.dtype()); buf.compressed_send_buf[i] = NDArray(TShape{small_size}, src[i].ctx(), false, buf.merged.dtype()); } } for (size_t i = 0; i < src.size(); ++i) { // compress before copy // this is done even if the data is on same context as copy_buf because // we don't want the training to be biased towards data on this GPU gc_->Quantize(src[i], &(buf.compressed_send_buf[i]), &(buf.residual[i]), priority); if (buf.compressed_send_buf[i].ctx() != buf.compressed_recv_buf[i].ctx()) { CopyFromTo(buf.compressed_send_buf[i], &(buf.compressed_recv_buf[i]), priority); } else { // avoid memory copy when they are on same context buf.compressed_recv_buf[i] = buf.compressed_send_buf[i]; } gc_->Dequantize(buf.compressed_recv_buf[i], &(buf.copy_buf[i]), priority); reduce[i] = buf.copy_buf[i]; } ElementwiseSum(reduce, &buf.merged); return buf.merged; } void Broadcast(int key, const NDArray& src, const std::vector<NDArray*> dst, int priority) override { if (!inited_) { // copy to a random device first int dev_id = key % dst.size(); CopyFromTo(src, dst[dev_id], priority); for (size_t i = 0; i < dst.size(); ++i) { if (i != static_cast<size_t>(dev_id)) { CopyFromTo(*dst[dev_id], dst[i], priority); } } } else { auto& buf = merge_buf_[key]; CopyFromTo(src, &buf.merged, priority); for (auto d : dst) { CopyFromTo(buf.merged, d, priority); } } } void BroadcastRowSparse(int key, const NDArray& src, const std::vector<std::pair<NDArray*, NDArray>>& dst, const int priority) override { CHECK_EQ(src.storage_type(), kRowSparseStorage) << "BroadcastRowSparse expects row-sparse src NDArray"; for (size_t i = 0; i < dst.size(); ++i) { NDArray* out = dst[i].first; NDArray row_id = dst[i].second; CHECK_EQ(out->storage_type(), kRowSparseStorage) << "BroadcastRowSparse expects row_sparse dst NDArray"; CHECK_EQ(row_id.ctx(), src.ctx()) << "row_id and src are expected to be on the same context"; // retain according to indices const bool is_diff_ctx = out->ctx() != src.ctx(); NDArray out_gpu = is_diff_ctx? NDArray(kRowSparseStorage, out->shape(), src.ctx(), true, out->dtype(), out->aux_types()) : *out; Engine::Get()->PushAsync([=](RunContext rctx, Engine::CallbackOnComplete on_complete) { const TBlob& indices = row_id.data(); using namespace mxnet::common; NDArray temp = out_gpu; switch (temp.ctx().dev_mask()) { case cpu::kDevMask: { SparseRetainOpForwardRspWrapper<cpu>(rctx.get_stream<cpu>(), src, indices, kWriteTo, &temp); break; } #if MXNET_USE_CUDA case gpu::kDevMask: { SparseRetainOpForwardRspWrapper<gpu>(rctx.get_stream<gpu>(), src, indices, kWriteTo, &temp); // wait for GPU operations to complete rctx.get_stream<gpu>()->Wait(); break; } #endif default: LOG(FATAL) << MXNET_GPU_NOT_ENABLED_ERROR; } on_complete(); }, out_gpu.ctx(), {src.var(), row_id.var()}, {out_gpu.var()}, FnProperty::kNormal, priority, PROFILER_MESSAGE("KVStoreSparseRetain")); CopyFromTo(out_gpu, out, priority); } } private: void EnableP2P(const std::vector<Context>& devs) { #if MXNET_USE_CUDA std::vector<int> gpus; for (const auto& d : devs) { if (d.dev_mask() == gpu::kDevMask) { gpus.push_back(d.dev_id); } } int n = static_cast<int>(gpus.size()); int enabled = 0; std::vector<int> p2p(n*n); for (int i = 0; i < n; ++i) { cudaSetDevice(gpus[i]); for (int j = 0; j < n; j++) { int access; cudaDeviceCanAccessPeer(&access, gpus[i], gpus[j]); if (access) { cudaError_t e = cudaDeviceEnablePeerAccess(gpus[j], 0); if (e == cudaSuccess || e == cudaErrorPeerAccessAlreadyEnabled) { ++enabled; p2p[i*n+j] = 1; } } } } if (enabled != n*(n-1)) { // print warning info if not fully enabled LOG(WARNING) << "only " << enabled << " out of " << n*(n-1) << " GPU pairs are enabled direct access. " << "It may affect the performance. " << "You can set MXNET_ENABLE_GPU_P2P=0 to turn it off"; std::string access(n, '.'); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { access[j] = p2p[i*n+j] ? 'v' : '.'; } LOG(WARNING) << access; } } #endif } using KeyAttrs = std::tuple<int, TShape, int, NDArrayStorageType>; // try to allocate buff on device evenly void InitMergeBuffer(const std::vector<Context>& devs) { std::sort(sorted_key_attrs_.begin(), sorted_key_attrs_.end(), []( const KeyAttrs& a, const KeyAttrs& b) { return std::get<1>(a).Size() > std::get<1>(b).Size(); }); std::unordered_map<int, std::pair<Context, size_t>> ctx_info; for (auto d : devs) { ctx_info[d.dev_id] = std::make_pair(d, 0); } for (size_t i = 0; i < sorted_key_attrs_.size(); ++i) { const int key = std::get<0>(sorted_key_attrs_[i]); const TShape& shape = std::get<1>(sorted_key_attrs_[i]); const int type = std::get<2>(sorted_key_attrs_[i]); const NDArrayStorageType stype = std::get<3>(sorted_key_attrs_[i]); auto& buf = merge_buf_[key]; Context ctx; size_t min_size = std::numeric_limits<size_t>::max(); for (auto it = ctx_info.begin(); it != ctx_info.end(); ++it) { size_t size = it->second.second; if (size <= min_size) { ctx = it->second.first; min_size = size; } } if (stype == kDefaultStorage) { buf.merged = NDArray(shape, ctx, false, type); } else { buf.merged = NDArray(stype, shape, ctx, true, type); } ctx_info[ctx.dev_id].second += shape.Size(); } inited_ = true; } std::vector<KeyAttrs> sorted_key_attrs_; /// \brief temporal space for pushing and pulling struct BufferEntry { /// \brief the merged value NDArray merged; /// \brief the gpu buffer std::vector<NDArray> copy_buf; /// \brief the residual buffer for gradient compression std::vector<NDArray> residual; /// \brief the small buffer for compressed data in sender std::vector<NDArray> compressed_send_buf; /// \brief the small buffer for compressed data in receiver std::vector<NDArray> compressed_recv_buf; }; std::unordered_map<int, BufferEntry> merge_buf_; bool inited_; }; } // namespace kvstore } // namespace mxnet #endif // MXNET_KVSTORE_COMM_H_
multi_bspline_create.c
///////////////////////////////////////////////////////////////////////////// // einspline: a library for creating and evaluating B-splines // // Copyright (C) 2007 Kenneth P. Esler, Jr. // // // // 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 "multi_bspline_create.h" #ifndef _XOPEN_SOURCE #define _XOPEN_SOURCE 600 #endif #ifndef __USE_XOPEN2K #define __USE_XOPEN2K #endif #include <stdlib.h> #include <stdio.h> #include <inttypes.h> int posix_memalign(void **memptr, size_t alignment, size_t size); //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //// Helper functions for spline creation //// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// void init_sse_data(); void find_coefs_1d_d (Ugrid grid, BCtype_d bc, double *data, intptr_t dstride, double *coefs, intptr_t cstride); void solve_deriv_interp_1d_s (float bands[], float coefs[], int M, int cstride); // On input, bands should be filled with: // row 0 : abcdInitial from boundary conditions // rows 1:M: basis functions in first 3 cols, data in last // row M+1 : abcdFinal from boundary conditions // cstride gives the stride between values in coefs. // On exit, coefs with contain interpolating B-spline coefs void solve_periodic_interp_1d_s (float bands[], float coefs[], int M, int cstride); // On input, bands should be filled with: // row 0 : abcdInitial from boundary conditions // rows 1:M: basis functions in first 3 cols, data in last // row M+1 : abcdFinal from boundary conditions // cstride gives the stride between values in coefs. // On exit, coefs with contain interpolating B-spline coefs void solve_antiperiodic_interp_1d_s (float bands[], float coefs[], int M, int cstride); void find_coefs_1d_s (Ugrid grid, BCtype_s bc, float *data, intptr_t dstride, float *coefs, intptr_t cstride); //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //// Single-Precision, Real Creation Routines //// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // On input, bands should be filled with: // row 0 : abcdInitial from boundary conditions // rows 1:M: basis functions in first 3 cols, data in last // row M+1 : abcdFinal from boundary conditions // cstride gives the stride between values in coefs. // On exit, coefs with contain interpolating B-spline coefs multi_UBspline_1d_s* create_multi_UBspline_1d_s (Ugrid x_grid, BCtype_s xBC, int num_splines) { // Create new spline multi_UBspline_1d_s* restrict spline = malloc (sizeof(multi_UBspline_1d_s)); if (!spline) { fprintf (stderr, "Out of memory allocating spline in create_multi_UBspline_1d_s.\n"); abort(); } spline->spcode = MULTI_U1D; spline->tcode = SINGLE_REAL; spline->xBC = xBC; spline->x_grid = x_grid; spline->num_splines = num_splines; // Setup internal variables int Mx = x_grid.num; int Nx; if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) { x_grid.delta = (x_grid.end-x_grid.start)/(double)(x_grid.num); Nx = Mx+3; } else { x_grid.delta = (x_grid.end-x_grid.start)/(double)(x_grid.num-1); Nx = Mx+2; } int N = num_splines; #ifdef HAVE_SSE if (N % 4) N += 4 - (N % 4); #endif spline->x_stride = N; x_grid.delta_inv = 1.0/x_grid.delta; spline->x_grid = x_grid; #ifndef HAVE_POSIX_MEMALIGN spline->coefs = malloc (sizeof(float)*Nx*N); #else posix_memalign ((void**)&spline->coefs, 64, (sizeof(float)*Nx*N)); #endif spline->coefs_size=(size_t)Nx*(size_t)N; #ifdef HAVE_SSE init_sse_data(); #endif if (!spline->coefs) { fprintf (stderr, "Out of memory allocating spline coefficient in create_multi_UBspline_1d_s.\n"); abort(); } return spline; } void set_multi_UBspline_1d_s (multi_UBspline_1d_s *spline, int num, float *data) { float *coefs = spline->coefs + num; int xs = spline->x_stride; find_coefs_1d_s (spline->x_grid, spline->xBC, data, 1, coefs, xs); } multi_UBspline_2d_s* create_multi_UBspline_2d_s (Ugrid x_grid, Ugrid y_grid, BCtype_s xBC, BCtype_s yBC, int num_splines) { // Create new spline multi_UBspline_2d_s* restrict spline = malloc (sizeof(multi_UBspline_2d_s)); if (!spline) { fprintf (stderr, "Out of memory allocating spline in create_multi_UBspline_2d_s.\n"); abort(); } spline->spcode = MULTI_U2D; spline->tcode = SINGLE_REAL; spline->xBC = xBC; spline->yBC = yBC; spline->num_splines = num_splines; // Setup internal variables int Mx = x_grid.num; int My = y_grid.num; int Nx, Ny; if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; x_grid.delta = (x_grid.end - x_grid.start)/(double)(Nx-3); x_grid.delta_inv = 1.0/x_grid.delta; spline->x_grid = x_grid; if (yBC.lCode == PERIODIC || yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; y_grid.delta = (y_grid.end - y_grid.start)/(double)(Ny-3); y_grid.delta_inv = 1.0/y_grid.delta; spline->y_grid = y_grid; int N = num_splines; #ifdef HAVE_SSE if (N % 4) N += 4 - (N % 4); #endif spline->x_stride = Ny*N; spline->y_stride = N; #ifndef HAVE_POSIX_MEMALIGN spline->coefs = malloc ((size_t)sizeof(float)*Nx*Ny*N); #else posix_memalign ((void**)&spline->coefs, 64, sizeof(float)*Nx*Ny*N); #endif #ifdef HAVE_SSE init_sse_data(); #endif if (!spline->coefs) { fprintf (stderr, "Out of memory allocating spline coefficients in create_multi_UBspline_2d_s.\n"); abort(); } return spline; } void set_multi_UBspline_2d_s (multi_UBspline_2d_s* spline, int num, float *data) { int Mx = spline->x_grid.num; int My = spline->y_grid.num; int Nx, Ny; if (spline->xBC.lCode == PERIODIC || spline->xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; if (spline->yBC.lCode == PERIODIC || spline->yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; float *coefs = spline->coefs + num; int ys = spline->y_stride; // First, solve in the X-direction for (int iy=0; iy<My; iy++) { intptr_t doffset = iy; intptr_t coffset = iy*ys; find_coefs_1d_s (spline->x_grid, spline->xBC, data+doffset, (intptr_t)My, coefs+coffset, (intptr_t)Ny*ys); } // Now, solve in the Y-direction for (int ix=0; ix<Nx; ix++) { intptr_t doffset = ix*Ny*ys; intptr_t coffset = ix*Ny*ys; find_coefs_1d_s (spline->y_grid, spline->yBC, coefs+doffset, (intptr_t)ys, coefs+coffset, (intptr_t)ys); } } multi_UBspline_3d_s* create_multi_UBspline_3d_s (Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_s xBC, BCtype_s yBC, BCtype_s zBC, int num_splines) { // Create new spline multi_UBspline_3d_s* restrict spline = malloc (sizeof(multi_UBspline_3d_s)); if (!spline) { fprintf (stderr, "Out of memory allocating spline in create_multi_UBspline_3d_s.\n"); abort(); } spline->spcode = MULTI_U3D; spline->tcode = SINGLE_REAL; spline->xBC = xBC; spline->yBC = yBC; spline->zBC = zBC; spline->num_splines = num_splines; // Setup internal variables int Mx = x_grid.num; int My = y_grid.num; int Mz = z_grid.num; int Nx, Ny, Nz; if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; x_grid.delta = (x_grid.end - x_grid.start)/(double)(Nx-3); x_grid.delta_inv = 1.0/x_grid.delta; spline->x_grid = x_grid; if (yBC.lCode == PERIODIC || yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; y_grid.delta = (y_grid.end - y_grid.start)/(double)(Ny-3); y_grid.delta_inv = 1.0/y_grid.delta; spline->y_grid = y_grid; if (zBC.lCode == PERIODIC || zBC.lCode == ANTIPERIODIC) Nz = Mz+3; else Nz = Mz+2; z_grid.delta = (z_grid.end - z_grid.start)/(double)(Nz-3); z_grid.delta_inv = 1.0/z_grid.delta; spline->z_grid = z_grid; int N = num_splines; #if defined(HAVE_SSE) || defined(BGQPX) if (N % 4) N += 4 - (N % 4); // fprintf(stdout, " The coefs has been 16-byte aligned.\n"); #endif spline->x_stride = Ny*Nz*N; spline->y_stride = Nz*N; spline->z_stride = N; #ifndef HAVE_POSIX_MEMALIGN spline->coefs = malloc (sizeof(float)*Nx*Ny*Nz*N); #else posix_memalign ((void**)&spline->coefs, 64, ((size_t)sizeof(float)*Nx*Ny*Nz*N)); #endif spline->coefs_size=(size_t)Nx*(size_t)Ny*(size_t)Nz*(size_t)N; #ifdef HAVE_SSE init_sse_data(); #endif if (!spline->coefs) { fprintf (stderr, "Out of memory allocating spline coefficients in create_multi_UBspline_3d_s.\n"); abort(); } return spline; } void set_multi_UBspline_3d_s (multi_UBspline_3d_s* spline, int num, float *data) { int Mx = spline->x_grid.num; int My = spline->y_grid.num; int Mz = spline->z_grid.num; int Nx, Ny, Nz; if (spline->xBC.lCode == PERIODIC || spline->xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; if (spline->yBC.lCode == PERIODIC || spline->yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; if (spline->zBC.lCode == PERIODIC || spline->zBC.lCode == ANTIPERIODIC) Nz = Mz+3; else Nz = Mz+2; float *coefs = spline->coefs + num; intptr_t zs = spline->z_stride; // First, solve in the X-direction #pragma omp parallel for for (int iy=0; iy<My; iy++) for (int iz=0; iz<Mz; iz++) { intptr_t doffset = iy*Mz+iz; intptr_t coffset = (iy*Nz+iz)*zs; find_coefs_1d_s (spline->x_grid, spline->xBC, data+doffset, (intptr_t)(My*Mz), coefs+coffset, (intptr_t)(Ny*Nz)*zs); } // Now, solve in the Y-direction #pragma omp parallel for for (int ix=0; ix<Nx; ix++) for (int iz=0; iz<Nz; iz++) { intptr_t doffset = (ix*Ny*Nz + iz)*zs; intptr_t coffset = (ix*Ny*Nz + iz)*zs; find_coefs_1d_s (spline->y_grid, spline->yBC, coefs+doffset, (intptr_t)Nz*zs, coefs+coffset, (intptr_t)Nz*zs); } // Now, solve in the Z-direction #pragma omp parallel for for (int ix=0; ix<Nx; ix++) for (int iy=0; iy<Ny; iy++) { intptr_t doffset = ((ix*Ny+iy)*Nz)*zs; intptr_t coffset = ((ix*Ny+iy)*Nz)*zs; find_coefs_1d_s (spline->z_grid, spline->zBC, coefs+doffset, zs, coefs+coffset, zs); } } void set_multi_UBspline_3d_s_d(multi_UBspline_3d_s* spline, int num, double *data) { BCtype_d xBC, yBC, zBC; xBC.lCode=spline->xBC.lCode; xBC.rCode=spline->xBC.rCode; yBC.lCode=spline->yBC.lCode; yBC.rCode=spline->yBC.rCode; zBC.lCode=spline->zBC.lCode; zBC.rCode=spline->zBC.rCode; xBC.lVal=spline->xBC.lVal; xBC.rVal=spline->xBC.rVal; yBC.lVal=spline->yBC.lVal; yBC.rVal=spline->yBC.rVal; zBC.lVal=spline->zBC.lVal; zBC.rVal=spline->zBC.rVal; int Mx = spline->x_grid.num; int My = spline->y_grid.num; int Mz = spline->z_grid.num; int Nx, Ny, Nz; if (spline->xBC.lCode == PERIODIC || spline->xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; if (spline->yBC.lCode == PERIODIC || spline->yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; if (spline->zBC.lCode == PERIODIC || spline->zBC.lCode == ANTIPERIODIC) Nz = Mz+3; else Nz = Mz+2; double *spline_tmp = malloc(sizeof(double)*Nx*Ny*Nz); // First, solve in the X-direction #pragma omp parallel for for (int iy=0; iy<My; iy++) for (int iz=0; iz<Mz; iz++) { intptr_t doffset = iy*Mz+iz; intptr_t coffset = iy*Nz+iz; find_coefs_1d_d (spline->x_grid, xBC, data+doffset, My*Mz, spline_tmp+coffset, Ny*Nz); } // Now, solve in the Y-direction #pragma omp parallel for for (int ix=0; ix<Nx; ix++) for (int iz=0; iz<Nz; iz++) { intptr_t doffset = ix*Ny*Nz + iz; intptr_t coffset = ix*Ny*Nz + iz; find_coefs_1d_d (spline->y_grid, yBC, spline_tmp+doffset, Nz, spline_tmp+coffset, Nz); } // Now, solve in the Z-direction #pragma omp parallel for for (int ix=0; ix<Nx; ix++) for (int iy=0; iy<Ny; iy++) { intptr_t doffset = (ix*Ny+iy)*Nz; intptr_t coffset = (ix*Ny+iy)*Nz; find_coefs_1d_d (spline->z_grid, zBC, spline_tmp+doffset, 1, spline_tmp+coffset, 1); } { // const double* restrict i_ptr=spline_tmp; #pragma omp parallel for for(int ix=0; ix<Nx; ++ix) { const double* restrict i_ptr=spline_tmp+ix*Ny*Nz; for(int iy=0; iy<Ny; ++iy) for(int iz=0; iz<Nz; ++iz) spline->coefs[ix*spline->x_stride + iy*spline->y_stride + iz*spline->z_stride + num] = (float)(*i_ptr++); } } free (spline_tmp); } ///////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //// Single-Precision, Complex Creation Routines //// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // On input, bands should be filled with: // row 0 : abcdInitial from boundary conditions // rows 1:M: basis functions in first 3 cols, data in last // row M+1 : abcdFinal from boundary conditions // cstride gives the stride between values in coefs. // On exit, coefs with contain interpolating B-spline coefs multi_UBspline_1d_c* create_multi_UBspline_1d_c (Ugrid x_grid, BCtype_c xBC, int num_splines) { // Create new spline multi_UBspline_1d_c* restrict spline = malloc (sizeof(multi_UBspline_1d_c)); if (!spline) { fprintf (stderr, "Out of memory allocating spline in create_multi_UBspline_1d_c.\n"); abort(); } spline->spcode = MULTI_U1D; spline->tcode = SINGLE_COMPLEX; spline->xBC = xBC; spline->num_splines = num_splines; // Setup internal variables int M = x_grid.num; int N; if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) { x_grid.delta = (x_grid.end-x_grid.start)/(double)(x_grid.num); N = M+3; } else { x_grid.delta = (x_grid.end-x_grid.start)/(double)(x_grid.num-1); N = M+2; } x_grid.delta_inv = 1.0/x_grid.delta; spline->x_grid = x_grid; spline->x_stride = num_splines; #ifndef HAVE_POSIX_MEMALIGN spline->coefs = malloc (2*sizeof(float)*N*num_splines); #else posix_memalign ((void**)&spline->coefs, 64, 2*sizeof(float)*N*num_splines); #endif spline->coefs_size=(size_t)N*(size_t)num_splines; #ifdef HAVE_SSE init_sse_data(); #endif if (!spline->coefs) { fprintf (stderr, "Out of memory allocating spline coefficients in create_multi_UBspline_1d_c.\n"); abort(); } return spline; } void set_multi_UBspline_1d_c (multi_UBspline_1d_c* spline, int num, complex_float *data) { complex_float *coefs = spline->coefs + num; BCtype_s xBC_r, xBC_i; xBC_r.lCode = spline->xBC.lCode; xBC_r.rCode = spline->xBC.rCode; xBC_r.lVal = spline->xBC.lVal_r; xBC_r.rVal = spline->xBC.rVal_r; xBC_i.lCode = spline->xBC.lCode; xBC_i.rCode = spline->xBC.rCode; xBC_i.lVal = spline->xBC.lVal_i; xBC_i.rVal = spline->xBC.rVal_i; int xs = spline->x_stride; // Real part find_coefs_1d_s (spline->x_grid, xBC_r, (float*)data, (intptr_t)2, (float*)coefs, (intptr_t)2*xs); // Imaginarty part find_coefs_1d_s (spline->x_grid, xBC_i, ((float*)data)+1, (intptr_t)2, ((float*)coefs+1), (intptr_t)2*xs); } multi_UBspline_2d_c* create_multi_UBspline_2d_c (Ugrid x_grid, Ugrid y_grid, BCtype_c xBC, BCtype_c yBC, int num_splines) { // Create new spline multi_UBspline_2d_c* restrict spline = malloc (sizeof(multi_UBspline_2d_c)); if (!spline) { fprintf (stderr, "Out of memory allocating spline in create_multi_UBspline_2d_c.\n"); abort(); } spline->spcode = MULTI_U2D; spline->tcode = SINGLE_COMPLEX; spline->xBC = xBC; spline->yBC = yBC; spline->num_splines = num_splines; // Setup internal variables int Mx = x_grid.num; int My = y_grid.num; int Nx, Ny; if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; x_grid.delta = (x_grid.end - x_grid.start)/(double)(Nx-3); x_grid.delta_inv = 1.0/x_grid.delta; spline->x_grid = x_grid; if (yBC.lCode == PERIODIC || yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; y_grid.delta = (y_grid.end - y_grid.start)/(double)(Ny-3); y_grid.delta_inv = 1.0/y_grid.delta; spline->y_grid = y_grid; int N = num_splines; #ifdef HAVE_SSE if (N % 2) N++; #endif spline->x_stride = Ny*N; spline->y_stride = N; #ifndef HAVE_POSIX_MEMALIGN spline->coefs = malloc (2*sizeof(float)*Nx*Ny*N); spline->lapl2 = malloc (4*sizeof(float)*N); #else posix_memalign ((void**)&spline->coefs, 64, 2*sizeof(float)*Nx*Ny*N); posix_memalign ((void**)&spline->lapl2, 64, 4*sizeof(float)*N); #endif #ifdef HAVE_SSE init_sse_data(); #endif if (!spline->coefs || !spline->lapl2) { fprintf (stderr, "Out of memory allocating spline coefficients in create_multi_UBspline_2d_c.\n"); abort(); } return spline; } void set_multi_UBspline_2d_c (multi_UBspline_2d_c* spline, int num, complex_float *data) { // Setup internal variables int Mx = spline->x_grid.num; int My = spline->y_grid.num; int Nx, Ny; complex_float* coefs = spline->coefs + num; if (spline->xBC.lCode == PERIODIC || spline->xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; if (spline->yBC.lCode == PERIODIC || spline->yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; BCtype_s xBC_r, xBC_i, yBC_r, yBC_i; xBC_r.lCode = spline->xBC.lCode; xBC_r.rCode = spline->xBC.rCode; xBC_r.lVal = spline->xBC.lVal_r; xBC_r.rVal = spline->xBC.rVal_r; xBC_i.lCode = spline->xBC.lCode; xBC_i.rCode = spline->xBC.rCode; xBC_i.lVal = spline->xBC.lVal_i; xBC_i.rVal = spline->xBC.rVal_i; yBC_r.lCode = spline->yBC.lCode; yBC_r.rCode = spline->yBC.rCode; yBC_r.lVal = spline->yBC.lVal_r; yBC_r.rVal = spline->yBC.rVal_r; yBC_i.lCode = spline->yBC.lCode; yBC_i.rCode = spline->yBC.rCode; yBC_i.lVal = spline->yBC.lVal_i; yBC_i.rVal = spline->yBC.rVal_i; int ys = spline->y_stride; // First, solve in the X-direction for (int iy=0; iy<My; iy++) { intptr_t doffset = (2*iy); intptr_t coffset = (2*iy)*ys; // Real part find_coefs_1d_s (spline->x_grid, xBC_r, ((float*)data)+doffset, (intptr_t)2*My, (float*)coefs+coffset, (intptr_t)2*Ny*ys); // Imag part find_coefs_1d_s (spline->x_grid, xBC_i, ((float*)data)+doffset+1, (intptr_t)2*My, ((float*)coefs)+coffset+1, (intptr_t)2*Ny*ys); } // Now, solve in the Y-direction for (int ix=0; ix<Nx; ix++) { intptr_t doffset = (2*ix*Ny)*ys; intptr_t coffset = (2*ix*Ny)*ys; // Real part find_coefs_1d_s (spline->y_grid, yBC_r, ((float*)coefs)+doffset, (intptr_t)2*ys, ((float*)coefs)+coffset, (intptr_t)2*ys); // Imag part find_coefs_1d_s (spline->y_grid, yBC_i, ((float*)coefs)+doffset+1, (intptr_t)2*ys, ((float*)coefs)+coffset+1, (intptr_t)2*ys); } } multi_UBspline_3d_c* create_multi_UBspline_3d_c (Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_c xBC, BCtype_c yBC, BCtype_c zBC, int num_splines) { // Create new spline multi_UBspline_3d_c* restrict spline = malloc (sizeof(multi_UBspline_3d_c)); if (!spline) { fprintf (stderr, "Out of memory allocating spline in create_multi_UBspline_3d_c.\n"); abort(); } spline->spcode = MULTI_U3D; spline->tcode = SINGLE_COMPLEX; spline->xBC = xBC; spline->yBC = yBC; spline->zBC = zBC; spline->num_splines = num_splines; // Setup internal variables int Mx = x_grid.num; int My = y_grid.num; int Mz = z_grid.num; int Nx, Ny, Nz; if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; x_grid.delta = (x_grid.end - x_grid.start)/(double)(Nx-3); x_grid.delta_inv = 1.0/x_grid.delta; spline->x_grid = x_grid; if (yBC.lCode == PERIODIC || yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; y_grid.delta = (y_grid.end - y_grid.start)/(double)(Ny-3); y_grid.delta_inv = 1.0/y_grid.delta; spline->y_grid = y_grid; if (zBC.lCode == PERIODIC || zBC.lCode == ANTIPERIODIC) Nz = Mz+3; else Nz = Mz+2; z_grid.delta = (z_grid.end - z_grid.start)/(double)(Nz-3); z_grid.delta_inv = 1.0/z_grid.delta; spline->z_grid = z_grid; int N = spline->num_splines; #ifdef HAVE_SSE if (N % 2) N++; #endif spline->x_stride = Ny*Nz*N; spline->y_stride = Nz*N; spline->z_stride = N; #ifndef HAVE_POSIX_MEMALIGN spline->coefs = malloc ((size_t)2*sizeof(float)*Nx*Ny*Nz*N); spline->lapl3 = malloc (6*sizeof(float)*N); #else posix_memalign ((void**)&spline->coefs, 64, (size_t)2*sizeof(float)*Nx*Ny*Nz*N); posix_memalign ((void**)&spline->lapl3, 64, 6*sizeof(float)*N); #endif spline->coefs_size=(size_t)Nx*(size_t)Ny*(size_t)Nz*(size_t)N; #ifdef HAVE_SSE init_sse_data(); #endif if (!spline->coefs || !spline->lapl3) { fprintf (stderr, "Out of memory allocating spline coefficients in create_multi_UBspline_3d_c.\n"); abort(); } return spline; } void set_multi_UBspline_3d_c (multi_UBspline_3d_c* spline, int num, complex_float *data) { // Setup internal variables int Mx = spline->x_grid.num; int My = spline->y_grid.num; int Mz = spline->z_grid.num; int Nx, Ny, Nz; if (spline->xBC.lCode == PERIODIC || spline->xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; if (spline->yBC.lCode == PERIODIC || spline->yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; if (spline->zBC.lCode == PERIODIC || spline->zBC.lCode == ANTIPERIODIC) Nz = Mz+3; else Nz = Mz+2; BCtype_s xBC_r, xBC_i, yBC_r, yBC_i, zBC_r, zBC_i; xBC_r.lCode = spline->xBC.lCode; xBC_r.rCode = spline->xBC.rCode; xBC_r.lVal = spline->xBC.lVal_r; xBC_r.rVal = spline->xBC.rVal_r; xBC_i.lCode = spline->xBC.lCode; xBC_i.rCode = spline->xBC.rCode; xBC_i.lVal = spline->xBC.lVal_i; xBC_i.rVal = spline->xBC.rVal_i; yBC_r.lCode = spline->yBC.lCode; yBC_r.rCode = spline->yBC.rCode; yBC_r.lVal = spline->yBC.lVal_r; yBC_r.rVal = spline->yBC.rVal_r; yBC_i.lCode = spline->yBC.lCode; yBC_i.rCode = spline->yBC.rCode; yBC_i.lVal = spline->yBC.lVal_i; yBC_i.rVal = spline->yBC.rVal_i; zBC_r.lCode = spline->zBC.lCode; zBC_r.rCode = spline->zBC.rCode; zBC_r.lVal = spline->zBC.lVal_r; zBC_r.rVal = spline->zBC.rVal_r; zBC_i.lCode = spline->zBC.lCode; zBC_i.rCode = spline->zBC.rCode; zBC_i.lVal = spline->zBC.lVal_i; zBC_i.rVal = spline->zBC.rVal_i; complex_float *coefs = spline->coefs + num; int zs = spline->z_stride; // First, solve in the X-direction for (int iy=0; iy<My; iy++) for (int iz=0; iz<Mz; iz++) { intptr_t doffset = 2*(iy*Mz+iz); intptr_t coffset = 2*(iy*Nz+iz)*zs; // Real part find_coefs_1d_s (spline->x_grid, xBC_r, ((float*)data)+doffset, (intptr_t)2*My*Mz, ((float*)coefs)+coffset, (intptr_t)2*Ny*Nz*zs); // Imag part find_coefs_1d_s (spline->x_grid, xBC_i, ((float*)data)+doffset+1, (intptr_t)2*My*Mz, ((float*)coefs)+coffset+1, (intptr_t)2*Ny*Nz*zs); } // Now, solve in the Y-direction for (int ix=0; ix<Nx; ix++) for (int iz=0; iz<Nz; iz++) { intptr_t doffset = 2*(ix*Ny*Nz + iz)*zs; intptr_t coffset = 2*(ix*Ny*Nz + iz)*zs; // Real part find_coefs_1d_s (spline->y_grid, yBC_r, ((float*)coefs)+doffset, (intptr_t)2*Nz*zs, ((float*)coefs)+coffset, (intptr_t)2*Nz*zs); // Imag part find_coefs_1d_s (spline->y_grid, yBC_i, ((float*)coefs)+doffset+1, (intptr_t)2*Nz*zs, ((float*)coefs)+coffset+1, (intptr_t)2*Nz*zs); } // Now, solve in the Z-direction for (int ix=0; ix<Nx; ix++) for (int iy=0; iy<Ny; iy++) { intptr_t doffset = 2*((ix*Ny+iy)*Nz)*zs; intptr_t coffset = 2*((ix*Ny+iy)*Nz)*zs; // Real part find_coefs_1d_s (spline->z_grid, zBC_r, ((float*)coefs)+doffset, (intptr_t)2*zs, ((float*)coefs)+coffset, (intptr_t)2*zs); // Imag part find_coefs_1d_s (spline->z_grid, zBC_i, ((float*)coefs)+doffset+1, (intptr_t)2*zs, ((float*)coefs)+coffset+1, (intptr_t)2*zs); } } void set_multi_UBspline_3d_c_z (multi_UBspline_3d_c* spline, int num, complex_double *data) { // Setup internal variables int Mx = spline->x_grid.num; int My = spline->y_grid.num; int Mz = spline->z_grid.num; int Nx, Ny, Nz; if (spline->xBC.lCode == PERIODIC || spline->xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; if (spline->yBC.lCode == PERIODIC || spline->yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; if (spline->zBC.lCode == PERIODIC || spline->zBC.lCode == ANTIPERIODIC) Nz = Mz+3; else Nz = Mz+2; BCtype_d xBC_r, xBC_i, yBC_r, yBC_i, zBC_r, zBC_i; xBC_r.lCode = spline->xBC.lCode; xBC_r.rCode = spline->xBC.rCode; xBC_r.lVal = (double)spline->xBC.lVal_r; xBC_r.rVal = (double)spline->xBC.rVal_r; xBC_i.lCode = spline->xBC.lCode; xBC_i.rCode = spline->xBC.rCode; xBC_i.lVal = (double)spline->xBC.lVal_i; xBC_i.rVal = (double)spline->xBC.rVal_i; yBC_r.lCode = spline->yBC.lCode; yBC_r.rCode = spline->yBC.rCode; yBC_r.lVal = (double)spline->yBC.lVal_r; yBC_r.rVal = (double)spline->yBC.rVal_r; yBC_i.lCode = spline->yBC.lCode; yBC_i.rCode = spline->yBC.rCode; yBC_i.lVal = (double)spline->yBC.lVal_i; yBC_i.rVal = (double)spline->yBC.rVal_i; zBC_r.lCode = spline->zBC.lCode; zBC_r.rCode = spline->zBC.rCode; zBC_r.lVal = (double)spline->zBC.lVal_r; zBC_r.rVal = (double)spline->zBC.rVal_r; zBC_i.lCode = spline->zBC.lCode; zBC_i.rCode = spline->zBC.rCode; zBC_i.lVal = (double)spline->zBC.lVal_i; zBC_i.rVal = (double)spline->zBC.rVal_i; complex_double *spline_tmp = malloc(2*sizeof(double)*Nx*Ny*Nz); // First, solve in the X-direction for (int iy=0; iy<My; iy++) for (int iz=0; iz<Mz; iz++) { intptr_t doffset = 2*(iy*Mz+iz); intptr_t coffset = 2*(iy*Nz+iz); // Real part find_coefs_1d_d (spline->x_grid, xBC_r, ((double*)data)+doffset, 2*My*Mz, ((double*)spline_tmp)+coffset, 2*Ny*Nz); // Imag part find_coefs_1d_d (spline->x_grid, xBC_i, ((double*)data)+doffset+1, 2*My*Mz, ((double*)spline_tmp)+coffset+1, 2*Ny*Nz); } // Now, solve in the Y-direction for (int ix=0; ix<Nx; ix++) for (int iz=0; iz<Nz; iz++) { intptr_t doffset = 2*(ix*Ny*Nz + iz); intptr_t coffset = 2*(ix*Ny*Nz + iz); // Real part find_coefs_1d_d (spline->y_grid, yBC_r, ((double*)spline_tmp)+doffset, 2*Nz, ((double*)spline_tmp)+coffset, 2*Nz); // Imag part find_coefs_1d_d (spline->y_grid, yBC_i, ((double*)spline_tmp)+doffset+1, 2*Nz, ((double*)spline_tmp)+coffset+1, 2*Nz); } // Now, solve in the Z-direction for (int ix=0; ix<Nx; ix++) for (int iy=0; iy<Ny; iy++) { intptr_t doffset = 2*((ix*Ny+iy)*Nz); intptr_t coffset = 2*((ix*Ny+iy)*Nz); // Real part find_coefs_1d_d (spline->z_grid, zBC_r, ((double*)spline_tmp)+doffset, 2, ((double*)spline_tmp)+coffset, 2); // Imag part find_coefs_1d_d (spline->z_grid, zBC_i, ((double*)spline_tmp)+doffset+1, 2, ((double*)spline_tmp)+coffset+1, 2); } { const complex_double* restrict i_ptr=spline_tmp; for(int ix=0; ix<Nx; ++ix) for(int iy=0; iy<Ny; ++iy) for(int iz=0; iz<Nz; ++iz) spline->coefs[ix*spline->x_stride + iy*spline->y_stride + iz*spline->z_stride + num] = (complex_float)(*i_ptr++); } free(spline_tmp); } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //// Double-Precision, Real Creation Routines //// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // On input, bands should be filled with: // row 0 : abcdInitial from boundary conditions // rows 1:M: basis functions in first 3 cols, data in last // row M+1 : abcdFinal from boundary conditions // cstride gives the stride between values in coefs. // On exit, coefs with contain interpolating B-spline coefs void solve_deriv_interp_1d_d (double bands[], double coefs[], int M, int cstride); // On input, bands should be filled with: // row 0 : abcdInitial from boundary conditions // rows 1:M: basis functions in first 3 cols, data in last // row M+1 : abcdFinal from boundary conditions // cstride gives the stride between values in coefs. // On exit, coefs with contain interpolating B-spline coefs void solve_periodic_interp_1d_d (double bands[], double coefs[], int M, intptr_t cstride); void find_coefs_1d_d (Ugrid grid, BCtype_d bc, double *data, intptr_t dstride, double *coefs, intptr_t cstride); multi_UBspline_1d_d* create_multi_UBspline_1d_d (Ugrid x_grid, BCtype_d xBC, int num_splines) { // Create new spline multi_UBspline_1d_d* restrict spline = malloc (sizeof(multi_UBspline_1d_d)); if (!spline) { fprintf (stderr, "Out of memory allocating spline in create_multi_UBspline_1d_d.\n"); abort(); } spline->spcode = MULTI_U1D; spline->tcode = DOUBLE_REAL; spline->xBC = xBC; spline->num_splines = num_splines; // Setup internal variables int Mx = x_grid.num; int Nx; if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) { x_grid.delta = (x_grid.end-x_grid.start)/(double)(x_grid.num); Nx = Mx+3; } else { x_grid.delta = (x_grid.end-x_grid.start)/(double)(x_grid.num-1); Nx = Mx+2; } x_grid.delta_inv = 1.0/x_grid.delta; spline->x_grid = x_grid; int N = num_splines; #ifdef HAVE_SSE2 // We must pad to keep data aligned for SSE operations if (N & 1) N++; #endif spline->x_stride = N; #ifndef HAVE_POSIX_MEMALIGN spline->coefs = malloc (sizeof(double)*Nx*N); #else posix_memalign ((void**)&spline->coefs, 64, sizeof(double)*Nx*N); #endif spline->coefs_size=(size_t)Nx*(size_t)N; #ifdef HAVE_SSE2 init_sse_data(); #endif if (!spline->coefs) { fprintf (stderr, "Out of memory allocating spline coefficients in create_multi_UBspline_1d_d.\n"); abort(); } return spline; } void set_multi_UBspline_1d_d (multi_UBspline_1d_d* spline, int num, double *data) { double *coefs = spline->coefs + num; int xs = spline->x_stride; find_coefs_1d_d (spline->x_grid, spline->xBC, data, 1, coefs, xs); } void set_multi_UBspline_1d_d_BC (multi_UBspline_1d_d* spline, int num, double *data, BCtype_d xBC) { double *coefs = spline->coefs + num; int xs = spline->x_stride; find_coefs_1d_d (spline->x_grid, xBC, data, 1, coefs, xs); } multi_UBspline_2d_d* create_multi_UBspline_2d_d (Ugrid x_grid, Ugrid y_grid, BCtype_d xBC, BCtype_d yBC, int num_splines) { // Create new spline multi_UBspline_2d_d* restrict spline = malloc (sizeof(multi_UBspline_2d_d)); if (!spline) { fprintf (stderr, "Out of memory allocating spline in create_multi_UBspline_2d_d.\n"); abort(); } spline->spcode = MULTI_U2D; spline->tcode = DOUBLE_REAL; spline->xBC = xBC; spline->yBC = yBC; spline->num_splines = num_splines; // Setup internal variables int Mx = x_grid.num; int My = y_grid.num; int Nx, Ny; if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; x_grid.delta = (x_grid.end - x_grid.start)/(double)(Nx-3); x_grid.delta_inv = 1.0/x_grid.delta; spline->x_grid = x_grid; if (yBC.lCode == PERIODIC || yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; y_grid.delta = (y_grid.end - y_grid.start)/(double)(Ny-3); y_grid.delta_inv = 1.0/y_grid.delta; spline->y_grid = y_grid; int N = num_splines; #ifdef HAVE_SSE2 // We must pad to keep data align for SSE operations if (num_splines & 1) N++; #endif spline->x_stride = Ny*N; spline->y_stride = N; #ifndef HAVE_POSIX_MEMALIGN spline->coefs = malloc (sizeof(double)*Nx*Ny*N); #else posix_memalign ((void**)&spline->coefs, 64, (sizeof(double)*Nx*Ny*N)); #endif #ifdef HAVE_SSE2 init_sse_data(); #endif if (!spline->coefs) { fprintf (stderr, "Out of memory allocating spline coefficients in create_multi_UBspline_2d_d.\n"); abort(); } return spline; } void set_multi_UBspline_2d_d (multi_UBspline_2d_d* spline, int num, double *data) { int Mx = spline->x_grid.num; int My = spline->y_grid.num; int Nx, Ny; double *coefs = spline->coefs + num; if (spline->xBC.lCode == PERIODIC || spline->xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; if (spline->yBC.lCode == PERIODIC || spline->yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; int ys = spline->y_stride; // First, solve in the X-direction for (int iy=0; iy<My; iy++) { intptr_t doffset = iy; intptr_t coffset = iy*ys; find_coefs_1d_d (spline->x_grid, spline->xBC, data+doffset, (intptr_t)My, coefs+coffset, (intptr_t)Ny*ys); } // Now, solve in the Y-direction for (int ix=0; ix<Nx; ix++) { intptr_t doffset = ix*Ny*ys; intptr_t coffset = ix*Ny*ys; find_coefs_1d_d (spline->y_grid, spline->yBC, coefs+doffset, (intptr_t)ys, coefs+coffset, (intptr_t)ys); } } multi_UBspline_3d_d* create_multi_UBspline_3d_d (Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_d xBC, BCtype_d yBC, BCtype_d zBC, int num_splines) { // Create new spline multi_UBspline_3d_d* restrict spline; #ifdef HAVE_POSIX_MEMALIGN posix_memalign ((void**)&spline, 64, (size_t)sizeof(multi_UBspline_3d_d)); #else spline = malloc (sizeof(multi_UBspline_3d_d)); #endif if (!spline) { fprintf (stderr, "Out of memory allocating spline in create_multi_UBspline_3d_d.\n"); abort(); } spline->spcode = MULTI_U3D; spline->tcode = DOUBLE_REAL; spline->xBC = xBC; spline->yBC = yBC; spline->zBC = zBC; spline->num_splines = num_splines; // Setup internal variables int Mx = x_grid.num; int My = y_grid.num; int Mz = z_grid.num; int Nx, Ny, Nz; if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; x_grid.delta = (x_grid.end - x_grid.start)/(double)(Nx-3); x_grid.delta_inv = 1.0/x_grid.delta; spline->x_grid = x_grid; if (yBC.lCode == PERIODIC || yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; y_grid.delta = (y_grid.end - y_grid.start)/(double)(Ny-3); y_grid.delta_inv = 1.0/y_grid.delta; spline->y_grid = y_grid; if (zBC.lCode == PERIODIC || zBC.lCode == ANTIPERIODIC) Nz = Mz+3; else Nz = Mz+2; z_grid.delta = (z_grid.end - z_grid.start)/(double)(Nz-3); z_grid.delta_inv = 1.0/z_grid.delta; spline->z_grid = z_grid; int N = num_splines; #if defined HAVE_SSE2 // We must pad to keep data align for SSE operations if (N & 1) N++; #endif #ifdef BGQPX if (N % 4) N += 4 - (N % 4); // fprintf(stdout, " The coefs has been 32-byte aligned.\n"); #endif spline->x_stride = Ny*Nz*N; spline->y_stride = Nz*N; spline->z_stride = N; #ifdef HAVE_POSIX_MEMALIGN posix_memalign ((void**)&spline->coefs, 64, ((size_t)sizeof(double)*Nx*Ny*Nz*N)); #else spline->coefs = malloc ((size_t)sizeof(double)*Nx*Ny*Nz*N); #endif spline->coefs_size=(size_t)Nx*(size_t)Ny*(size_t)Nz*(size_t)N; #ifdef HAVE_SSE2 init_sse_data(); #endif if (!spline->coefs) { fprintf (stderr, "Out of memory allocating spline coefficients in create_multi_UBspline_3d_d.\n"); abort(); } return spline; } void set_multi_UBspline_3d_d (multi_UBspline_3d_d* spline, int num, double *data) { int Mx = spline->x_grid.num; int My = spline->y_grid.num; int Mz = spline->z_grid.num; int Nx, Ny, Nz; if (spline->xBC.lCode == PERIODIC || spline->xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; if (spline->yBC.lCode == PERIODIC || spline->yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; if (spline->zBC.lCode == PERIODIC || spline->zBC.lCode == ANTIPERIODIC) Nz = Mz+3; else Nz = Mz+2; double *coefs = spline->coefs + num; intptr_t zs = spline->z_stride; // First, solve in the X-direction #pragma omp parallel for for (int iy=0; iy<My; iy++) for (int iz=0; iz<Mz; iz++) { intptr_t doffset = iy*Mz+iz; intptr_t coffset = (iy*Nz+iz)*zs; find_coefs_1d_d (spline->x_grid, spline->xBC, data+doffset, (intptr_t)My*Mz, coefs+coffset, (intptr_t)Ny*Nz*zs); } // Now, solve in the Y-direction #pragma omp parallel for for (int ix=0; ix<Nx; ix++) for (int iz=0; iz<Nz; iz++) { intptr_t doffset = (ix*Ny*Nz + iz)*zs; intptr_t coffset = (ix*Ny*Nz + iz)*zs; find_coefs_1d_d (spline->y_grid, spline->yBC, coefs+doffset, (intptr_t)Nz*zs, coefs+coffset, (intptr_t)Nz*zs); } // Now, solve in the Z-direction #pragma omp parallel for for (int ix=0; ix<Nx; ix++) for (int iy=0; iy<Ny; iy++) { intptr_t doffset = (ix*Ny+iy)*Nz*zs; intptr_t coffset = (ix*Ny+iy)*Nz*zs; find_coefs_1d_d (spline->z_grid, spline->zBC, coefs+doffset, (intptr_t)zs, coefs+coffset, (intptr_t)zs); } } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //// Double-Precision, Complex Creation Routines //// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // On input, bands should be filled with: // row 0 : abcdInitial from boundary conditions // rows 1:M: basis functions in first 3 cols, data in last // row M+1 : abcdFinal from boundary conditions // cstride gives the stride between values in coefs. // On exit, coefs with contain interpolating B-spline coefs multi_UBspline_1d_z* create_multi_UBspline_1d_z (Ugrid x_grid, BCtype_z xBC, int num_splines) { // Create new spline multi_UBspline_1d_z* restrict spline = malloc (sizeof(multi_UBspline_1d_z)); if (!spline) { fprintf (stderr, "Out of memory allocating spline in create_multi_UBspline_1d_z.\n"); abort(); } spline->spcode = MULTI_U1D; spline->tcode = DOUBLE_COMPLEX; spline->xBC = xBC; spline->num_splines = num_splines; // Setup internal variables int Mx = x_grid.num; int Nx; if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) { x_grid.delta = (x_grid.end-x_grid.start)/(double)(x_grid.num); Nx = Mx+3; } else { x_grid.delta = (x_grid.end-x_grid.start)/(double)(x_grid.num-1); Nx = Mx+2; } x_grid.delta_inv = 1.0/x_grid.delta; spline->x_grid = x_grid; spline->x_stride = num_splines; #ifndef HAVE_POSIX_MEMALIGN spline->coefs = malloc (2*sizeof(double)*Nx*num_splines); #else posix_memalign ((void**)&spline->coefs, 64, 2*sizeof(double)*Nx*num_splines); #endif spline->coefs_size=(size_t)Nx*(size_t)num_splines; #ifdef HAVE_SSE2 init_sse_data(); #endif if (!spline->coefs) { fprintf (stderr, "Out of memory allocating spline coefficients in create_multi_UBspline_1d_z.\n"); abort(); } return spline; } void set_multi_UBspline_1d_z (multi_UBspline_1d_z* spline, int num, complex_double *data) { int Mx = spline->x_grid.num; int Nx; complex_double *coefs = spline->coefs + num; if (spline->xBC.lCode == PERIODIC || spline->xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; BCtype_d xBC_r, xBC_i; xBC_r.lCode = spline->xBC.lCode; xBC_r.rCode = spline->xBC.rCode; xBC_r.lVal = spline->xBC.lVal_r; xBC_r.rVal = spline->xBC.rVal_r; xBC_i.lCode = spline->xBC.lCode; xBC_i.rCode = spline->xBC.rCode; xBC_i.lVal = spline->xBC.lVal_i; xBC_i.rVal = spline->xBC.rVal_i; int xs = spline->x_stride; // Real part find_coefs_1d_d (spline->x_grid, xBC_r, (double*)data, (intptr_t)2, ((double*)coefs), (intptr_t)2*xs); // Imaginary part find_coefs_1d_d (spline->x_grid, xBC_i, ((double*)data)+1, (intptr_t)2, ((double*)coefs)+1, (intptr_t)2*xs); } void set_multi_UBspline_1d_z_BC (multi_UBspline_1d_z *spline, int num, complex_double *data, BCtype_z xBC) { int Mx = spline->x_grid.num; int Nx; complex_double *coefs = spline->coefs + num; if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; BCtype_d xBC_r, xBC_i; xBC_r.lCode = xBC.lCode; xBC_r.rCode = xBC.rCode; xBC_r.lVal = xBC.lVal_r; xBC_r.rVal = xBC.rVal_r; xBC_i.lCode = xBC.lCode; xBC_i.rCode = xBC.rCode; xBC_i.lVal = xBC.lVal_i; xBC_i.rVal = xBC.rVal_i; int xs = spline->x_stride; // Real part find_coefs_1d_d (spline->x_grid, xBC_r, (double*)data, (intptr_t)2, ((double*)coefs), (intptr_t)2*xs); // Imaginary part find_coefs_1d_d (spline->x_grid, xBC_i, ((double*)data)+1, (intptr_t)2, ((double*)coefs)+1, (intptr_t)2*xs); } multi_UBspline_2d_z* create_multi_UBspline_2d_z (Ugrid x_grid, Ugrid y_grid, BCtype_z xBC, BCtype_z yBC, int num_splines) { // Create new spline multi_UBspline_2d_z* restrict spline = malloc (sizeof(multi_UBspline_2d_z)); if (!spline) { fprintf (stderr, "Out of memory allocating spline in create_multi_UBspline_2d_z.\n"); abort(); } spline->spcode = MULTI_U2D; spline->tcode = DOUBLE_COMPLEX; spline->xBC = xBC; spline->yBC = yBC; spline->num_splines = num_splines; // Setup internal variables int Mx = x_grid.num; int My = y_grid.num; int Nx, Ny; if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; x_grid.delta = (x_grid.end - x_grid.start)/(double)(Nx-3); x_grid.delta_inv = 1.0/x_grid.delta; spline->x_grid = x_grid; if (yBC.lCode == PERIODIC || yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; y_grid.delta = (y_grid.end - y_grid.start)/(double)(Ny-3); y_grid.delta_inv = 1.0/y_grid.delta; spline->y_grid = y_grid; spline->x_stride = Ny*num_splines; spline->y_stride = num_splines; #ifndef HAVE_POSIX_MEMALIGN spline->coefs = malloc (2*sizeof(double)*Nx*Ny*num_splines); spline->lapl2 = malloc (4*sizeof(double)*num_splines); #else posix_memalign ((void**)&spline->coefs, 64, 2*sizeof(double)*Nx*Ny*num_splines); posix_memalign ((void**)&spline->lapl2, 64, 4*sizeof(double)*num_splines); #endif #ifdef HAVE_SSE2 init_sse_data(); #endif if (!spline->coefs || !spline->lapl2) { fprintf (stderr, "Out of memory allocating spline coefficients in create_multi_UBspline_2d_z.\n"); abort(); } return spline; } void set_multi_UBspline_2d_z (multi_UBspline_2d_z* spline, int num, complex_double *data) { int Mx = spline->x_grid.num; int My = spline->y_grid.num; int Nx, Ny; if (spline->xBC.lCode == PERIODIC || spline->xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; if (spline->yBC.lCode == PERIODIC || spline->yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; BCtype_d xBC_r, xBC_i, yBC_r, yBC_i; xBC_r.lCode = spline->xBC.lCode; xBC_r.rCode = spline->xBC.rCode; xBC_r.lVal = spline->xBC.lVal_r; xBC_r.rVal = spline->xBC.rVal_r; xBC_i.lCode = spline->xBC.lCode; xBC_i.rCode = spline->xBC.rCode; xBC_i.lVal = spline->xBC.lVal_i; xBC_i.rVal = spline->xBC.rVal_i; yBC_r.lCode = spline->yBC.lCode; yBC_r.rCode = spline->yBC.rCode; yBC_r.lVal = spline->yBC.lVal_r; yBC_r.rVal = spline->yBC.rVal_r; yBC_i.lCode = spline->yBC.lCode; yBC_i.rCode = spline->yBC.rCode; yBC_i.lVal = spline->yBC.lVal_i; yBC_i.rVal = spline->yBC.rVal_i; complex_double *coefs = spline->coefs + num; int ys = spline->y_stride; // First, solve in the X-direction for (int iy=0; iy<My; iy++) { intptr_t doffset = 2*iy; intptr_t coffset = 2*iy*ys; // Real part find_coefs_1d_d (spline->x_grid, xBC_r, ((double*)data+doffset), (intptr_t)2*My, (double*)coefs+coffset, (intptr_t)2*Ny*ys); // Imag part find_coefs_1d_d (spline->x_grid, xBC_i, ((double*)data)+doffset+1, (intptr_t)2*My, ((double*)coefs)+coffset+1, (intptr_t)2*Ny*ys); } // Now, solve in the Y-direction for (int ix=0; ix<Nx; ix++) { intptr_t doffset = 2*ix*Ny*ys; intptr_t coffset = 2*ix*Ny*ys; // Real part find_coefs_1d_d (spline->y_grid, yBC_r, ((double*)coefs)+doffset, (intptr_t)2*ys, (double*)coefs+coffset, (intptr_t)2*ys); // Imag part find_coefs_1d_d (spline->y_grid, yBC_i, (double*)coefs+doffset+1, (intptr_t)2*ys, ((double*)coefs)+coffset+1, (intptr_t)2*ys); } } multi_UBspline_3d_z* create_multi_UBspline_3d_z (Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_z xBC, BCtype_z yBC, BCtype_z zBC, int num_splines) { // Create new spline multi_UBspline_3d_z* restrict spline = malloc (sizeof(multi_UBspline_3d_z)); if (!spline) { fprintf (stderr, "Out of memory allocating spline in create_multi_UBspline_3d_z.\n"); abort(); } spline->spcode = MULTI_U3D; spline->tcode = DOUBLE_COMPLEX; spline->xBC = xBC; spline->yBC = yBC; spline->zBC = zBC; spline->num_splines = num_splines; // Setup internal variables int Mx = x_grid.num; int My = y_grid.num; int Mz = z_grid.num; int Nx, Ny, Nz; if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; x_grid.delta = (x_grid.end - x_grid.start)/(double)(Nx-3); x_grid.delta_inv = 1.0/x_grid.delta; spline->x_grid = x_grid; if (yBC.lCode == PERIODIC || yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; y_grid.delta = (y_grid.end - y_grid.start)/(double)(Ny-3); y_grid.delta_inv = 1.0/y_grid.delta; spline->y_grid = y_grid; if (zBC.lCode == PERIODIC || zBC.lCode == ANTIPERIODIC) Nz = Mz+3; else Nz = Mz+2; z_grid.delta = (z_grid.end - z_grid.start)/(double)(Nz-3); z_grid.delta_inv = 1.0/z_grid.delta; spline->z_grid = z_grid; int N = num_splines; #ifdef HAVE_SSE2 if (N & 3) N += 4-(N & 3); #endif #ifdef BGQPX if (N % 2) N += 2 - (N % 2); // fprintf(stdout, " The coefs has been 32-byte aligned.\n"); #endif spline->x_stride = (intptr_t)Ny*(intptr_t)Nz*N; spline->y_stride = Nz*N; spline->z_stride = N; #ifndef HAVE_POSIX_MEMALIGN spline->coefs = malloc ((size_t)2*sizeof(double)*Nx*Ny*Nz*N); spline->lapl3 = malloc (6*sizeof(double)*N); #else posix_memalign ((void**)&spline->coefs, 64, (size_t)2*sizeof(double)*Nx*Ny*Nz*N); posix_memalign ((void**)&spline->lapl3, 64, 6*sizeof(double)*N); #endif spline->coefs_size=(size_t)Nx*(size_t)Ny*(size_t)Nz*(size_t)N; #ifdef HAVE_SSE2 init_sse_data(); #endif if (!spline->coefs || !spline->lapl3) { fprintf (stderr, "Out of memory allocating spline coefficients in create_multi_UBspline_3d_z.\n"); abort(); } return spline; } void set_multi_UBspline_3d_z (multi_UBspline_3d_z* spline, int num, complex_double *data) { // Setup internal variables int Mx = spline->x_grid.num; int My = spline->y_grid.num; int Mz = spline->z_grid.num; int Nx, Ny, Nz; if (spline->xBC.lCode == PERIODIC || spline->xBC.lCode == ANTIPERIODIC) Nx = Mx+3; else Nx = Mx+2; if (spline->yBC.lCode == PERIODIC || spline->yBC.lCode == ANTIPERIODIC) Ny = My+3; else Ny = My+2; if (spline->zBC.lCode == PERIODIC || spline->zBC.lCode == ANTIPERIODIC) Nz = Mz+3; else Nz = Mz+2; BCtype_d xBC_r, xBC_i, yBC_r, yBC_i, zBC_r, zBC_i; xBC_r.lCode = spline->xBC.lCode; xBC_r.rCode = spline->xBC.rCode; xBC_r.lVal = spline->xBC.lVal_r; xBC_r.rVal = spline->xBC.rVal_r; xBC_i.lCode = spline->xBC.lCode; xBC_i.rCode = spline->xBC.rCode; xBC_i.lVal = spline->xBC.lVal_i; xBC_i.rVal = spline->xBC.rVal_i; yBC_r.lCode = spline->yBC.lCode; yBC_r.rCode = spline->yBC.rCode; yBC_r.lVal = spline->yBC.lVal_r; yBC_r.rVal = spline->yBC.rVal_r; yBC_i.lCode = spline->yBC.lCode; yBC_i.rCode = spline->yBC.rCode; yBC_i.lVal = spline->yBC.lVal_i; yBC_i.rVal = spline->yBC.rVal_i; zBC_r.lCode = spline->zBC.lCode; zBC_r.rCode = spline->zBC.rCode; zBC_r.lVal = spline->zBC.lVal_r; zBC_r.rVal = spline->zBC.rVal_r; zBC_i.lCode = spline->zBC.lCode; zBC_i.rCode = spline->zBC.rCode; zBC_i.lVal = spline->zBC.lVal_i; zBC_i.rVal = spline->zBC.rVal_i; complex_double *coefs = spline->coefs + num; int N = spline->num_splines; int zs = spline->z_stride; // First, solve in the X-direction #pragma omp parallel { for (int iy=0; iy<My; iy++) { #pragma omp for for (int iz=0; iz<Mz; iz++) { intptr_t doffset = 2*(iy*Mz+iz); intptr_t coffset = 2*(iy*Nz+iz)*zs; // Real part find_coefs_1d_d (spline->x_grid, xBC_r, ((double*)data)+doffset, (intptr_t)2*My*Mz, ((double*)coefs)+coffset, (intptr_t)2*Ny*Nz*zs); // Imag part find_coefs_1d_d (spline->x_grid, xBC_i, ((double*)data)+doffset+1, (intptr_t)2*My*Mz, ((double*)coefs)+coffset+1, (intptr_t)2*Ny*Nz*zs); } } // Now, solve in the Y-direction for (int ix=0; ix<Nx; ix++) { #pragma omp for for (int iz=0; iz<Nz; iz++) { intptr_t doffset = 2*(ix*Ny*Nz + iz)*zs; intptr_t coffset = 2*(ix*Ny*Nz + iz)*zs; // Real part find_coefs_1d_d (spline->y_grid, yBC_r, ((double*)coefs)+doffset, (intptr_t)2*Nz*zs, ((double*)coefs)+coffset, (intptr_t)2*Nz*zs); // Imag part find_coefs_1d_d (spline->y_grid, yBC_i, ((double*)coefs)+doffset+1, (intptr_t)2*Nz*zs, ((double*)coefs)+coffset+1, (intptr_t)2*Nz*zs); } } // Now, solve in the Z-direction for (int ix=0; ix<Nx; ix++) { #pragma omp for for (int iy=0; iy<Ny; iy++) { intptr_t doffset = 2*((ix*Ny+iy)*Nz)*zs; intptr_t coffset = 2*((ix*Ny+iy)*Nz)*zs; // Real part find_coefs_1d_d (spline->z_grid, zBC_r, ((double*)coefs)+doffset, (intptr_t)2*zs, ((double*)coefs)+coffset, (intptr_t)2*zs); // Imag part find_coefs_1d_d (spline->z_grid, zBC_i, ((double*)coefs)+doffset+1, (intptr_t)2*zs, ((double*)coefs)+coffset+1, (intptr_t)2*zs); } } } } void destroy_multi_UBspline (Bspline *spline) { free (spline->coefs); free (spline); }
GB_unop__identity_int16_uint64.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_int16_uint64) // op(A') function: GB (_unop_tran__identity_int16_uint64) // C type: int16_t // A type: uint64_t // cast: int16_t cij = (int16_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint64_t #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_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) \ int16_t z = (int16_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int16_t z = (int16_t) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT16 || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int16_uint64) ( int16_t *Cx, // Cx and Ax may be aliased const uint64_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++) { uint64_t aij = Ax [p] ; int16_t z = (int16_t) 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 ; uint64_t aij = Ax [p] ; int16_t z = (int16_t) 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_int16_uint64) ( 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
fista.h
/* Software SPAMS v2.1 - Copyright 2009-2011 Julien Mairal * * This file is part of SPAMS. * * SPAMS 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 of the License, or * (at your option) any later version. * * SPAMS 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 SPAMS. If not, see <http://www.gnu.org/licenses/>. */ #ifndef FISTA_H #define FISTA_H #include <linalg.h> #include <project.h> namespace FISTA { enum loss_t { SQUARE, SQUARE_MISSING, LOG, LOGWEIGHT, MULTILOG, CUR, HINGE, INCORRECT_LOSS}; enum regul_t { L0, L1, RIDGE, L2, LINF, ELASTICNET, FUSEDLASSO, GROUPLASSO_L2, GROUPLASSO_LINF, GROUPLASSO_L2_L1, GROUPLASSO_LINF_L1, L1L2, L1LINF, L1L2_L1, L1LINF_L1, TREE_L0, TREE_L2, TREE_LINF, GRAPH, GRAPH_RIDGE, GRAPH_L2, TREEMULT, GRAPHMULT, L1LINFCR, NONE, TRACE_NORM, TRACE_NORM_VEC, RANK, RANK_VEC, INCORRECT_REG, GRAPH_PATH_L0, GRAPH_PATH_CONV}; regul_t regul_from_string(char* regul) { if (strcmp(regul,"l0")==0) return L0; if (strcmp(regul,"l1")==0) return L1; if (strcmp(regul,"l2")==0) return RIDGE; if (strcmp(regul,"linf")==0) return LINF; if (strcmp(regul,"l2-not-squared")==0) return L2; if (strcmp(regul,"elastic-net")==0) return ELASTICNET; if (strcmp(regul,"fused-lasso")==0) return FUSEDLASSO; if (strcmp(regul,"group-lasso-l2")==0) return GROUPLASSO_L2; if (strcmp(regul,"group-lasso-linf")==0) return GROUPLASSO_LINF; if (strcmp(regul,"sparse-group-lasso-l2")==0) return GROUPLASSO_L2_L1; if (strcmp(regul,"sparse-group-lasso-linf")==0) return GROUPLASSO_LINF_L1; if (strcmp(regul,"l1l2")==0) return L1L2; if (strcmp(regul,"l1linf")==0) return L1LINF; if (strcmp(regul,"l1l2+l1")==0) return L1L2_L1; if (strcmp(regul,"l1linf+l1")==0) return L1LINF_L1; if (strcmp(regul,"tree-l0")==0) return TREE_L0; if (strcmp(regul,"tree-l2")==0) return TREE_L2; if (strcmp(regul,"tree-linf")==0) return TREE_LINF; if (strcmp(regul,"graph")==0) return GRAPH; if (strcmp(regul,"graph-ridge")==0) return GRAPH_RIDGE; if (strcmp(regul,"graph-l2")==0) return GRAPH_L2; if (strcmp(regul,"multi-task-tree")==0) return TREEMULT; if (strcmp(regul,"multi-task-graph")==0) return GRAPHMULT; if (strcmp(regul,"l1linf-row-column")==0) return L1LINFCR; if (strcmp(regul,"trace-norm")==0) return TRACE_NORM; if (strcmp(regul,"trace-norm-vec")==0) return TRACE_NORM_VEC; if (strcmp(regul,"rank")==0) return RANK; if (strcmp(regul,"rank-vec")==0) return RANK_VEC; if (strcmp(regul,"graph-path-l0")==0) return GRAPH_PATH_L0; if (strcmp(regul,"graph-path-conv")==0) return GRAPH_PATH_CONV; if (strcmp(regul,"none")==0) return NONE; return INCORRECT_REG; } loss_t loss_from_string(char* loss) { if (strcmp(loss,"square")==0) return SQUARE; if (strcmp(loss,"square-missing")==0) return SQUARE_MISSING; if (strcmp(loss,"logistic")==0) return LOG; if (strcmp(loss,"weighted-logistic")==0) return LOGWEIGHT; if (strcmp(loss,"hinge")==0) return HINGE; if (strcmp(loss,"multi-logistic")==0) return MULTILOG; if (strcmp(loss,"cur")==0) return CUR; return INCORRECT_LOSS; } void print_loss(const loss_t& loss) { switch (loss) { case SQUARE: cout << "Square loss" << endl; break; case SQUARE_MISSING: cout << "Square loss with missing data" << endl; break; case LOG: cout << "Logistic loss" << endl; break; case LOGWEIGHT: cout << "Weighted Logistic loss" << endl; break; case HINGE: cout << "Hinge loss" << endl; break; case MULTILOG: cout << "Multiclass logistic Loss" << endl; break; case CUR: cout << "CUR decomposition" << endl; break; default: cerr << "Not implemented" << endl; } }; bool loss_for_matrices(const loss_t& loss) { return loss==MULTILOG || loss==CUR; } void print_regul(const regul_t& regul) { switch (regul) { case L0: cout << "L0 regularization" << endl; break; case L1: cout << "L1 regularization" << endl; break; case RIDGE: cout << "L2-squared regularization" << endl; break; case L2: cout << "L2-not-squared regularization" << endl; break; case LINF: cout << "Linf regularization" << endl; break; case ELASTICNET: cout << "Elastic-net regularization" << endl; break; case FUSEDLASSO: cout << "Fused Lasso or total variation regularization" << endl; break; case GROUPLASSO_L2: cout << "Group Lasso L2" << endl; break; case GROUPLASSO_LINF: cout << "Group Lasso LINF" << endl; break; case GROUPLASSO_L2_L1: cout << "Group Lasso L2 + L1" << endl; break; case GROUPLASSO_LINF_L1: cout << "Group Lasso LINF + L1" << endl; break; case L1L2: cout << "L1L2 regularization" << endl; break; case L1LINF: cout << "L1LINF regularization" << endl; break; case TRACE_NORM: cout << "Trace Norm regularization" << endl; break; case TRACE_NORM_VEC: cout << "Trace Norm regularization for vectors" << endl; break; case RANK: cout << "Rank regularization" << endl; break; case RANK_VEC: cout << "Rank regularization for vectors" << endl; break; case L1L2_L1: cout << "L1L2 regularization + L1" << endl; break; case L1LINF_L1: cout << "L1LINF regularization + L1" << endl; break; case TREE_L0: cout << "Tree-L0 regularization" << endl; break; case TREE_L2: cout << "Tree-L2 regularization" << endl; break; case TREE_LINF: cout << "Tree-Linf regularization" << endl; break; case GRAPH: cout << "Graph regularization" << endl; break; case GRAPH_RIDGE: cout << "Graph+ridge regularization" << endl; break; case GRAPH_L2: cout << "Graph regularization with l2" << endl; break; case TREEMULT: cout << "multitask tree regularization" << endl; break; case GRAPHMULT: cout << "multitask graph regularization" << endl; break; case L1LINFCR: cout << "L1LINF regularization on rows and columns" << endl; break; case GRAPH_PATH_L0: cout << "Graph path non-convex regularization" << endl; break; case GRAPH_PATH_CONV: cout << "Graph path convex regularization" << endl; break; case NONE: cout << "No regularization" << endl; break; default: cerr << "Not implemented" << endl; } }; bool regul_for_matrices(const regul_t& regul) { return regul==L1L2 || regul==L1LINF || regul==L1L2_L1 || regul==L1LINF_L1 || regul==TREEMULT || regul==GRAPHMULT || regul==L1LINFCR || regul==TRACE_NORM || regul==RANK; } template <typename T> struct ParamFISTA { ParamFISTA() { num_threads=1; max_it=100; L0=0.1; gamma=1.5; tol=1e-10; it0=10; max_iter_backtracking=1000; loss=SQUARE; compute_gram=false; admm=false; lin_admm=false; intercept=false; regul=RIDGE; resetflow=false; delta=0; lambda2=0; lambda3=0; verbose=false; pos=false; clever=true; a=1.0; b=0.0; c=1.0; log=false; logName=NULL; ista=false; subgrad=false; length_names=30; name_regul=new char[length_names]; name_loss=new char[length_names]; is_inner_weights=false; inner_weights=NULL; eval=false; size_group=1; sqrt_step=true; transpose=false; fixed_step=false; copied=false; groups=NULL; ngroups=0; } ~ParamFISTA() { if (!copied) { delete[](name_regul); delete[](name_loss); } }; int num_threads; int max_it; T L0; T gamma; int length_names; T lambda; T delta; T lambda2; T lambda3; T a; T b; T c; T tol; int it0; int max_iter_backtracking; loss_t loss; bool compute_gram; bool lin_admm; bool admm; bool intercept; bool resetflow; regul_t regul; char* name_regul; char* name_loss; bool verbose; bool pos; bool clever; bool log; bool ista; bool copied; bool subgrad; char* logName; bool is_inner_weights; T* inner_weights; bool eval; int size_group; bool sqrt_step; bool transpose; bool fixed_step; int* groups; int ngroups; }; template <typename T> struct ParamReg { ParamReg() { size_group=1; lambda2d1 = 0; lambda3d1 = 0; pos=false; intercept=false; num_cols=1; graph_st=NULL; tree_st=NULL; graph_path_st=NULL; resetflow=false; clever=false; linf=true; transpose=false; ngroups=0; groups=NULL;}; T lambda2d1; T lambda3d1; int size_group; bool pos; bool intercept; int num_cols; GraphPathStruct<T>* graph_path_st; GraphStruct<T>* graph_st; TreeStruct<T>* tree_st; bool resetflow; bool clever; bool linf; bool transpose; int ngroups; int* groups; }; template <typename T> bool param_for_admm(const ParamFISTA<T>& param) { return (param.admm) && (param.loss==SQUARE || param.loss == HINGE) && (param.regul==GRAPH_L2 || param.regul==GRAPH || param.regul == NONE); }; template <typename T, typename F = Matrix<T>, typename D = Vector<T> , typename E = Vector<T> > class SplittingFunction { public: SplittingFunction() { }; virtual ~SplittingFunction() { }; virtual void init(const E& y) { }; virtual T eval(const D& input) const = 0; virtual void reset() { }; virtual T eval_split(const F& input) const = 0; virtual T eval_weighted(const D& input,const F& input_struct, const T* weights) const { return this->eval(input);}; virtual int num_components() const = 0; virtual void prox_split(F& splitted_w, const T lambda) const = 0; virtual void init_split_variables(F& splitted_w) const = 0; virtual void init_prim_var(E& prim_var) const { }; virtual void prox_prim_var(E& out,const E& dual_var, const E& prim_var, const T gamma) const { }; virtual void compute_new_prim(E& prim, const E& prim_var, const E& dual_var, const T gamma, const T delta) const { }; virtual void add_mult_design_matrix(const E& prim, E& out, const T fact) const { }; private: explicit SplittingFunction<T,F,D,E>(const SplittingFunction<T,F,D,E>& loss); SplittingFunction<T,F,D,E>& operator=(const SplittingFunction<T,F,D,E>& loss); }; template <typename T, typename D = Vector<T> , typename E = Vector<T> > class Loss { public: Loss() { }; virtual ~Loss() { }; virtual void init(const E& input) = 0; virtual T eval(const D& input) const = 0; virtual void grad(const D& input, D& output) const = 0; virtual inline bool test_backtracking(const D& y, const D& grad, const D& prox, const T L) const { D tmp; tmp.copy(prox); tmp.sub(y); return (this->eval(prox) <= this->eval(y) + grad.dot(tmp) + 0.5*L*tmp.nrm2sq()); }; virtual T fenchel(const D& input) const = 0; virtual bool is_fenchel() const { return true; }; virtual void var_fenchel(const D& x, D& grad1, D& grad2, const bool intercept = false) const = 0; private: explicit Loss<T,D,E>(const Loss<T,D,E>& dict); Loss<T,D,E>& operator=(const Loss<T,D,E>& dict); }; template <typename T> class SqLossMissing : public Loss<T> { public: SqLossMissing(const AbstractMatrixB<T>& D) : _D(&D) { }; virtual ~SqLossMissing() { }; inline void init(const Vector<T>& x) { _x.copy(x); _missingvalues.clear(); for (int i = 0; i<_x.n(); ++i) { if (isnan(_x[i])) { _x[i]=0; _missingvalues.push_back(i); } } }; inline T eval(const Vector<T>& alpha) const { Vector<T> residual; residual.copy(_x); SpVector<T> spalpha(alpha.n()); alpha.toSparse(spalpha); _D->mult(spalpha,residual,T(-1.0),T(1.0)); for (ListIterator<int> it = _missingvalues.begin(); it != _missingvalues.end(); ++it) residual[*it]=0; return 0.5*residual.nrm2sq(); } inline void grad(const Vector<T>& alpha, Vector<T>& grad) const { Vector<T> residual; residual.copy(_x); SpVector<T> spalpha(alpha.n()); alpha.toSparse(spalpha); _D->mult(spalpha,residual,T(-1.0),T(1.0)); for (ListIterator<int> it = _missingvalues.begin(); it != _missingvalues.end(); ++it) residual[*it]=0; _D->multTrans(residual,grad,T(-1.0),T(0.0)); }; virtual T fenchel(const Vector<T>& input) const { return 0.5*input.nrm2sq()+input.dot(_x); }; virtual void var_fenchel(const Vector<T>& x, Vector<T>& grad1, Vector<T>& grad2, const bool intercept) const { grad1.copy(_x); SpVector<T> spalpha(x.n()); x.toSparse(spalpha); _D->mult(spalpha,grad1,T(1.0),T(-1.0)); for (ListIterator<int> it = _missingvalues.begin(); it != _missingvalues.end(); ++it) grad1[*it]=0; if (intercept) grad1.whiten(1); // remove the mean of grad1 _D->multTrans(grad1,grad2,T(1.0),T(0.0)); }; private: explicit SqLossMissing<T>(const SqLossMissing<T>& dict); SqLossMissing<T>& operator=(const SqLossMissing<T>& dict); const AbstractMatrixB<T>* _D; Vector<T> _x; List<int> _missingvalues; }; template <typename T> class SqLoss : public Loss<T>, public SplittingFunction<T> { public: SqLoss(const AbstractMatrixB<T>& D) : _D(&D) { _compute_gram = false; }; SqLoss(const AbstractMatrixB<T>& D, const Matrix<T>& G) : _D(&D), _G(&G) { _compute_gram = true; }; virtual ~SqLoss() { }; inline void init(const Vector<T>& x) { _x.copy(x); if (_compute_gram) { _D->multTrans(x,_DtX); } }; inline T eval(const Vector<T>& alpha) const { Vector<T> residual; residual.copy(_x); SpVector<T> spalpha(alpha.n()); alpha.toSparse(spalpha); if (spalpha.L() < alpha.n()/2) { _D->mult(spalpha,residual,T(-1.0),T(1.0)); } else { _D->mult(alpha,residual,T(-1.0),T(1.0)); } return 0.5*residual.nrm2sq(); } inline void grad(const Vector<T>& alpha, Vector<T>& grad) const { if (_compute_gram) { grad.copy(_DtX); SpVector<T> spalpha(alpha.n()); alpha.toSparse(spalpha); _G->mult(spalpha,grad,T(1.0),-T(1.0)); } else { Vector<T> residual; residual.copy(_x); SpVector<T> spalpha(alpha.n()); alpha.toSparse(spalpha); _D->mult(spalpha,residual,T(-1.0),T(1.0)); _D->multTrans(residual,grad,T(-1.0),T(0.0)); } }; virtual inline bool test_backtracking(const Vector<T>& y, const Vector<T>& grad, const Vector<T>& prox, const T L) const { Vector<T> tmp; tmp.copy(y); tmp.sub(prox); SpVector<T> sptmp(tmp.n()); tmp.toSparse(sptmp); if (_compute_gram) { return (_G->quad(sptmp) <= L*sptmp.nrm2sq()); } else { Vector<T> tmp2(_D->m()); _D->mult(sptmp,tmp2); return (tmp2.nrm2sq() <= L*sptmp.nrm2sq()); } }; virtual T fenchel(const Vector<T>& input) const { return 0.5*input.nrm2sq()+input.dot(_x); }; virtual void var_fenchel(const Vector<T>& x, Vector<T>& grad1, Vector<T>& grad2, const bool intercept) const { grad1.copy(_x); SpVector<T> spalpha(x.n()); x.toSparse(spalpha); _D->mult(spalpha,grad1,T(1.0),T(-1.0)); if (intercept) grad1.whiten(1); // remove the mean of grad1 _D->multTrans(grad1,grad2,T(1.0),T(0.0)); }; inline int num_components() const { return _D->m();}; inline void prox_split(Matrix<T>& splitted_w, const T lambda) const { const int n = this->num_components(); Vector<T> row(_D->n()); Vector<T> wi; for (int i = 0; i<n; ++i) { _D->copyRow(i,row); splitted_w.refCol(i,wi); const T xtw=row.dot(wi); const T xtx=row.dot(row); wi.add(row,-lambda*(xtw-_x[i])/(T(1.0)+lambda*xtx)); } }; inline T eval_split(const Matrix<T>& input) const { const int n = this->num_components(); Vector<T> row(_D->n()); Vector<T> wi; T sum = 0; for (int i = 0; i<n; ++i) { _D->copyRow(i,row); input.refCol(i,wi); const T xtw=row.dot(wi); sum += 0.5*(_x[i]-xtw)*(_x[i]-xtw); } return sum; }; inline void init_split_variables(Matrix<T>& splitted_w) const { splitted_w.resize(_D->n(),_D->m()); splitted_w.setZeros(); }; inline void init_prim_var(Vector<T>& prim_var) const { prim_var.resize(_D->m()); prim_var.setZeros(); } virtual void prox_prim_var(Vector<T>& out,const Vector<T>& dual_var, const Vector<T>& prim_var, const T c) const { const T gamma=T(1.0)/c; out.copy(dual_var); out.scal(-gamma); _D->mult(prim_var,out,T(1.0),T(1.0)); out.add(_x,gamma); out.scal(T(1.0)/(T(1.0)+gamma)); }; inline void compute_new_prim(Vector<T>& prim, const Vector<T>& prim_var, const Vector<T>& dual_var, const T gamma, const T delta) const { Vector<T> tmp; _D->mult(prim,tmp); tmp.scal(-gamma); tmp.add(prim_var); tmp.add(dual_var,gamma); _D->multTrans(tmp,prim,T(1.0),delta); }; inline void add_mult_design_matrix(const Vector<T>& prim, Vector<T>& out, const T fact) const { _D->mult(prim,out,fact,T(1.0)); }; private: explicit SqLoss<T>(const SqLoss<T>& dict); SqLoss<T>& operator=(const SqLoss<T>& dict); const AbstractMatrixB<T>* _D; Vector<T> _x; bool _compute_gram; const Matrix<T>* _G; Vector<T> _DtX; }; template <typename T> class HingeLoss : public SplittingFunction<T > { public: HingeLoss(const AbstractMatrixB<T>& X) : _X(&X) { }; virtual ~HingeLoss() { }; inline void init(const Vector<T>& y) { _y.copy(y); }; inline T eval(const Vector<T>& w) const { Vector<T> tmp(_X->m()); SpVector<T> spw(w.n()); w.toSparse(spw); _X->mult(spw,tmp); tmp.mult(_y,tmp); tmp.neg(); tmp.add(T(1.0)); tmp.thrsPos(); return tmp.sum()/tmp.n(); }; virtual T eval_split(const Matrix<T>& input) const { Vector<T> row(_X->n()); Vector<T> wi; T sum = 0; for (int i = 0; i<_X->n(); ++i) { _X->copyRow(i,row); input.refCol(i,wi); sum += MAX(0,T(1.0)-_y[i]*row.dot(wi)); } return sum/_X->m(); }; virtual int num_components() const { return _X->m(); }; inline void init_split_variables(Matrix<T>& splitted_w) const { splitted_w.resize(_X->n(),_X->m()); splitted_w.setZeros(); }; inline void init_prim_var(Vector<T>& prim_var) const { prim_var.resize(_X->m()); prim_var.setZeros(); } inline void prox_prim_var(Vector<T>& out,const Vector<T>& dual_var, const Vector<T>& prim_var, const T lambda, const T c) const { const T gamma=T(1.0)/c; out.copy(dual_var); out.scal(-gamma); _X->mult(prim_var,out,T(1.0),T(1.0)); const T thrs=T(1.0)-gamma; for (int i = 0; i<out.n(); ++i) { const T y = _y[i]*out[i]; if (y < thrs) { out[i]+=_y[i]*gamma; } else if (y < T(1.0)) { out[i]=_y[i]; } } } inline void compute_new_prim(Vector<T>& prim, const Vector<T>& prim_var, const Vector<T>& dual_var, const T gamma, const T delta) const { Vector<T> tmp; _X->mult(prim,tmp); tmp.scal(-gamma); tmp.add(prim_var); tmp.add(dual_var,gamma); _X->multTrans(tmp,prim,T(1.0),delta); }; inline void add_mult_design_matrix(const Vector<T>& prim, Vector<T>& out, const T fact) const { _X->mult(prim,out,fact,T(1.0)); }; inline void prox_split(Matrix<T>& splitted_w, const T lambda) const { const int n = this->num_components(); Vector<T> row(_X->n()); Vector<T> wi; for (int i = 0; i<n; ++i) { _X->copyRow(i,row); splitted_w.refCol(i,wi); const T xtw=row.dot(wi); const T xtx=row.dot(row); const T diff=1-_y[i]*xtw; if (diff > lambda*xtx) { wi.add(row,lambda*_y[i]); } else if (diff > 0) { wi.add(row,_y[i]*diff/xtx); } } }; private: explicit HingeLoss<T>(const HingeLoss<T>& dict); HingeLoss<T>& operator=(const HingeLoss<T>& dict); const AbstractMatrixB<T>* _X; Vector<T> _y; }; template <typename T, bool weighted = false> class LogLoss : public Loss<T> { public: LogLoss(const AbstractMatrixB<T>& X) : _X(&X) { }; virtual ~LogLoss() { }; inline void init(const Vector<T>& y) { _y.copy(y); if (weighted) { int countpos=0; for (int i = 0; i<y.n(); ++i) if (y[i]>0) countpos++; _weightpos=T(1.0)/countpos; _weightneg=T(1.0)/MAX(1e-3,(y.n()-countpos)); } }; inline T eval(const Vector<T>& w) const { Vector<T> tmp(_X->m()); SpVector<T> spw(w.n()); w.toSparse(spw); _X->mult(spw,tmp); tmp.mult(_y,tmp); tmp.neg(); tmp.logexp(); if (weighted) { T sum=0; for (int i = 0; i<tmp.n(); ++i) sum+= _y[i]>0 ? _weightpos*tmp[i] : _weightneg*tmp[i]; return sum; } else { return tmp.sum()/tmp.n(); } }; inline void grad(const Vector<T>& w, Vector<T>& grad) const { Vector<T> tmp(_X->m()); SpVector<T> spw(w.n()); w.toSparse(spw); _X->mult(spw,tmp); tmp.mult(_y,tmp); tmp.exp(); tmp.add(T(1.0)); tmp.inv(); tmp.mult(_y,tmp); tmp.neg(); if (weighted) { for (int i = 0; i<tmp.n(); ++i) tmp[i] *= _y[i] > 0 ? _weightpos : _weightneg; _X->multTrans(tmp,grad); } else { _X->multTrans(tmp,grad); grad.scal(T(1.0)/_X->m()); } }; virtual bool is_fenchel() const { return !weighted; }; virtual T fenchel(const Vector<T>& input) const { T sum = 0; if (weighted) { for (int i = 0; i<input.n(); ++i) { T prod = _y[i]>0 ? input[i]/_weightpos : -input[i]/_weightneg; sum += _y[i] >0 ? _weightpos*(xlogx(1.0+prod)+xlogx(-prod)) : _weightneg*(xlogx(1.0+prod)+xlogx(-prod)); } return sum; } else { for (int i = 0; i<input.n(); ++i) { T prod = _y[i]*input[i]*_X->m(); sum += xlogx(1.0+prod)+xlogx(-prod); } return sum/_X->m(); } }; virtual void var_fenchel(const Vector<T>& w, Vector<T>& grad1, Vector<T>& grad2, const bool intercept) const { grad1.resize(_X->m()); SpVector<T> spw(w.n()); w.toSparse(spw); _X->mult(spw,grad1); grad1.mult(_y,grad1); grad1.exp(); grad1.add(T(1.0)); grad1.inv(); grad1.mult(_y,grad1); grad1.neg(); // -gradient (no normalization) if (intercept) grad1.project_sft_binary(_y); grad1.scal(T(1.0)/_X->m()); _X->multTrans(grad1,grad2); }; private: explicit LogLoss<T,weighted>(const LogLoss<T,weighted>& dict); LogLoss<T,weighted>& operator=(const LogLoss<T,weighted>& dict); const AbstractMatrixB<T>* _X; Vector<T> _y; T _weightpos; T _weightneg; }; template <typename T> class MultiLogLoss : public Loss<T, Matrix<T> > { public: MultiLogLoss(const AbstractMatrixB<T>& X) : _X(&X) { }; virtual ~MultiLogLoss() { }; inline void init(const Vector<T>& y) { _y.resize(y.n()); for (int i = 0; i<y.n(); ++i) _y[i] = static_cast<int>(y[i]); }; inline T eval(const Matrix<T>& W) const { Matrix<T> tmp; _X->multSwitch(W,tmp,true,true); //W.mult(*_X,tmp,true,true); Vector<T> col; T sum=0; for (int i = 0; i<tmp.n(); ++i) { tmp.refCol(i,col); sum+=col.softmax(_y[i]); } return sum/tmp.n(); }; inline void grad(const Matrix<T>& W, Matrix<T>& grad) const { Matrix<T> tmp; _X->multSwitch(W,tmp,true,true); //W.mult(*_X,tmp,true,true); Vector<T> col; grad.resize(W.m(),W.n()); for (int i = 0; i<tmp.n(); ++i) { tmp.refCol(i,col); col.add(-col[_y[i]]); bool overweight=false; for (int j = 0; j<col.n(); ++j) if (col[j] > 1e2) overweight=true; if (overweight) { const int ind =col.fmax(); col.setZeros(); col[ind]=1; } else { col.exp(); col.scal(T(1.0)/col.sum()); col.scal(T(1.0)/col.sum()); } col[_y[i]] = col[_y[i]]-T(1.0); } _X->mult(tmp,grad,true,true); grad.scal(T(1.0)/_X->m()); }; virtual T fenchel(const Matrix<T>& input) const { T sum = 0; Vector<T> col; for (int i = 0; i<input.n(); ++i) { const int clas = _y[i]; input.refCol(i,col); for (int j = 0; j<input.m(); ++j) { if (j == clas) { sum += xlogx(_X->m()*input[i*input.m()+j]+1.0); } else { sum += xlogx(_X->m()*input[i*input.m()+j]); } } } return sum/_X->m(); }; virtual void var_fenchel(const Matrix<T>& W, Matrix<T>& grad1, Matrix<T>& grad2, const bool intercept) const { _X->multSwitch(W,grad1,true,true); //W.mult(*_X,grad1,true,true); Vector<T> col; for (int i = 0; i<grad1.n(); ++i) { grad1.refCol(i,col); col.add(-col[_y[i]]); bool overweight=false; for (int j = 0; j<col.n(); ++j) if (col[j] > 1e2) overweight=true; if (overweight) { const int ind =col.fmax(); col.setZeros(); col[ind]=1; } else { col.exp(); col.scal(T(1.0)/col.sum()); col.scal(T(1.0)/col.sum()); } col[_y[i]] = col[_y[i]]-T(1.0); } if (intercept) { Vector<T> row; for (int i = 0; i<grad1.m(); ++i) { grad1.extractRow(i,row); row.project_sft(_y,i); grad1.setRow(i,row); } } grad1.scal(T(1.0)/_X->m()); grad2.resize(W.m(),W.n()); _X->mult(grad1,grad2,true,true); }; private: explicit MultiLogLoss<T>(const MultiLogLoss<T>& dict); MultiLogLoss<T>& operator=(const MultiLogLoss<T>& dict); const AbstractMatrixB<T>* _X; Vector<int> _y; }; template <typename T> class LossCur: public Loss<T, Matrix<T>, Matrix<T> > { public: LossCur(const AbstractMatrixB<T>& X) : _X(&X) { }; virtual ~LossCur() { }; inline void init(const Matrix<T>& y) { }; inline T eval(const Matrix<T>& A) const { Matrix<T> tmp(_X->m(),A.n()); _X->mult(A,tmp); Matrix<T> tmp2; //tmp2.copy(*_X); _X->copyTo(tmp2); //tmp.mult(*_X,tmp2,false,false,T(-1.0),T(1.0)); _X->multSwitch(tmp,tmp2,false,false,T(-1.0),T(1.0)); return 0.5*tmp2.normFsq(); }; inline void grad(const Matrix<T>& A, Matrix<T>& grad) const { Matrix<T> tmp(_X->m(),A.n()); _X->mult(A,tmp); Matrix<T> tmp2; //tmp2.copy(*_X); _X->copyTo(tmp2); //tmp.mult(*_X,tmp2,false,false,T(-1.0),T(1.0)); _X->multSwitch(tmp,tmp2,false,false,T(-1.0),T(1.0)); //tmp2.mult(*_X,tmp,false,true,T(-1.0),T(0.0)); _X->multSwitch(tmp2,tmp,true,false,T(-1.0),T(0.0)); grad.resize(A.m(),A.n()); _X->mult(tmp,grad,true,false); }; virtual T fenchel(const Matrix<T>& input) const { return 0.5*input.normFsq()+_X->dot(input); } virtual void var_fenchel(const Matrix<T>& A, Matrix<T>& grad1, Matrix<T>& grad2, const bool intercept) const { Matrix<T> tmp(_X->m(),A.n()); _X->mult(A,tmp); //grad1.copy(*_X); _X->copyTo(grad1); //tmp.mult(*_X,grad1,false,false,T(1.0),T(-1.0)); _X->multSwitch(tmp,grad1,false,false,T(1.0),T(-1.0)); //grad1.mult(*_X,tmp,false,true,T(1.0),T(0.0)); _X->multSwitch(grad1,tmp,true,false,T(1.0),T(0.0)); grad2.resize(A.m(),A.n()); _X->mult(tmp,grad2,true,false); }; private: explicit LossCur<T>(const LossCur<T>& dict); LossCur<T>& operator=(const LossCur<T>& dict); const AbstractMatrixB<T>* _X; }; template <typename T> class SqLossMat : public Loss<T, Matrix<T> , Matrix<T> > { public: SqLossMat(const AbstractMatrixB<T>& D) : _D(&D) { _compute_gram = false; }; SqLossMat(const AbstractMatrixB<T>& D, const Matrix<T>& G) : _D(&D), _G(&G) { _compute_gram = true; }; virtual ~SqLossMat() { }; virtual inline void init(const Matrix<T>& x) { _x.copy(x); if (_compute_gram) { _D->mult(x,_DtX,true,false); } }; inline T eval(const Matrix<T>& alpha) const { Matrix<T> residual; residual.copy(_x); SpMatrix<T> spalpha; alpha.toSparse(spalpha); _D->mult(spalpha,residual,false,false,T(-1.0),T(1.0)); return 0.5*residual.normFsq(); } inline void grad(const Matrix<T>& alpha, Matrix<T>& grad) const { SpMatrix<T> spalpha; alpha.toSparse(spalpha); if (_compute_gram) { grad.copy(_DtX); _G->mult(spalpha,grad,false,false,T(1.0),-T(1.0)); } else { Matrix<T> residual; residual.copy(_x); _D->mult(spalpha,residual,false,false,T(-1.0),T(1.0)); _D->mult(residual,grad,true,false,T(-1.0),T(0.0)); } }; virtual inline bool test_backtracking(const Matrix<T>& y, const Matrix<T>& grad, const Matrix<T>& prox, const T L) const { Matrix<T> tmp; tmp.copy(y); tmp.sub(prox); SpMatrix<T> sptmp; tmp.toSparse(sptmp); if (_compute_gram) { SpVector<T> col; T sum=0; for (int i = 0; i<sptmp.n(); ++i) { sptmp.refCol(i,col); sum += _G->quad(col); } return (sum <= L*sptmp.normFsq()); } else { Matrix<T> tmp2; _D->mult(sptmp,tmp2); return (tmp2.normFsq() <= L*sptmp.normFsq()); } }; virtual T fenchel(const Matrix<T>& input) const { return 0.5*input.normFsq()+input.dot(_x); }; virtual void var_fenchel(const Matrix<T>& x, Matrix<T>& grad1, Matrix<T>& grad2, const bool intercept) const { grad1.copy(_x); SpMatrix<T> spalpha; x.toSparse(spalpha); _D->mult(spalpha,grad1,false,false,T(1.0),T(-1.0)); if (intercept) grad1.center(); _D->mult(grad1,grad2,true,false,T(1.0),T(0.0)); }; private: explicit SqLossMat<T>(const SqLossMat<T>& dict); SqLossMat<T>& operator=(const SqLossMat<T>& dict); const AbstractMatrixB<T>* _D; Matrix<T> _x; bool _compute_gram; const Matrix<T>* _G; Matrix<T> _DtX; }; template <typename T, typename L> class LossMatSup : public Loss<T,Matrix<T>, Matrix<T> > { public: LossMatSup() { }; virtual ~LossMatSup() { for (int i = 0; i<_N; ++i) { delete(_losses[i]); _losses[i]=NULL; } delete[](_losses); }; virtual void init(const Matrix<T>& input) { Vector<T> col; _m=input.m(); for (int i = 0; i<_N; ++i) { input.refCol(i,col); _losses[i]->init(col); } }; inline T eval(const Matrix<T>& w) const { Vector<T> col; T sum = 0; for (int i = 0; i<_N; ++i) { w.refCol(i,col); sum+=_losses[i]->eval(col); } return sum; } inline void grad(const Matrix<T>& w, Matrix<T>& grad) const { Vector<T> col, col2; grad.resize(w.m(),w.n()); for (int i = 0; i<_N; ++i) { w.refCol(i,col); grad.refCol(i,col2); _losses[i]->grad(col,col2); } }; virtual T fenchel(const Matrix<T>& input) const { Vector<T> col; T sum = 0; for (int i = 0; i<_N; ++i) { input.refCol(i,col); sum += _losses[i]->fenchel(col); } return sum; } virtual void var_fenchel(const Matrix<T>& x, Matrix<T>& grad1, Matrix<T>& grad2, const bool intercept) const { grad1.resize(_m,x.n()); grad2.resize(x.m(),x.n()); Vector<T> col, col2, col3; for (int i = 0; i<_N; ++i) { x.refCol(i,col); grad1.refCol(i,col2); grad2.refCol(i,col3); _losses[i]->var_fenchel(col,col2,col3,intercept); } }; virtual bool is_fenchel() const { bool ok=true; for (int i = 0; i<_N; ++i) ok = ok && _losses[i]->is_fenchel(); return ok; }; virtual void dummy() = 0; private: explicit LossMatSup<T,L>(const LossMatSup<T,L>& dict); LossMatSup<T,L>& operator=(const LossMatSup<T,L>& dict); int _m; protected: int _N; L** _losses; }; template <typename T, typename L> class LossMat : public LossMatSup<T,L> { }; template <typename T, bool weighted> class LossMat<T, LogLoss<T,weighted> > : public LossMatSup<T, LogLoss<T,weighted> > { public: LossMat(const int N, const AbstractMatrixB<T>& X) { this->_N=N; this->_losses=new LogLoss<T,weighted>*[this->_N]; Vector<T> col; for (int i = 0; i<this->_N; ++i) this->_losses[i]=new LogLoss<T,weighted>(X); } virtual void dummy() { }; virtual ~LossMat() { }; }; template <typename T> class LossMat<T, SqLossMissing<T> > : public LossMatSup<T, SqLossMissing<T> > { public: LossMat(const int N, const AbstractMatrixB<T>& X) { this->_N=N; this->_losses=new SqLossMissing<T>*[this->_N]; Vector<T> col; for (int i = 0; i<this->_N; ++i) this->_losses[i]=new SqLossMissing<T>(X); } virtual void dummy() { }; virtual ~LossMat() { }; }; template <typename T, typename D = Vector<T> > class Regularizer { public: Regularizer() { }; Regularizer(const ParamReg<T>& param) { _intercept=param.intercept; _pos=param.pos; } virtual ~Regularizer() { }; virtual void reset() { }; virtual void prox(const D& input, D& output, const T lambda) = 0; virtual T eval(const D& input) const = 0; /// returns phi^star( input ) and ouput=input if the fenchel is unconstrained /// returns 0 and scale input such that phi^star(output)=0 otherwise virtual void fenchel(const D& input, T& val, T& scal) const = 0; virtual bool is_fenchel() const { return !_pos; }; virtual bool is_intercept() const { return _intercept; }; virtual bool is_subgrad() const { return false; }; virtual void sub_grad(const D& input, D& output) const { }; virtual T eval_paths(const D& x, SpMatrix<T>& paths_mat) const { return this->eval(x); }; protected: bool _pos; bool _intercept; private: explicit Regularizer<T,D>(const Regularizer<T,D>& reg); Regularizer<T,D>& operator=(const Regularizer<T,D>& reg); }; template <typename T> class Lasso : public Regularizer<T> { public: Lasso(const ParamReg<T>& param) : Regularizer<T>(param) { }; virtual ~Lasso() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); y.softThrshold(lambda); if (this->_intercept) y[y.n()-1] = x[y.n()-1]; }; T inline eval(const Vector<T>& x) const { return (this->_intercept ? x.asum() - abs(x[x.n()-1]) : x.asum()); }; void inline fenchel(const Vector<T>& input, T& val, T& scal) const { Vector<T> output; output.copy(input); if (this->_intercept) output[output.n()-1]=0; T mm = output.fmaxval(); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; }; virtual bool is_subgrad() const { return true; }; virtual void sub_grad(const Vector<T>& input, Vector<T>& output) const { output.resize(input.n()); if (!this->_pos) { for (int i = 0; i<input.n(); ++i) { output[i] = input[i] > 0 ? T(1.0) : input[i] < 0 ? -T(1.0) : 0; } } else { for (int i = 0; i<input.n(); ++i) { output[i] = input[i] > 0 ? T(1.0) : 0; } } if (this->_intercept) output[output.n()-1]=0; } }; template <typename T> class Lzero : public Regularizer<T> { public: Lzero(const ParamReg<T>& param) : Regularizer<T>(param) { }; virtual ~Lzero() { }; virtual bool is_fenchel() const { return false; }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); y.hardThrshold(sqrt(2*lambda)); if (this->_intercept) y[y.n()-1] = x[y.n()-1]; }; T inline eval(const Vector<T>& x) const { return (this->_intercept ? x.lzero() - 1 : x.lzero()); }; void inline fenchel(const Vector<T>& input, T& val, T& scal) const { }; }; template <typename T> class None: public Regularizer<T>, public SplittingFunction<T, SpMatrix<T> > { public: None() { }; None(const ParamReg<T>& param) { }; virtual ~None() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); }; T inline eval(const Vector<T>& x) const { return 0; }; void inline fenchel(const Vector<T>& input, T& val, T& scal) const { }; virtual bool is_fenchel() const { return false; }; virtual bool is_subgrad() const { return true; }; virtual void sub_grad(const Vector<T>& input, Vector<T>& output) const { output.setZeros(); } virtual void reset() { }; virtual T eval_split(const SpMatrix<T>& input) const { return 0; }; virtual int num_components() const { return 0; }; virtual void prox_split(SpMatrix<T>& splitted_w, const T lambda) const { }; virtual void init_split_variables(SpMatrix<T>& splitted_w) const { }; virtual void init(const Vector<T>& y) { }; }; template <typename T> class Ridge: public Regularizer<T> { public: Ridge(const ParamReg<T>& param) : Regularizer<T>(param) { }; virtual ~Ridge() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); y.scal(T(1.0/(1.0+lambda))); if (this->_intercept) y[y.n()-1] = x[y.n()-1]; }; T inline eval(const Vector<T>& x) const { return (this->_intercept ? 0.5*x.nrm2sq() - 0.5*x[x.n()-1]*x[x.n()-1] : 0.5*x.nrm2sq()); }; void inline fenchel(const Vector<T>& input, T& val, T& scal) const { val=this->eval(input); scal=T(1.0); }; virtual bool is_subgrad() const { return true; }; virtual void sub_grad(const Vector<T>& input, Vector<T>& output) const { output.resize(input.n()); if (!this->_pos) { for (int i = 0; i<input.n(); ++i) { output[i] = input[i] > 0 ? 0.5*input[i] : 0; } } else { output.copy(input); output.scal(0.5); } if (this->_intercept) output[output.n()-1]=0; } }; template <typename T> class normL2: public Regularizer<T> { public: normL2(const ParamReg<T>& param) : Regularizer<T>(param) { }; virtual ~normL2() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); Vector<T> xref(x.rawX(),this->_intercept ? x.n()-1 : x.n()); const T nrm=xref.nrm2(); if (nrm < lambda) { y.setZeros(); } else { y.scal(T(1.0) - lambda/nrm); } if (this->_intercept) y[y.n()-1] = x[y.n()-1]; }; T inline eval(const Vector<T>& x) const { Vector<T> xref(x.rawX(),this->_intercept ? x.n()-1 : x.n()); return xref.nrm2(); }; /// TODO add subgradient void inline fenchel(const Vector<T>& input, T& val, T& scal) const { Vector<T> output; output.copy(input); if (this->_intercept) output[output.n()-1]=0; T mm = output.nrm2(); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; }; }; template <typename T> class normLINF: public Regularizer<T> { public: normLINF(const ParamReg<T>& param) : Regularizer<T>(param) { }; virtual ~normLINF() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); Vector<T> xref(y.rawX(),this->_intercept ? x.n()-1 : x.n()); Vector<T> row(xref.n()); xref.l1project(row,lambda); for (int j = 0; j<xref.n(); ++j) y[j]=y[j]-row[j]; if (this->_intercept) y[y.n()-1] = x[y.n()-1]; }; T inline eval(const Vector<T>& x) const { Vector<T> xref(x.rawX(),this->_intercept ? x.n()-1 : x.n()); return xref.fmaxval(); }; /// TODO add subgradient void inline fenchel(const Vector<T>& input, T& val, T& scal) const { Vector<T> output; output.copy(input); if (this->_intercept) output[output.n()-1]=0; T mm = output.asum(); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; }; }; template <typename T, typename D, typename RegA, typename RegB, bool order = true, bool scale_lambda = false> class ComposeProx: public Regularizer<T,D> { public: ComposeProx(const ParamReg<T>& param) : Regularizer<T,D>(param) { _lambda2d1=param.lambda2d1; _regA=new RegA(param); _regB=new RegB(param); } virtual ~ComposeProx() { delete(_regA); delete(_regB); }; void inline prox(const D& x, D& y, const T lambda) { D tmp; if (scale_lambda) { if (order) { _regA->prox(x,tmp,lambda); _regB->prox(tmp,y,lambda*_lambda2d1/(T(1.0)+lambda)); } else { _regB->prox(x,tmp,lambda*_lambda2d1); _regA->prox(tmp,y,lambda/(T(1.0)+lambda*_lambda2d1)); } } else { if (order) { _regA->prox(x,tmp,lambda); _regB->prox(tmp,y,lambda*_lambda2d1); } else { _regB->prox(x,tmp,lambda*_lambda2d1); _regA->prox(tmp,y,lambda); } } }; T inline eval(const D& x) const { return _regA->eval(x) + _lambda2d1*_regB->eval(x); }; virtual bool is_fenchel() const { return false; }; void inline fenchel(const D& input, T& val, T& scal) const { }; virtual bool is_subgrad() const { return _regA->is_subgrad() && _regB->is_subgrad(); }; virtual void sub_grad(const D& input, D& output) const { _regA->sub_grad(input,output); D tmp; _regB->sub_grad(input,tmp); output.add(tmp,_lambda2d1); }; private: RegA* _regA; RegB* _regB; T _lambda2d1; }; template <typename T> struct ElasticNet { typedef ComposeProx< T, Vector<T>, Lasso<T>, Ridge<T>, true > type; }; template <typename T> class FusedLasso: public Regularizer<T> { public: FusedLasso(const ParamReg<T>& param) : Regularizer<T>(param) { _lambda2d1=param.lambda2d1; _lambda3d1=param.lambda3d1; }; virtual ~FusedLasso() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.resize(x.n()); Vector<T> copyx; copyx.copy(x); copyx.fusedProjectHomotopy(y,_lambda2d1*lambda,lambda,_lambda3d1*lambda,true); }; T inline eval(const Vector<T>& x) const { T sum = T(); const int maxn = this->_intercept ? x.n()-1 : x.n(); for (int i = 0; i<maxn-1; ++i) sum += abs(x[i+1]-x[i]) + _lambda2d1*abs(x[i]) + 0.5*_lambda3d1*x[i]*x[i]; sum += _lambda2d1*abs(x[maxn-1])+0.5*_lambda3d1*x[maxn-1]*x[maxn-1]; return sum; }; virtual bool is_fenchel() const { return false; }; void inline fenchel(const Vector<T>& input, T& val, T& scal) const { }; private: T _lambda2d1; T _lambda3d1; }; template <typename T> class GraphLasso : public Regularizer<T>, public SplittingFunction<T, SpMatrix<T> > { public: GraphLasso(const ParamReg<T>& param) : Regularizer<T>(param) { const bool resetflow = param.resetflow; const bool linf = param.linf; const bool clever = param.clever; const GraphStruct<T>& graph_st=*(param.graph_st); _clever=clever; _resetflow=resetflow; _graph.create_graph(graph_st.Nv,graph_st.Ng,graph_st.weights, graph_st.gv_ir,graph_st.gv_jc,graph_st.gg_ir,graph_st.gg_jc); _graph.save_capacities(); _work.resize(graph_st.Nv+graph_st.Ng+2); _weights.resize(graph_st.Ng); for (int i = 0; i<graph_st.Ng; ++i) _weights[i] = graph_st.weights[i]; _old_lambda=-1.0; _linf=linf; }; virtual ~GraphLasso() { }; void inline reset() { _old_lambda = -1.0; }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { if (!_linf) { cerr << "Not implemented" << endl; exit(1); } y.copy(x); _graph.restore_capacities(); _graph.set_weights(_weights.rawX(),lambda); if (_old_lambda < 0 || _resetflow) { _graph.reset_flow(); } else { if (lambda != _old_lambda) _graph.scale_flow(lambda/_old_lambda); } if (this->_pos) { Vector<T> xc; xc.copy(x); xc.thrsPos(); _graph.proximal_operator(xc.rawX(),y.rawX(),_clever); } else { _graph.proximal_operator(x.rawX(),y.rawX(),_clever); } #ifdef VERB2 T duality_gap2 = y.nrm2sq()-y.dot(x)+lambda*this->eval(y); cerr << "duality_gap2 " << duality_gap2 << endl; #endif _old_lambda=lambda; }; T inline eval(const Vector<T>& x) const { Graph<T>* gr = const_cast<Graph<T>* >(&_graph); gr->restore_capacities(); return gr->norm(x.rawX(),_work.rawX(),_weights.rawX(),_linf); }; virtual bool is_fenchel() const { return _linf; }; void inline fenchel(const Vector<T>& input, T& val, T& scal) const { Graph<T>* gr = const_cast<Graph<T>* >(&_graph); if (!_resetflow) { gr->save_flow(); } gr->reset_flow(); gr->restore_capacities(); T mm = gr->dual_norm_inf(input,_weights); if (!_resetflow) gr->restore_flow(); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; }; virtual void init(const Vector<T>& y) { }; inline int num_components() const { return _weights.n(); }; inline void prox_split(SpMatrix<T>& splitted_w, const T lambda) const { Vector<T> tmp; SpVector<T> col; if (_linf) { for (int i = 0; i<splitted_w.n(); ++i) { splitted_w.refCol(i,col); tmp.setData(col.rawX(),col.nzmax()); Vector<T> res; res.copy(tmp); vAbs<T>(res.n(),res.rawX(),res.rawX()); T thrs=project_tree_l1(res.rawX(),res.n(),lambda); tmp.thrsabsmin(thrs); } } else { for (int i = 0; i<splitted_w.n(); ++i) { splitted_w.refCol(i,col); tmp.setData(col.rawX(),col.nzmax()); const T nrm = tmp.nrm2(); if (nrm > lambda*_weights[i]) { tmp.scal(T(1.0)-lambda*_weights[i]/nrm); } else { tmp.setZeros(); } } } }; inline void init_split_variables(SpMatrix<T>& splitted_w) const { Graph<T>* gr = const_cast<Graph<T>* >(&_graph); gr->init_split_variables(splitted_w); }; inline T eval_split(const SpMatrix<T>& input) const { SpVector<T> col; T sum = 0; for (int i = 0; i<input.n(); ++i) { input.refCol(i,col); sum += _linf ? _weights[i]*col.fmaxval() : _weights[i]*col.nrm2(); } return sum; } inline T eval_weighted(const Vector<T>& input, const SpMatrix<T>& input_struct, const T* inner_weight) const { SpVector<T> col; T sum = 0; Vector<T> tmp(input_struct.m()); for (int i = 0; i<input_struct.n(); ++i) { input_struct.refCol(i,col); tmp.setn(col.L()); for (int j = 0; j<col.L(); ++j) tmp[j]=inner_weight[j]*input[col.r(j)]; sum += _linf ? _weights[i]*tmp.fmaxval() : _weights[i]*tmp.nrm2(); } return sum; } private: bool _clever; Graph<T> _graph; bool _resetflow; Vector<T> _work; Vector<T> _weights; T _old_lambda; bool _linf; }; template <typename T> struct GraphLassoRidge { typedef ComposeProx<T, Vector<T>, GraphLasso<T>, Ridge<T>, true> type; }; template <typename T> class TreeLasso : public Regularizer<T> { public: TreeLasso(const ParamReg<T>& param) : Regularizer<T>(param) { const TreeStruct<T>& tree_st=*(param.tree_st); const bool linf = param.linf; _tree.create_tree(tree_st.Nv,tree_st.own_variables, tree_st.N_own_variables,tree_st.weights, tree_st.groups_ir,tree_st.groups_jc, tree_st.Ng,0); _linf=linf; }; virtual ~TreeLasso() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); Vector<T> yp; if (this->_intercept) { yp.setData(y.rawX(),y.n()-1); } else { yp.setData(y.rawX(),y.n()); } _tree.proj(yp,_linf,lambda); }; T inline eval(const Vector<T>& x) const { return const_cast<Tree_Seq<T>* >(&_tree)->val_norm(x.rawX(),0,_linf); }; void inline fenchel(const Vector<T>& y, T& val, T& scal) const { if (_linf) { Vector<T> yp; if (this->_intercept) { yp.setData(y.rawX(),y.n()-1); } else { yp.setData(y.rawX(),y.n()); } T mm = const_cast<Tree_Seq<T>* >(&_tree)->dual_norm_inf(yp); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; } }; virtual bool is_fenchel() const { return _linf; }; virtual bool is_subgrad() const { return true; }; virtual void sub_grad(const Vector<T>& input, Vector<T>& output) const { output.resize(input.n()); const_cast<Tree_Seq<T>*>(&_tree)->sub_grad(input,output,_linf); if (this->_intercept) output[output.n()-1]=0; } private: Tree_Seq<T> _tree; bool _linf; }; template <typename T> class TreeLzero : public Regularizer<T> { public: TreeLzero(const ParamReg<T>& param) : Regularizer<T>(param) { const TreeStruct<T>& tree_st=*(param.tree_st); _tree.create_tree(tree_st.Nv,tree_st.own_variables, tree_st.N_own_variables,tree_st.weights, tree_st.groups_ir,tree_st.groups_jc, tree_st.Ng,0); }; virtual ~TreeLzero() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); Vector<T> yp; if (this->_intercept) { yp.setData(y.rawX(),y.n()-1); } else { yp.setData(y.rawX(),y.n()); } _tree.proj_zero(yp,lambda); }; T inline eval(const Vector<T>& x) const { return const_cast<Tree_Seq<T>* >(&_tree)->val_zero(x.rawX(),0); }; virtual bool is_fenchel() const { return false; }; void inline fenchel(const Vector<T>& y, T& val, T& scal) const { }; private: Tree_Seq<T> _tree; }; template <typename T, typename ProxMat> class ProxMatToVec : public Regularizer<T> { public: ProxMatToVec(const ParamReg<T>& param) : Regularizer<T>(param) { _size_group=param.size_group; ParamReg<T> param2=param; param2.intercept=false; _proxy = new ProxMat(param2); }; virtual ~ProxMatToVec() { delete(_proxy); }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.resize(x.n()); int size_vec=this->_intercept ? x.n()-1 : x.n(); Matrix<T> mX(x.rawX(),_size_group,size_vec/_size_group); Matrix<T> mY(y.rawX(),_size_group,size_vec/_size_group); _proxy->prox(mX,mY,lambda); if (this->_intercept) y[y.n()-1]=x[x.n()-1]; } T inline eval(const Vector<T>& x) const { int size_vec=this->_intercept ? x.n()-1 : x.n(); Matrix<T> mX(x.rawX(),_size_group,size_vec/_size_group); return _proxy->eval(mX); } virtual bool is_fenchel() const { return (_proxy->is_fenchel()); }; void inline fenchel(const Vector<T>& x, T& val, T& scal) const { int size_vec=this->_intercept ? x.n()-1 : x.n(); Matrix<T> mX(x.rawX(),_size_group,size_vec/_size_group); _proxy->fenchel(mX,val,scal); }; private: int _size_group; ProxMat* _proxy; }; template <typename T, typename Reg> class GroupProx : public Regularizer<T> { public: GroupProx(const ParamReg<T> & param) : Regularizer<T>(param) { ParamReg<T> param2=param; param2.intercept=false; _size_group=param.size_group; if (param.groups) { int num_groups=0; for (int i = 0; i<param.ngroups; ++i) num_groups=MAX(num_groups,param.groups[i]); _groups.resize(num_groups); for (int i = 0; i<num_groups; ++i) _groups[i]=new list_int(); for (int i = 0; i<param.ngroups; ++i) _groups[param.groups[i]-1]->push_back(i); } _prox = new Reg(param2); } virtual ~GroupProx() { delete(_prox); for (int i = 0; i<_groups.size(); ++i) delete(_groups[i]); }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); const int maxn= this->_intercept ? x.n()-1 : x.n(); if (!_groups.empty()) { for (int i = 0; i<_groups.size(); ++i) { list_int* group=_groups[i]; Vector<T> tmp(group->size()); Vector<T> tmp2(group->size()); int count=0; for (const_iterator_int it = group->begin(); it != group->end(); ++it) { tmp[count++]=x[*it]; } _prox->prox(tmp,tmp2,lambda); count=0; for (const_iterator_int it = group->begin(); it != group->end(); ++it) { y[*it]=tmp2[count++]; } } } else { Vector<T> tmp; Vector<T> tmp2; const int p = _size_group; for (int i = 0; i+p-1<maxn; i+=p) { tmp.setPointer(x.rawX()+i,p); tmp2.setPointer(y.rawX()+i,p); _prox->prox(tmp,tmp2,lambda); } } } T inline eval(const Vector<T>& x) const { const int maxn= this->_intercept ? x.n()-1 : x.n(); T sum=0; if (!_groups.empty()) { for (int i = 0; i<_groups.size(); ++i) { list_int* group=_groups[i]; Vector<T> tmp(group->size()); int count=0; for (const_iterator_int it = group->begin(); it != group->end(); ++it) { tmp[count++]=x[*it]; } sum+=_prox->eval(tmp); } } else { Vector<T> tmp; const int p = _size_group; for (int i = 0; i+p-1<maxn; i+=p) { tmp.setPointer(x.rawX()+i,p); sum+=_prox->eval(tmp); } } return sum; } virtual bool is_fenchel() const { return _prox->is_fenchel(); }; void inline fenchel(const Vector<T>& x, T& val, T& scal) const { const int maxn= this->_intercept ? x.n()-1 : x.n(); T val2; T scal2; scal=T(1.0); val=0; if (!_groups.empty()) { for (int i = 0; i<_groups.size(); ++i) { list_int* group=_groups[i]; Vector<T> tmp(group->size()); int count=0; for (const_iterator_int it = group->begin(); it != group->end(); ++it) { tmp[count++]=x[*it]; } _prox->fenchel(tmp,val2,scal2); val+=val2; scal=MIN(scal,scal2); } } else { const int p = _size_group; Vector<T> tmp; for (int i = 0; i+p-1<maxn; i+=p) { tmp.setPointer(x.rawX()+i,p); _prox->fenchel(tmp,val2,scal2); val+=val2; scal=MIN(scal,scal2); } } }; protected: int _size_group; std::vector<list_int*> _groups; Reg* _prox; }; template <typename T> struct GroupLassoL2 { typedef GroupProx<T, normL2<T> > type; }; template <typename T> struct GroupLassoLINF { typedef GroupProx<T, normLINF<T> > type; }; template <typename T> struct GroupLassoL2_L1 { typedef ComposeProx<T, Vector<T>, typename GroupLassoL2<T>::type, Lasso<T>, false> type; }; template <typename T> struct GroupLassoLINF_L1 { typedef ComposeProx<T, Vector<T>, typename GroupLassoLINF<T>::type, Lasso<T>, false> type; }; template <typename T> class MixedL1L2 : public Regularizer<T,Matrix<T> > { public: MixedL1L2(const ParamReg<T>& param) : Regularizer<T,Matrix<T> >(param) { }; virtual ~MixedL1L2() { }; void inline prox(const Matrix<T>& x, Matrix<T>& y, const T lambda) { Vector<T> norm; y.copy(x); if (this->_pos) y.thrsPos(); y.norm_2_rows(norm); y.setZeros(); const int m = x.m(); const int n = x.n(); for (int i = 0; i<m; ++i) { if (norm[i] > lambda) { T scal = (norm[i]-lambda)/norm[i]; for (int j = 0; j<n; ++j) y[j*m+i] = x[j*m+i]*scal; } } if (this->_pos) y.thrsPos(); if (this->_intercept) for (int j = 0; j<n; ++j) y[j*m+m-1]=x[j*m+m-1]; } T inline eval(const Matrix<T>& x) const { Vector<T> norm; x.norm_2_rows(norm); return this->_intercept ? norm.asum() - norm[norm.n() -1] : norm.asum(); } virtual bool is_subgrad() const { return true; }; virtual void sub_grad(const Matrix<T>& input, Matrix<T>& output) const { Vector<T> norm; input.norm_2_rows(norm); for (int i = 0; i<norm.n(); ++i) { if (norm[i] < 1e-20) norm[i]=T(1.0); } norm.inv(); if (this->_intercept) norm[norm.n()-1]=0; output.copy(input); output.multDiagLeft(norm); }; void inline fenchel(const Matrix<T>& input, T& val, T& scal) const { Vector<T> norm; input.norm_2_rows(norm); if (this->_intercept) norm[norm.n()-1]=0; T mm = norm.fmaxval(); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; }; }; template <typename T> class MixedL1LINF : public Regularizer<T,Matrix<T> > { public: MixedL1LINF(const ParamReg<T>& param) : Regularizer<T,Matrix<T> >(param) { }; virtual ~MixedL1LINF() { }; void inline prox(const Matrix<T>& x, Matrix<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); Vector<T> row(x.n()); Vector<T> row2(x.n()); const int maxn= this->_intercept ? x.m()-1 : x.m(); for (int i = 0; i< maxn; ++i) { for (int j = 0; j<x.n(); ++j) row[j]=y(i,j); row.l1project(row2,lambda); for (int j = 0; j<x.n(); ++j) y(i,j) = row[j]-row2[j]; } } T inline eval(const Matrix<T>& x) const { Vector<T> norm; x.norm_inf_rows(norm); return this->_intercept ? norm.asum() - norm[norm.n() -1] : norm.asum(); } void inline fenchel(const Matrix<T>& input, T& val, T& scal) const { Vector<T> norm; input.norm_l1_rows(norm); if (this->_intercept) norm[norm.n()-1]=0; T mm = norm.fmaxval(); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; }; virtual bool is_subgrad() const { return true; }; virtual void sub_grad(const Matrix<T>& input, Matrix<T>& output) const { output.resize(input.m(),input.n()); output.setZeros(); const T maxm= this->_intercept ? input.m()-1 : input.m(); Vector<T> row(input.n()); for (int i = 0; i<maxm; ++i) { input.copyRow(i,row); T max=row.fmaxval(); if (max > 1e-15) { int num_max=0; for (int j = 0; j<row.n(); ++j) { if (abs<T>(max-abs<T>(row[j])) < 1e-15) num_max++; } T add = T(1.0)/num_max; for (int j = 0; j<row.n(); ++j) { if (abs<T>(max-abs<T>(row[j])) < 1e-15) row[j] = row[j] > 0 ? add : -add; } output.setRow(i,row); } } }; }; template <typename T> class TraceNorm : public Regularizer<T,Matrix<T> > { public: TraceNorm(const ParamReg<T>& param) : Regularizer<T,Matrix<T> >(param) { if (param.intercept) { cerr << "Trace norm implementation is not compatible with intercept, intercept deactivated" << endl; } if (param.pos) { cerr << "Trace norm implementation is not compatible with non-negativity constraints" << endl; } }; virtual ~TraceNorm() { }; void inline prox(const Matrix<T>& x, Matrix<T>& y, const T lambda) { //Matrix<T> tmp; //tmp.copy(x); Matrix<T> U; Matrix<T> V; Vector<T> S; x.svd(U,S,V); S.softThrshold(lambda); U.multDiagRight(S); U.mult(V,y); /* Vector<T> u0(x.m()); u0.setZeros(); Vector<T> u, v; for (int i = 0; i<MIN(x.m(),x.n()); ++i) { tmp.svdRankOne(u0,u,v); T val=v.nrm2(); if (val < lambda) break; y.rank1Update(u,v,(val-lambda)/val); tmp.rank1Update(u,v,-T(1.0)); }*/ } T inline eval(const Matrix<T>& x) const { Vector<T> tmp; x.singularValues(tmp); return tmp.sum(); /* Matrix<T> XtX; if (x.m() > x.n()) { x.XtX(XtX); } else { x.XXt(XtX); } T sum=0; Vector<T> u0(XtX.m()); u0.setAleat(); for (int i = 0; i<XtX.m(); ++i) { T val=XtX.eigLargestMagnSym(u0,u0); // uses power method XtX.rank1Update(u0,u0,-val); sum+=sqrt(val); if (val <= 1e-10) break; } return sum; */ } void inline fenchel(const Matrix<T>& input, T& val, T& scal) const { //Vector<T> u0(input.m()); //u0.setZeros(); //Vector<T> u, v; //input.svdRankOne(u0,u,v); //T mm = v.nrm2(); Vector<T> tmp; input.singularValues(tmp); T mm = tmp.fmaxval(); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; }; }; template <typename T> class Rank : public Regularizer<T,Matrix<T> > { public: Rank(const ParamReg<T>& param) : Regularizer<T,Matrix<T> >(param) { if (param.intercept) { cerr << "Rank implementation is not compatible with intercept, intercept deactivated" << endl; } if (param.pos) { cerr << "Rank implementation is not compatible with non-negativity constraints" << endl; } }; virtual ~Rank() { }; void inline prox(const Matrix<T>& x, Matrix<T>& y, const T lambda) { Matrix<T> tmp; tmp.copy(x); y.resize(x.m(),x.n()); y.setZeros(); Vector<T> u0(x.m()); u0.setZeros(); Vector<T> u, v; for (int i = 0; i<MIN(x.m(),x.n()); ++i) { tmp.svdRankOne(u0,u,v); T val=v.nrm2(); if (val*val < lambda) break; y.rank1Update(u,v); tmp.rank1Update(u,v,-T(1.0)); } } T inline eval(const Matrix<T>& x) const { Matrix<T> XtX; if (x.m() > x.n()) { x.XtX(XtX); } else { x.XXt(XtX); } T sum=0; Vector<T> u0(XtX.m()); u0.setAleat(); for (int i = 0; i<XtX.m(); ++i) { T val=XtX.eigLargestMagnSym(u0,u0); // uses power method XtX.rank1Update(u0,u0,-val); sum++; if (val <= 1e-10) break; } return sum; } virtual bool is_fenchel() const { return false; }; void inline fenchel(const Matrix<T>& input, T& val, T& scal) const { }; }; template <typename T> inline void convert_paths_to_mat(const List<Path<long long>*>& paths,SpMatrix<T>& paths_mat, const int n) { int nzmax=0; for (ListIterator<Path<long long>*> it=paths.begin(); it != paths.end(); ++it) nzmax+=it->nodes.size(); paths_mat.resize(n,paths.size(),nzmax); int* pB =paths_mat.pB(); int* pE =paths_mat.pE(); int* r =paths_mat.r(); T* v =paths_mat.v(); int count_col=0; int count=0; pB[0]=0; for (ListIterator<Path<long long>*> it_path=paths.begin(); it_path != paths.end(); ++it_path) { for (const_iterator_int it = it_path->nodes.begin(); it != it_path->nodes.end(); ++it) { r[count]= *it; v[count++]= it_path->flow; } pB[++count_col]=count; } for (int i = 0; i<paths_mat.n(); ++i) sort(r,v,pB[i],pE[i]-1); }; template <typename T> class GraphPathL0 : public Regularizer<T> { public: GraphPathL0(const ParamReg<T>& param) : Regularizer<T>(param) { const GraphPathStruct<T>& graph=*(param.graph_path_st); _graph.init_graph(graph); } virtual ~GraphPathL0() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { // DEBUG y.copy(x); if (this->_pos) y.thrsPos(); _graph.proximal_l0(y.rawX(),lambda); }; T inline eval(const Vector<T>& x) const { return const_cast<GraphPath<T>* >(&_graph)->eval_l0(x.rawX()); }; T inline eval_paths(const Vector<T>& x, SpMatrix<T>& paths_mat) const { List<Path<long long>*> paths; T val=const_cast<GraphPath<T>* >(&_graph)->eval_l0(x.rawX(),&paths); convert_paths_to_mat<T>(paths,paths_mat,_graph.n()); for (ListIterator<Path<>*> it_path=paths.begin(); it_path != paths.end(); ++it_path) delete(*it_path); return val; }; virtual bool is_fenchel() const { return false; }; void inline fenchel(const Vector<T>& input, T& val, T& scal) const { }; private: GraphPath<T> _graph; }; template <typename T> class GraphPathConv : public Regularizer<T> { public: GraphPathConv(const ParamReg<T>& param) : Regularizer<T>(param) { const GraphPathStruct<T>& graph=*(param.graph_path_st); _graph.init_graph(graph); } virtual ~GraphPathConv() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); _graph.proximal_conv(y.rawX(),lambda); }; T inline eval(const Vector<T>& x) const { return const_cast<GraphPath<T>* >(&_graph)->eval_conv(x.rawX()); }; T inline eval_paths(const Vector<T>& x, SpMatrix<T>& paths_mat) const { List<Path<long long>*> paths; T val=const_cast<GraphPath<T>* >(&_graph)->eval_conv(x.rawX(),&paths); convert_paths_to_mat<T>(paths,paths_mat,_graph.n()); for (ListIterator<Path<long long>*> it_path=paths.begin(); it_path != paths.end(); ++it_path) delete(*it_path); return val; }; void inline fenchel(const Vector<T>& input, T& val, T& scal) const { T mm = const_cast<GraphPath<T>* >(&_graph)->eval_dual_norm(input.rawX()); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; }; private: GraphPath<T> _graph; }; template <typename T,typename Reg> class RegMat : public Regularizer<T,Matrix<T> > { public: RegMat(const ParamReg<T>& param) : Regularizer<T,Matrix<T> >(param) { _transpose=param.transpose; const int N = param.num_cols; _regs=new Reg*[N]; _N=N; for (int i = 0; i<N; ++i) _regs[i]=new Reg(param); }; virtual ~RegMat() { for (int i = 0; i<_N; ++i) { delete(_regs[i]); _regs[i]=NULL; } delete[](_regs); }; void inline reset() { for (int i = 0; i<_N; ++i) _regs[i]->reset(); }; void inline prox(const Matrix<T>& x, Matrix<T>& y, const T lambda) { y.copy(x); int i; if (_transpose) { #pragma omp parallel for private(i) for (i = 0; i<_N; ++i) { Vector<T> colx, coly; x.copyRow(i,colx); _regs[i]->prox(colx,coly,lambda); y.setRow(i,coly); } } else { #pragma omp parallel for private(i) for (i = 0; i<_N; ++i) { Vector<T> colx, coly; x.refCol(i,colx); y.refCol(i,coly); _regs[i]->prox(colx,coly,lambda); } } }; virtual bool is_subgrad() const { bool ok=true; for (int i = 0; i<_N; ++i) ok=ok && _regs[i]->is_subgrad(); return ok; }; void inline sub_grad(const Matrix<T>& x, Matrix<T>& y) const { y.resize(x.m(),x.n()); Vector<T> colx, coly, cold; if (_transpose) { for (int i = 0; i<_N; ++i) { x.copyRow(i,colx); _regs[i]->sub_grad(colx,coly); y.setRow(i,coly); } } else { for (int i = 0; i<_N; ++i) { x.refCol(i,colx); y.refCol(i,coly); _regs[i]->sub_grad(colx,coly); } } }; T inline eval(const Matrix<T>& x) const { T sum = 0; int i; #pragma omp parallel for private(i) for (i = 0; i<_N; ++i) { Vector<T> col; if (_transpose) { x.copyRow(i,col); } else { x.refCol(i,col); } #pragma omp critical sum += _regs[i]->eval(col); } return sum; }; void inline fenchel(const Matrix<T>& input, T& val, T& scal) const { Vector<T> col; val = 0; scal = 1.0; for (int i = 0; i<_N; ++i) { if (_transpose) { input.copyRow(i,col); } else { input.refCol(i,col); } T val2 = 0; T scal2 = 1.0; _regs[i]->fenchel(col,val2,scal2); scal=MIN(scal,scal2); val += val2; } }; virtual bool is_fenchel() const { bool ok=true; for (int i = 0; i<_N; ++i) ok = ok && _regs[i]->is_fenchel(); return ok; }; protected: int _N; Reg** _regs; bool _transpose; }; template <typename T> struct MixedL1L2_L1 { typedef ComposeProx<T, Matrix<T>, MixedL1L2<T>, RegMat<T, Lasso<T> >, false> type; }; template <typename T> struct MixedL1LINF_L1 { typedef ComposeProx<T, Matrix<T>, MixedL1LINF<T>, RegMat<T, Lasso<T> >, false> type; }; template <typename T> class SpecGraphMat : public Regularizer<T,Matrix<T> > { public: SpecGraphMat(const ParamReg<T>& param) : Regularizer<T,Matrix<T> >(param) { }; virtual ~SpecGraphMat() { delete(_graphlasso); }; virtual void dummy() = 0; void inline reset() { _graphlasso->reset(); }; void inline prox(const Matrix<T>& x, Matrix<T>& y, const T lambda) { Vector<T> xv, yv; x.toVect(xv); y.resize(x.m(),x.n()); y.toVect(yv); _graphlasso->prox(xv,yv,lambda); } T inline eval(const Matrix<T>& X) const { Vector<T> xv; X.toVect(xv); return _graphlasso->eval(xv); } void inline fenchel(const Matrix<T>& input, T& val, T& scal) const { Vector<T> inv; input.toVect(inv); _graphlasso->fenchel(inv,val,scal); }; virtual bool is_fenchel() const { return _graphlasso->is_fenchel(); }; protected: GraphLasso<T>* _graphlasso; }; template <typename T> class MixedL1LINFCR : public SpecGraphMat<T> { public: MixedL1LINFCR(const int m, const ParamReg<T>& param) : SpecGraphMat<T>(param) { const int n = param.num_cols; const T l2dl1 = param.lambda2d1; GraphStruct<T> graph_st; graph_st.Nv=m*n; graph_st.Ng=m+n; T* weights = new T[graph_st.Ng]; for (int i = 0; i<n; ++i) weights[i]=T(1.0); for (int i = 0; i<m; ++i) weights[i+n]=l2dl1; graph_st.weights=weights; mwSize* gv_jc = new mwSize[graph_st.Ng+1]; mwSize* gv_ir = new mwSize[m*n*2]; for (int i = 0; i<n; ++i) { gv_jc[i]=i*m; for (int j = 0; j<m; ++j) gv_ir[i*m+j]=i*m+j; } for (int i = 0; i<m; ++i) { gv_jc[i+n]=i*n+n*m; for (int j = 0; j<n; ++j) gv_ir[i*n+n*m+j]=j*m+i; } gv_jc[m+n]=2*m*n; graph_st.gv_jc=gv_jc; graph_st.gv_ir=gv_ir; mwSize* gg_jc = new mwSize[graph_st.Ng+1]; mwSize* gg_ir = new mwSize[1]; for (int i = 0; i< graph_st.Ng+1; ++i) gg_jc[i]=0; graph_st.gg_jc=gg_jc; graph_st.gg_ir=gg_ir; ParamReg<T> param_lasso = param; param_lasso.graph_st = &graph_st; this->_graphlasso = new GraphLasso<T>(param_lasso); delete[](weights); delete[](gv_jc); delete[](gv_ir); delete[](gg_jc); delete[](gg_ir); }; virtual ~MixedL1LINFCR() { }; virtual void dummy() { }; }; template <typename T> class TreeMult : public SpecGraphMat<T> { public: TreeMult(const ParamReg<T>& param) : SpecGraphMat<T>(param) { const TreeStruct<T>& tree_st=*(param.tree_st); const int N = param.num_cols; const T l1dl2 = param.lambda2d1; GraphStruct<T> graph_st; int Nv=tree_st.Nv; if (param.intercept) ++Nv; int Ng=tree_st.Ng; graph_st.Nv=Nv*N; graph_st.Ng=Ng*(N+1); T* weights=new T[graph_st.Ng]; for (int i = 0; i<N+1; ++i) for (int j = 0; j<Ng; ++j) weights[i*Ng+j]=tree_st.weights[j]; for (int j = 0; j<Ng; ++j) weights[N*Ng+j]*=l1dl2; graph_st.weights=weights; int nzmax_tree=0; for (int i = 0; i<Ng; ++i) nzmax_tree += tree_st.N_own_variables[i]; int nzmax_v=nzmax_tree*N; mwSize* gv_jc = new mwSize[graph_st.Ng+1]; mwSize* gv_ir = new mwSize[nzmax_v]; int count=0; for (int i = 0; i<N; ++i) { for (int j = 0; j<Ng; ++j) { gv_jc[i*Ng+j]=count; for (int k = 0; k<tree_st.N_own_variables[j]; ++k) { gv_ir[gv_jc[i*Ng+j] + k] =Nv*i+tree_st.own_variables[j]+k; ++count; } } } for (int i = 0; i<Ng+1; ++i) { gv_jc[N*Ng+i]=count; } graph_st.gv_jc=gv_jc; graph_st.gv_ir=gv_ir; mwSize* gg_jc = new mwSize[graph_st.Ng+1]; int nzmax_tree2=tree_st.groups_jc[Ng]; int nzmax2=nzmax_tree2*(N+1)+Ng*N; mwSize* gg_ir = new mwSize[nzmax2]; count=0; for (int i = 0; i<N; ++i) { for (int j = 0; j<Ng; ++j) { gg_jc[i*Ng+j] = count; for (int k = tree_st.groups_jc[j]; k<static_cast<int>(tree_st.groups_jc[j+1]); ++k) { gg_ir[count++] = i*Ng+tree_st.groups_ir[k]; } } } for (int i = 0; i<Ng; ++i) { gg_jc[N*Ng+i] = count; for (int j = tree_st.groups_jc[i]; j<static_cast<int>(tree_st.groups_jc[i+1]); ++j) { gg_ir[count++] = N*Ng+tree_st.groups_ir[j]; } for (int j = 0; j<N; ++j) { gg_ir[count++] = j*Ng+i; } } gg_jc[(N+1)*Ng]=nzmax2; graph_st.gg_jc=gg_jc; graph_st.gg_ir=gg_ir; // param.graph_st=&graph_st; ParamReg<T> param_lasso = param; param_lasso.graph_st=&graph_st; this->_graphlasso = new GraphLasso<T>(param_lasso); delete[](weights); delete[](gv_ir); delete[](gv_jc); delete[](gg_ir); delete[](gg_jc); }; virtual void dummy() { }; virtual ~TreeMult() { }; }; template <typename T> class GraphMult : public SpecGraphMat<T> { public: GraphMult(const ParamReg<T>& param) : SpecGraphMat<T>(param) { const GraphStruct<T>& graph_st=*(param.graph_st); const int N = param.num_cols; const T l1dl2 = param.lambda2d1; GraphStruct<T> g_st; int Nv=graph_st.Nv; int Ng=graph_st.Ng; g_st.Nv=Nv*N; g_st.Ng=Ng*(N+1); T* weights=new T[g_st.Ng]; for (int i = 0; i<N+1; ++i) for (int j = 0; j<Ng; ++j) weights[i*Ng+j]=graph_st.weights[j]; for (int j = 0; j<Ng; ++j) weights[N*Ng+j]*=l1dl2; g_st.weights=weights; int nzmax_graph=graph_st.gv_jc[Ng]; //just corrected to gv int nzmax_v=nzmax_graph*N; mwSize* gv_jc = new mwSize[g_st.Ng+1]; mwSize* gv_ir = new mwSize[nzmax_v]; int count=0; for (int i = 0; i<N; ++i) { for (int j = 0; j<Ng; ++j) { gv_jc[i*Ng+j]=count; for (int k = graph_st.gv_jc[j]; k<graph_st.gv_jc[j+1]; ++k) { gv_ir[count++] =Nv*i+graph_st.gv_ir[k]; } } } for (int i = 0; i<Ng+1; ++i) { gv_jc[N*Ng+i]=count; } g_st.gv_jc=gv_jc; g_st.gv_ir=gv_ir; mwSize* gg_jc = new mwSize[g_st.Ng+1]; int nzmax_tree2=graph_st.gg_jc[Ng]; int nzmax2=nzmax_tree2*(N+1)+Ng*N; mwSize* gg_ir = new mwSize[nzmax2]; count=0; for (int i = 0; i<N; ++i) { for (int j = 0; j<Ng; ++j) { gg_jc[i*Ng+j] = count; for (int k = graph_st.gg_jc[j]; k<graph_st.gg_jc[j+1]; ++k) { gg_ir[count++] = i*Ng+graph_st.gg_ir[k]; } } } for (int i = 0; i<Ng; ++i) { gg_jc[N*Ng+i] = count; for (int j = graph_st.gg_jc[i]; j<static_cast<int>(graph_st.gg_jc[i+1]); ++j) { gg_ir[count++] = N*Ng+graph_st.gg_ir[j]; } for (int j = 0; j<N; ++j) { gg_ir[count++] = j*Ng+i; } } gg_jc[(N+1)*Ng]=nzmax2; g_st.gg_jc=gg_jc; g_st.gg_ir=gg_ir; ParamReg<T> param_lasso = param; param_lasso.graph_st = &g_st; this->_graphlasso = new GraphLasso<T>(param_lasso); delete[](weights); delete[](gv_ir); delete[](gv_jc); delete[](gg_ir); delete[](gg_jc); }; virtual void dummy() { }; virtual ~GraphMult() { }; }; template <typename T, typename D, typename E> T duality_gap(Loss<T,D,E>& loss, Regularizer<T,D>& regularizer, const D& x, const T lambda, T& best_dual, const bool verbose = false) { if (!regularizer.is_fenchel() || !loss.is_fenchel()) { cerr << "Error: no duality gap available" << endl; exit(1); } T primal= loss.eval(x)+lambda*regularizer.eval(x); bool intercept=regularizer.is_intercept(); D grad1, grad2; loss.var_fenchel(x,grad1,grad2,intercept); grad2.scal(-T(1.0)/lambda); T val=0; T scal=1.0; regularizer.fenchel(grad2,val,scal); T dual = -lambda*val; grad1.scal(scal); dual -= loss.fenchel(grad1); dual = MAX(dual,best_dual); T delta= primal == 0 ? 0 : (primal-dual)/primal; if (verbose) { cout << "Relative duality gap: " << delta << endl; flush(cout); } best_dual=dual; return delta; } template <typename T, typename D, typename E> T duality_gap(Loss<T,D,E>& loss, Regularizer<T,D>& regularizer, const D& x, const T lambda, const bool verbose = false) { T best_dual=-INFINITY; return duality_gap(loss,regularizer,x,lambda,best_dual,verbose); } template <typename T> void dualityGraph(const Matrix<T>& X, const Matrix<T>& D, const Matrix<T>& alpha0, Vector<T>& res, const ParamFISTA<T>& param, const GraphStruct<T>* graph_st) { Regularizer<T>* regularizer=new GraphLasso<T>(*graph_st, param.intercept,param.resetflow,param.pos,param.clever); Loss<T>* loss; switch (param.loss) { case SQUARE: loss=new SqLoss<T>(D); break; case LOG: loss = new LogLoss<T>(D); break; case LOGWEIGHT: loss = new LogLoss<T,true>(D); break; default: cerr << "Not implemented"; exit(1); } Vector<T> Xi; X.refCol(0,Xi); loss->init(Xi); Vector<T> alpha0i; alpha0.refCol(0,alpha0i); regularizer->reset(); res[0]=loss->eval(alpha0i)+param.lambda*regularizer->eval(alpha0i); res[1]=duality_gap(*loss,*regularizer,alpha0i,param.lambda); delete(loss); delete(regularizer); } template <typename T> void writeLog(const int iter, const T time, const T primal, const T dual, char* name) { std::ofstream f; f.precision(12); f.flags(std::ios_base::scientific); f.open(name, ofstream::app); f << iter << " " << primal << " " << dual << " " << time << std::endl; f.close(); }; template <typename T, typename D, typename E> void subGradientDescent_Generic(Loss<T,D,E>& loss, Regularizer<T,D>& regularizer, const D& x0, D& x, Vector<T>& optim_info, const ParamFISTA<T>& param) { D grad; D sub_grad; const T lambda=param.lambda; const int it0 = MAX(1,param.it0); const bool duality = loss.is_fenchel() && regularizer.is_fenchel(); optim_info.set(-1); T best_dual=-INFINITY; T rel_duality_gap=-INFINITY; Timer time; time.start(); int it; for (it = 1; it<=param.max_it; ++it) { /// print loss if (param.verbose && ((it % it0) == 0)) { time.stop(); T los=loss.eval(x) + lambda*regularizer.eval(x); optim_info[0]=los; T sec=time.getElapsed(); cout << "Iter: " << it << ", loss: " << los << ", time: " << sec << " "; if (param.log) writeLog(it,sec,los,best_dual,param.logName); if (param.verbose) cout << endl; flush(cout); time.start(); } /// compute gradient loss.grad(x,grad); regularizer.sub_grad(x,sub_grad); T step = param.sqrt_step ? param.a/(param.b+sqrt(static_cast<T>(it))) : param.a/(param.b+(static_cast<T>(it))); x.add(grad,-step); x.add(sub_grad,-lambda*step); if (duality && ((it % it0) == 0)) { time.stop(); rel_duality_gap=duality_gap(loss,regularizer,x,lambda,best_dual,param.verbose); optim_info[1]=best_dual; optim_info[2]=rel_duality_gap; if (rel_duality_gap < param.tol) break; time.start(); } } if ((it % it0) != 0 || !param.verbose) { T los=loss.eval(x) + lambda*regularizer.eval(x); optim_info[0]=los; if (duality) { rel_duality_gap=duality_gap(loss,regularizer,x,lambda,best_dual,param.verbose); optim_info[1]=best_dual; optim_info[2]=rel_duality_gap; } } optim_info[3]=it; } template <typename T, typename D, typename E> void ISTA_Generic(Loss<T,D,E>& loss, Regularizer<T,D>& regularizer, const D& x0, D& x, Vector<T>& optim_info, const ParamFISTA<T>& param) { const int it0 = MAX(1,param.it0); const T lambda=param.lambda; T L=param.L0; T Lold=L; x.copy(x0); D grad, tmp, prox, old; const bool duality = loss.is_fenchel() && regularizer.is_fenchel(); optim_info.set(-1); Timer time; time.start(); T rel_duality_gap=-INFINITY; int it; T best_dual=-INFINITY; for (it = 1; it<=param.max_it; ++it) { /// print loss if (param.verbose && ((it % it0) == 0)) { time.stop(); T los=loss.eval(x) + lambda*regularizer.eval(x); optim_info[0]=los; T sec=time.getElapsed(); cout << "Iter: " << it << ", loss: " << los << ", time: " << sec << ", L: " << L; flush(cout); if (param.log) writeLog(it,sec,los,best_dual,param.logName); time.start(); } /// compute gradient loss.grad(x,grad); int iter=1; while (iter < param.max_iter_backtracking) { prox.copy(x); prox.add(grad,-T(1.0)/L); regularizer.prox(prox,tmp,lambda/L); Lold=L; if (loss.test_backtracking(x,grad,tmp,L)) { break; } L *= param.gamma; if (param.verbose && ((it % it0) == 0)) cout << " " << L; ++iter; } if (param.verbose && ((it % it0) == 0)) cout << endl; old.copy(x); x.copy(tmp); if (duality) { if ((it % it0) == 0) { time.stop(); rel_duality_gap=duality_gap(loss,regularizer,x,lambda,best_dual,param.verbose); optim_info[1]=best_dual; optim_info[2]=rel_duality_gap; if (rel_duality_gap < param.tol) break; time.start(); } } else { old.sub(x); if (sqrt(old.nrm2sq()/MAX(EPSILON,x.nrm2sq())) < param.tol) break; } } T los=loss.eval(x) + lambda*regularizer.eval(x); optim_info[0]=los; T sec=time.getElapsed(); if (param.verbose) { cout << "Iter: " << it << ", loss: " << los << ", time: " << sec << ", L: " << L << endl; flush(cout); } if (duality) { rel_duality_gap=duality_gap(loss,regularizer,x,lambda,best_dual,param.verbose); optim_info[1]=best_dual; optim_info[2]=rel_duality_gap; } optim_info[3]=it; } template <typename T, typename D, typename E> void FISTA_Generic(Loss<T,D,E>& loss, Regularizer<T,D>& regularizer, const D& x0, D& x, Vector<T>& optim_info, const ParamFISTA<T>& param) { const int it0 = MAX(1,param.it0); const T lambda=param.lambda; T L=param.L0; T t = 1.0; T Lold=L; T old_t; D y, grad, prox, tmp; y.copy(x0); x.copy(x0); const bool duality = loss.is_fenchel() && regularizer.is_fenchel(); T rel_duality_gap=-INFINITY; optim_info.set(-1); Timer time; time.start(); int it; T best_dual=-INFINITY; for (it = 1; it<=param.max_it; ++it) { /// print loss if (param.verbose && ((it % it0) == 0)) { time.stop(); T los=loss.eval(x) + lambda*regularizer.eval(x); optim_info[0]=los; T sec=time.getElapsed(); cout << "Iter: " << it << ", loss: " << los << ", time: " << sec << ", L: " << L; flush(cout); if (param.log) writeLog(it,sec,los,best_dual,param.logName); time.start(); } /// compute gradient loss.grad(y,grad); int iter=1; while (iter < param.max_iter_backtracking) { prox.copy(y); prox.add(grad,-T(1.0)/L); regularizer.prox(prox,tmp,lambda/L); Lold=L; if (param.fixed_step || loss.test_backtracking(y,grad,tmp,L)) break; L *= param.gamma; if (param.verbose && ((it % it0) == 0)) cout << " " << L; ++iter; } if (param.verbose && ((it % it0) == 0)) cout << endl; prox.copy(x); prox.sub(tmp); x.copy(tmp); old_t=t; t=(1.0+sqrt(1+4*t*t))/2; y.copy(x); y.add(prox,(1-old_t)/t); if (duality) { if ((it % it0) == 0) { time.stop(); rel_duality_gap=duality_gap(loss,regularizer,x,lambda,best_dual,param.verbose); optim_info[1]=best_dual; optim_info[2]=rel_duality_gap; if (rel_duality_gap < param.tol) break; time.start(); } } else { if (sqrt(prox.nrm2sq()/MAX(EPSILON,x.nrm2sq())) < param.tol) break; } } T los=loss.eval(x) + lambda*regularizer.eval(x); optim_info[0]=los; T sec=time.getElapsed(); if (param.verbose) { cout << "Iter: " << it << ", loss: " << los << ", time: " << sec << ", L: " << L << endl; flush(cout); } if (duality) { rel_duality_gap=duality_gap(loss,regularizer,x,lambda,best_dual,param.verbose); optim_info[1]=best_dual; optim_info[2]=rel_duality_gap; } optim_info[3]=it; }; template <typename T> T LagrangianADMM(const SplittingFunction<T, Matrix<T> >& loss, const SplittingFunction<T, SpMatrix<T> >& reg, const T lambda, const T gamma, const Vector<T>& w, const Matrix<T>& splitted_loss, const SpMatrix<T>& splitted_reg, const Matrix<T>& multi_loss, const SpMatrix<T>& multi_reg, T& los, const T* weights = NULL) { const int n_reg=reg.num_components(); //T loss_val = loss.eval(w) + lambda*reg.eval(w); T lagrangian = loss.eval_split(splitted_loss) + lambda*reg.eval_split(splitted_reg); Matrix<T> tmp; tmp.copy(splitted_loss); tmp.addVecToCols(w,-T(1.0)); T add =0.5*gamma*tmp.normFsq(); lagrangian += add; los+=add; if (n_reg > 0) { SpMatrix<T> stmp; stmp.copy(splitted_reg); stmp.addVecToCols(w,-T(1.0)); add=0.5*gamma*stmp.normFsq(); lagrangian += add; los+=add; lagrangian -= multi_reg.dot_direct(stmp); } lagrangian -= multi_loss.dot(tmp); return lagrangian; }; template <typename T> void update_multipliers_ADMM(Vector<T>& w, const Matrix<T>& splitted_w_loss, const Matrix<T>& multipliers_w_loss, const SpMatrix<T>& splitted_w_reg, const SpMatrix<T>& multipliers_w_reg, const T gamma) { Vector<T> mean(w.n()); splitted_w_loss.sum_cols(mean); w.copy(mean); multipliers_w_loss.sum_cols(mean); w.add(mean,-T(1.0)/gamma); Vector<T> number_occurences(w.n()); number_occurences.set(splitted_w_loss.n()); const int n_reg=splitted_w_reg.n(); if (n_reg > 0) { SpVector<T> col; mean.setZeros(); for (int i = 0; i<n_reg; ++i) { splitted_w_reg.refCol(i,col); mean.add(col); for (int j = 0; j<col.L(); ++j) number_occurences[col.r(j)]++; } w.add(mean); mean.setZeros(); for (int i = 0; i<n_reg; ++i) { multipliers_w_reg.refCol(i,col); mean.add(col); } w.add(mean,-T(1.0)/gamma); }; w.div(number_occurences); }; template <typename T> void update_multipliers_weighted_ADMM(Vector<T>& w, const Matrix<T>& splitted_w_loss, const Matrix<T>& multipliers_w_loss, const SpMatrix<T>& splitted_w_reg, const SpMatrix<T>& multipliers_w_reg, const T gamma, const T* inner_weights) { Vector<T> mean(w.n()); splitted_w_loss.sum_cols(mean); w.copy(mean); multipliers_w_loss.sum_cols(mean); w.add(mean,-T(1.0)/gamma); Vector<T> number_occurences(w.n()); number_occurences.set(splitted_w_loss.n()); const int n_reg=splitted_w_reg.n(); if (n_reg > 0) { SpVector<T> col; mean.setZeros(); for (int i = 0; i<n_reg; ++i) { splitted_w_reg.refCol(i,col); for (int j = 0; j<col.L(); ++j) { mean[col.r(j)]+=inner_weights[j]*col.v(j); number_occurences[col.r(j)]+=inner_weights[j]*inner_weights[j]; } } w.add(mean); mean.setZeros(); for (int i = 0; i<n_reg; ++i) { multipliers_w_reg.refCol(i,col); for (int j = 0; j<col.L(); ++j) mean[col.r(j)]+=inner_weights[j]*col.v(j); } w.add(mean,-T(1.0)/gamma); }; w.div(number_occurences); }; template <typename T> void ADMM(const SplittingFunction<T, Matrix<T> >& loss, const SplittingFunction<T, SpMatrix<T> >& reg, const Vector<T>& w0, Vector<T>& w, Vector<T>& optim_info, const ParamFISTA<T>& param) { const T gamma = param.c; const int n_reg=reg.num_components(); const int it0 = MAX(1,param.it0); const T lambda=param.lambda; w.copy(w0); Matrix<T> splitted_w_loss; SpMatrix<T> splitted_w_reg; Matrix<T> multipliers_w_loss; SpMatrix<T> multipliers_w_reg; loss.init_split_variables(multipliers_w_loss); reg.init_split_variables(multipliers_w_reg); splitted_w_loss.copy(multipliers_w_loss); splitted_w_loss.addVecToCols(w); if (n_reg > 0) { splitted_w_reg.copy(multipliers_w_reg); splitted_w_reg.addVecToCols(w); } Timer time; time.start(); int it=0; T los; T old_los=INFINITY; for (it = 0; it<param.max_it; ++it) { if (((it % it0) == 0)) { time.stop(); if (param.is_inner_weights) { los= loss.eval(w)+lambda*reg.eval_weighted(w,splitted_w_reg, param.inner_weights); } else { los= loss.eval(w)+lambda*reg.eval(w); } optim_info[0]=los; T sec=time.getElapsed(); optim_info[2]=sec; if (param.verbose) { cout << "Iter: " << it << ", loss: " << los << ", time: " << sec << endl; flush(cout); if (param.log) writeLog(it,sec,los,T(0),param.logName); } time.start(); } if (param.is_inner_weights) { /// update w update_multipliers_weighted_ADMM(w,splitted_w_loss,multipliers_w_loss,splitted_w_reg,multipliers_w_reg,gamma,param.inner_weights); /// update the splitting variables splitted_w_loss.copy(multipliers_w_loss); splitted_w_loss.scal((1.0)/gamma); splitted_w_loss.addVecToCols(w); loss.prox_split(splitted_w_loss,T(1.0)/gamma); if (n_reg > 0) { splitted_w_reg.copy(multipliers_w_reg); splitted_w_reg.scal((1.0)/gamma); splitted_w_reg.addVecToColsWeighted(w,param.inner_weights); reg.prox_split(splitted_w_reg,lambda/gamma); } /// update multipliers multipliers_w_loss.addVecToCols(w,gamma); multipliers_w_loss.add(splitted_w_loss,-gamma); if (n_reg > 0) { multipliers_w_reg.addVecToColsWeighted(w,param.inner_weights, gamma); multipliers_w_reg.add_direct(splitted_w_reg,-gamma); } } else { /// update w update_multipliers_ADMM(w,splitted_w_loss,multipliers_w_loss,splitted_w_reg,multipliers_w_reg,gamma); /// update the splitting variables splitted_w_loss.copy(multipliers_w_loss); splitted_w_loss.scal((1.0)/gamma); splitted_w_loss.addVecToCols(w); loss.prox_split(splitted_w_loss,T(1.0)/gamma); if (n_reg > 0) { splitted_w_reg.copy(multipliers_w_reg); splitted_w_reg.scal((1.0)/gamma); splitted_w_reg.addVecToCols(w); reg.prox_split(splitted_w_reg,lambda/gamma); } /// update multipliers multipliers_w_loss.addVecToCols(w,gamma); multipliers_w_loss.add(splitted_w_loss,-gamma); if (n_reg > 0) { multipliers_w_reg.addVecToCols(w,gamma); multipliers_w_reg.add_direct(splitted_w_reg,-gamma); } } /// stopping criterion if ((it % it0) == 0) { if (it > 0 && (old_los-los)/old_los < param.tol) break; old_los=los; } } if (param.is_inner_weights) { los= loss.eval(w)+lambda*reg.eval_weighted(w,splitted_w_reg, param.inner_weights); } else { los= loss.eval(w)+lambda*reg.eval(w); } optim_info[0]=los; optim_info[3]=it; }; template <typename T> void update_multipliers_LinADMM(Vector<T>& w, const SpMatrix<T>& splitted_w_reg, const SpMatrix<T>& multipliers_w_reg, const T gamma, const T delta) { Vector<T> mean(w.n()); Vector<T> number_occurences(w.n()); number_occurences.set(delta); const int n_reg=splitted_w_reg.n(); if (n_reg > 0) { SpVector<T> col; mean.setZeros(); for (int i = 0; i<n_reg; ++i) { splitted_w_reg.refCol(i,col); mean.add(col); for (int j = 0; j<col.L(); ++j) number_occurences[col.r(j)]+=gamma; } mean.scal(gamma); for (int i = 0; i<n_reg; ++i) { multipliers_w_reg.refCol(i,col); mean.add(col); } w.add(mean); }; w.div(number_occurences); }; template <typename T> void LinADMM(const SplittingFunction<T, Matrix<T> >& loss, const SplittingFunction<T, SpMatrix<T> >& reg, const Vector<T>& w0, Vector<T>& w, Vector<T>& optim_info, const ParamFISTA<T>& param) { const T gamma = param.c; const int n_reg=reg.num_components(); const int it0 = MAX(1,param.it0); const T lambda=param.lambda; w.copy(w0); SpMatrix<T> primal_reg; SpMatrix<T> dual_reg; reg.init_split_variables(dual_reg); if (n_reg > 0) { primal_reg.copy(dual_reg); primal_reg.addVecToCols(w); } Vector<T> prim_loss; loss.init_prim_var(prim_loss); Vector<T> dual_loss; dual_loss.copy(prim_loss); Timer time; time.start(); int it=0; T los; T old_los=INFINITY; for (it = 0; it<param.max_it; ++it) { /*w.print("w"); prim_loss.print("z"); dual_loss.print("nu"); primal_reg.print("zg"); dual_reg.print("nug");*/ if (((it % it0) == 0)) { time.stop(); los= loss.eval(w)+lambda*reg.eval(w); optim_info[0]=los; T sec=time.getElapsed(); optim_info[2]=sec; if (param.verbose) { cout << "Iter: " << it << ", loss: " << los << ", time: " << sec << endl; flush(cout); if (param.log) writeLog(it,sec,los,T(0),param.logName); } time.start(); } /// update primal_loss variables loss.prox_prim_var(prim_loss,dual_loss,w,gamma); /// update primal_reg variables if (n_reg > 0) { primal_reg.copy(dual_reg); primal_reg.scal(-(1.0)/gamma); primal_reg.addVecToCols(w); reg.prox_split(primal_reg,lambda/gamma); } /// update w loss.compute_new_prim(w,prim_loss,dual_loss,gamma,param.delta); update_multipliers_LinADMM(w,primal_reg,dual_reg,gamma,param.delta); /// update multipliers if (n_reg > 0) { dual_reg.addVecToCols(w,-gamma); dual_reg.add_direct(primal_reg,gamma); } loss.add_mult_design_matrix(w,dual_loss,-gamma); dual_loss.add(prim_loss,gamma); /// stopping criterion if ((it % it0) == 0) { if (it > 0 && (old_los-los)/old_los < param.tol) break; old_los=los; } } los= loss.eval(w)+lambda*reg.eval(w); optim_info[0]=los; optim_info[3]=it; }; template <typename T> SplittingFunction<T, SpMatrix<T> >* setRegularizerADMM(const ParamFISTA<T>& param, const GraphStruct<T>* graph_st = NULL, const TreeStruct<T>* tree_st = NULL) { SplittingFunction<T, SpMatrix<T> >* reg; ParamReg<T> param_reg; param_reg.pos=param.pos; param_reg.intercept=param.intercept; param_reg.tree_st=const_cast<TreeStruct<T>* >(tree_st); param_reg.graph_st=const_cast<GraphStruct<T>* >(graph_st); param_reg.resetflow=param.resetflow; param_reg.clever=param.clever; switch (param.regul) { case GRAPH: param_reg.linf=true; reg=new GraphLasso<T>(param_reg); break; case GRAPH_L2: param_reg.linf=false; reg=new GraphLasso<T>(param_reg); break; case NONE: reg=new None<T>(); break; default: cerr << "Not implemented"; exit(1); } return reg; }; template <typename T> Regularizer<T>* setRegularizerVectors(const ParamFISTA<T>& param, const GraphStruct<T>* graph_st = NULL, const TreeStruct<T>* tree_st = NULL, const GraphPathStruct<T>* graph_path_st=NULL) { ParamReg<T> param_reg; param_reg.pos=param.pos; param_reg.intercept=param.intercept; param_reg.lambda2d1=param.lambda2/param.lambda; param_reg.lambda3d1=param.lambda3/param.lambda; param_reg.size_group=param.size_group; param_reg.tree_st=const_cast<TreeStruct<T>* >(tree_st); param_reg.graph_st=const_cast<GraphStruct<T>* >(graph_st); param_reg.graph_path_st=const_cast<GraphPathStruct<T>* >(graph_path_st); param_reg.resetflow=param.resetflow; param_reg.clever=param.clever; param_reg.ngroups=param.ngroups; param_reg.groups=param.groups; Regularizer<T>* reg; switch (param.regul) { case L0: reg=new Lzero<T>(param_reg); break; case L1: reg=new Lasso<T>(param_reg); break; case L2: reg=new normL2<T>(param_reg); break; case LINF: reg=new normLINF<T>(param_reg); break; case RIDGE: reg=new Ridge<T>(param_reg); break; case ELASTICNET: reg=new typename ElasticNet<T>::type(param_reg); break; case FUSEDLASSO: reg=new FusedLasso<T>(param_reg); break; case TREE_L0: reg=new TreeLzero<T>(param_reg); break; case TREE_L2: param_reg.linf=false; reg=new TreeLasso<T>(param_reg); break; case TREE_LINF: param_reg.linf=true; reg=new TreeLasso<T>(param_reg); break; case GRAPH: param_reg.linf=true; reg=new GraphLasso<T>(param_reg); break; case GRAPH_RIDGE: param_reg.linf=true; reg=new typename GraphLassoRidge<T>::type(param_reg); break; case GRAPH_L2: param_reg.linf=false; reg=new GraphLasso<T>(param_reg); break; case TRACE_NORM_VEC: reg=new ProxMatToVec<T, TraceNorm<T> >(param_reg); break; case RANK_VEC: reg=new ProxMatToVec<T, Rank<T> >(param_reg); break; case GROUPLASSO_L2: reg=new typename GroupLassoL2<T>::type(param_reg); break; case GROUPLASSO_LINF: reg=new typename GroupLassoLINF<T>::type(param_reg); break; case GROUPLASSO_L2_L1: reg=new typename GroupLassoL2_L1<T>::type(param_reg); break; case GROUPLASSO_LINF_L1: reg=new typename GroupLassoLINF_L1<T>::type(param_reg); break; case GRAPH_PATH_L0: reg = new GraphPathL0<T>(param_reg); break; case GRAPH_PATH_CONV: reg = new GraphPathConv<T>(param_reg); break; case NONE: reg=new None<T>(); break; default: cerr << "Not implemented"; exit(1); } return reg; }; template <typename T> Regularizer<T, Matrix<T> >* setRegularizerMatrices(const ParamFISTA<T>& param, const int m, const int n, const GraphStruct<T>* graph_st = NULL, const TreeStruct<T>* tree_st = NULL, const GraphPathStruct<T>* graph_path_st=NULL) { ParamReg<T> param_reg; param_reg.transpose=param.transpose; param_reg.pos=param.pos; param_reg.intercept=param.intercept; param_reg.lambda2d1=param.lambda2/param.lambda; param_reg.lambda3d1=param.lambda3/param.lambda; param_reg.size_group=param.size_group; param_reg.num_cols=param.transpose ? m : n; param_reg.tree_st=const_cast<TreeStruct<T>* >(tree_st); param_reg.graph_st=const_cast<GraphStruct<T>* >(graph_st); param_reg.resetflow=param.resetflow; param_reg.clever=param.clever; Regularizer<T, Matrix<T> >* reg; switch (param.regul) { case L0: reg=new RegMat<T, Lzero<T> >(param_reg); break; case L1: reg=new RegMat<T, Lasso<T> >(param_reg); break; case L2: reg=new RegMat<T, normL2<T> >(param_reg); break; case LINF: reg=new RegMat<T, normLINF<T> >(param_reg); break; case RIDGE: reg=new RegMat<T, Ridge<T> >(param_reg); break; case ELASTICNET: reg=new RegMat<T, typename ElasticNet<T>::type >(param_reg); break; case FUSEDLASSO: reg=new RegMat<T, FusedLasso<T> >(param_reg); break; case L1L2: reg=new MixedL1L2<T>(param_reg); break; case L1LINF: reg=new MixedL1LINF<T>(param_reg); break; case TRACE_NORM: reg=new TraceNorm<T>(param_reg); break; case RANK: reg=new Rank<T>(param_reg); break; case L1L2_L1: reg=new typename MixedL1L2_L1<T>::type(param_reg); break; case L1LINF_L1: reg=new typename MixedL1LINF_L1<T>::type(param_reg); break; case TREE_L0: reg=new RegMat<T, TreeLzero<T> >(param_reg); break; case TREE_L2: param_reg.linf=false; reg=new RegMat<T, TreeLasso<T> >(param_reg); break; case TREE_LINF: param_reg.linf=true; reg=new RegMat<T, TreeLasso<T> >(param_reg); break; case GRAPH: reg=new RegMat<T, GraphLasso<T> >(param_reg); break; case TREEMULT: reg = new TreeMult<T>(param_reg); break; case GRAPHMULT: reg=new GraphMult<T>(param_reg); break; case L1LINFCR: reg = new MixedL1LINFCR<T>(m,param_reg); break; case GRAPH_PATH_L0: reg = new RegMat<T, GraphPathL0<T> >(param_reg); break; case GRAPH_PATH_CONV: reg = new RegMat<T, GraphPathConv<T> >(param_reg); break; case NONE: reg=new RegMat<T, None<T> >(param_reg); break; default: cerr << "not implemented"; exit(1); } return reg; } template <typename T> void print_info_solver(const ParamFISTA<T>& param) { if (param.verbose) { print_loss(param.loss); print_regul(param.regul); if (param_for_admm(param)) { if (param.admm || param.lin_admm) { if (param.lin_admm) { cout << "Linearized ADMM algorithm" << endl; } else { cout << "ADMM algorithm" << endl; } } } else { if (param.ista) { cout << "ISTA algorithm" << endl; } else if (param.subgrad) { cout << "Subgradient descent" << endl; } else { cout << "FISTA algorithm" << endl; } if ((param.regul == GRAPH || param.regul == TREEMULT || param.regul == GRAPHMULT || param.regul==L1LINFCR) && param.clever) cout << "Projections with arc capacities" << endl; if (param.intercept) cout << "with intercept" << endl; if (param.log && param.logName) { cout << "log activated " << endl; cout << param.logName << endl; cout << endl; } } flush(cout); } }; template <typename T> void solver_admm(const Matrix<T>& X, const Matrix<T>& alpha0, Matrix<T>& alpha, Matrix<T>& optim_info, SplittingFunction<T, SpMatrix<T> >** regularizers, SplittingFunction<T, Matrix<T> >** losses, const ParamFISTA<T>& param) { const int M = X.n(); optim_info.resize(4,M); int i1; #pragma omp parallel for private(i1) for (i1 = 0; i1< M; ++i1) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> Xi; X.refCol(i1,Xi); losses[numT]->init(Xi); Vector<T> alpha0i; alpha0.refCol(i1,alpha0i); Vector<T> alphai; alpha.refCol(i1,alphai); regularizers[numT]->reset(); Vector<T> optim_infoi; optim_info.refCol(i1,optim_infoi); if (param.admm || param.lin_admm) { if (param.lin_admm) { LinADMM(*(losses[numT]),*(regularizers[numT]),alpha0i,alphai,optim_infoi,param); } else { ADMM(*(losses[numT]),*(regularizers[numT]),alpha0i,alphai,optim_infoi,param); } } } } template <typename T> void solver_aux1(const Matrix<T>& X, const Matrix<T>& alpha0, Matrix<T>& alpha, Matrix<T>& optim_info, Regularizer<T, Vector<T> >** regularizers, Loss<T, Vector<T> >** losses, const ParamFISTA<T>& param) { const int M = X.n(); if (param.verbose) { const bool duality = losses[0]->is_fenchel() && regularizers[0]->is_fenchel(); if (duality) cout << "Duality gap via Fenchel duality" << endl; if (!param.ista && param.subgrad && !regularizers[0]->is_subgrad()) { cerr << "Subgradient algorithm is not implemented for this combination of loss/regularization" << endl; exit(1); } cout << "Timings reported do not include loss and fenchel evaluation" << endl; flush(cout); } optim_info.resize(4,M); int i1; #pragma omp parallel for private(i1) for (i1 = 0; i1< M; ++i1) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> Xi; X.refCol(i1,Xi); losses[numT]->init(Xi); Vector<T> alpha0i; alpha0.refCol(i1,alpha0i); Vector<T> alphai; alpha.refCol(i1,alphai); regularizers[numT]->reset(); Vector<T> optim_infoi; optim_info.refCol(i1,optim_infoi); if (param.ista) { ISTA_Generic(*(losses[numT]),*(regularizers[numT]),alpha0i,alphai,optim_infoi,param); } else if (param.subgrad) { subGradientDescent_Generic(*(losses[numT]),*(regularizers[numT]),alpha0i,alphai,optim_infoi,param); } else { FISTA_Generic(*(losses[numT]),*(regularizers[numT]),alpha0i,alphai,optim_infoi,param); } } } template <typename T> void solver_aux2(const Matrix<T>& X, const Matrix<T>& alpha0, Matrix<T>& alpha, Matrix<T>& optim_info, Regularizer<T, Matrix<T> >** regularizers, Loss<T, Matrix<T> >** losses, const ParamFISTA<T>& param) { const int M = X.n(); if (param.verbose) { const bool duality = losses[0]->is_fenchel() && regularizers[0]->is_fenchel(); if (duality) cout << "Duality gap via Fenchel duality" << endl; flush(cout); } optim_info.resize(4,M); int i2; #pragma omp parallel for private(i2) for (i2 = 0; i2< M; ++i2) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> Xi; X.refCol(i2,Xi); losses[numT]->init(Xi); const int N = alpha0.n()/X.n(); Matrix<T> alpha0i; alpha0.refSubMat(i2*N,N,alpha0i); Matrix<T> alphai; alpha.refSubMat(i2*N,N,alphai); regularizers[numT]->reset(); Vector<T> optim_infoi; optim_info.refCol(i2,optim_infoi); if (param.ista) { ISTA_Generic(*(losses[numT]),*(regularizers[numT]),alpha0i,alphai,optim_infoi,param); } else if (param.subgrad) { subGradientDescent_Generic(*(losses[numT]),*(regularizers[numT]),alpha0i,alphai,optim_infoi,param); } else { FISTA_Generic(*(losses[numT]),*(regularizers[numT]),alpha0i,alphai,optim_infoi,param); } } } /// AbstractMatrixB is basically either SpMatrix or Matrix template <typename T> void solver(const Matrix<T>& X, const AbstractMatrixB<T>& D, const Matrix<T>& alpha0, Matrix<T>& alpha, const ParamFISTA<T>& param1, Matrix<T>& optim_info, const GraphStruct<T>* graph_st = NULL, const TreeStruct<T>* tree_st = NULL, const GraphPathStruct<T>* graph_path_st=NULL) { print_info_solver(param1); int num_threads=MIN(X.n(),param1.num_threads); num_threads=init_omp(num_threads); ParamFISTA<T> param=param1; param.copied=true; if (param_for_admm(param)) { if (num_threads > 1) param.verbose=false; SplittingFunction<T>** losses = new SplittingFunction<T>*[num_threads]; SplittingFunction<T, SpMatrix<T> >** regularizers= new SplittingFunction<T, SpMatrix<T> >*[num_threads]; for (int i = 0; i<num_threads; ++i) { regularizers[i]=setRegularizerADMM(param,graph_st,tree_st); switch (param.loss) { case SQUARE: losses[i]=new SqLoss<T>(D); break; case HINGE: losses[i] = new HingeLoss<T>(D); break; default: cerr << "Not implemented" << endl; exit(1); } } solver_admm(X, alpha0, alpha, optim_info, regularizers,losses,param); for (int i = 0; i<num_threads; ++i) { delete(losses[i]); delete(regularizers[i]); } delete[](losses); delete[](regularizers); } else { Matrix<T> G; if (param.loss==HINGE) { cerr << "Loss only implemented for ADMM" << endl; return; } if (param.compute_gram && (param.loss==SQUARE)) D.XtX(G); if (!loss_for_matrices(param.loss) && !(param.transpose || regul_for_matrices(param.regul))) { if (num_threads > 1) param.verbose=false; Loss<T>** losses = new Loss<T>*[num_threads]; Regularizer<T>** regularizers= new Regularizer<T>*[num_threads]; for (int i = 0; i<num_threads; ++i) { regularizers[i]=setRegularizerVectors(param,graph_st,tree_st,graph_path_st); switch (param.loss) { case SQUARE: if (param.compute_gram) { losses[i]=new SqLoss<T>(D,G); } else { losses[i]=new SqLoss<T>(D); } break; case SQUARE_MISSING: losses[i]=new SqLossMissing<T>(D); break; case LOG: losses[i] = new LogLoss<T>(D); break; case LOGWEIGHT: losses[i] = new LogLoss<T,true>(D); break; default: cerr << "Not implemented"; exit(1); } } solver_aux1(X, alpha0, alpha, optim_info, regularizers,losses,param); for (int i = 0; i<num_threads; ++i) { delete(losses[i]); losses[i]=NULL; delete(regularizers[i]); regularizers[i]=NULL; } delete[](losses); delete[](regularizers); } else if (loss_for_matrices(param.loss) && param.loss != CUR) { if (num_threads > 1) param.verbose=false; Loss<T, Matrix<T> >** losses = new Loss<T, Matrix<T> >*[num_threads]; Regularizer<T, Matrix<T> >** regularizers= new Regularizer<T, Matrix<T> >*[num_threads]; const int N = alpha0.n()/X.n(); for (int i = 0; i<num_threads; ++i) { regularizers[i]=setRegularizerMatrices(param,alpha0.m(),N,graph_st,tree_st,graph_path_st); switch (param.loss) { case MULTILOG: losses[i] = new MultiLogLoss<T>(D); break; default: cerr << "Not implemented"; exit(1); } } solver_aux2(X, alpha0, alpha, optim_info, regularizers,losses,param); for (int i = 0; i<num_threads; ++i) { delete(losses[i]); losses[i]=NULL; delete(regularizers[i]); regularizers[i]=NULL; } delete[](losses); delete[](regularizers); } else { /// (loss not for matrices and regul for matrices) or CUR Loss<T, Matrix<T>, Matrix<T> >* loss; Regularizer<T, Matrix<T> >* regularizer; switch (param.loss) { case SQUARE: if (param.compute_gram) { loss=new SqLossMat<T>(D,G); } else { loss=new SqLossMat<T>(D); } break; case SQUARE_MISSING: loss=new LossMat<T, SqLossMissing<T> >(X.n(),D); break; case LOG: loss = new LossMat<T, LogLoss<T,false> >(X.n(),D); break; case LOGWEIGHT: loss = new LossMat<T, LogLoss<T,true> >(X.n(),D); break; case CUR: loss = new LossCur<T>(D); break; default: cerr << "Not implemented"; exit(1); } regularizer=setRegularizerMatrices(param,alpha0.m(),alpha0.n(),graph_st,tree_st,graph_path_st); if (param.verbose) { const bool duality = loss->is_fenchel() && regularizer->is_fenchel(); if (duality) cout << "Duality gap via Fenchel duality" << endl; } loss->init(X); optim_info.resize(4,1); Vector<T> optim_infoi; optim_info.refCol(0,optim_infoi); if (param.ista) { ISTA_Generic(*loss,*regularizer,alpha0,alpha,optim_infoi,param); } else if (param.subgrad) { subGradientDescent_Generic(*loss,*regularizer,alpha0,alpha,optim_infoi,param); } else { FISTA_Generic(*loss,*regularizer,alpha0,alpha,optim_infoi,param); } delete(regularizer); delete(loss); } } }; template <typename T> void PROX(const Matrix<T>& alpha0, Matrix<T>& alpha, const ParamFISTA<T>& param, Vector<T>& val_loss, const GraphStruct<T>* graph_st = NULL, const TreeStruct<T>* tree_st = NULL, const GraphPathStruct<T>* graph_path_st = NULL) { if (param.verbose) { print_regul(param.regul); if ((param.regul == GRAPH || param.regul == TREEMULT || param.regul == GRAPHMULT || param.regul==L1LINFCR) && param.clever) cout << "Projections with arc capacities" << endl; if (param.intercept) cout << "with intercept" << endl; flush(cout); } int num_threads=MIN(alpha.n(),param.num_threads); num_threads=init_omp(num_threads); const int M = alpha.n(); if (!graph_st && param.regul==GRAPH) { cerr << "Graph structure should be provided" << endl; return; } if (!regul_for_matrices(param.regul)) { Regularizer<T>** regularizers= new Regularizer<T>*[num_threads]; for (int i = 0; i<num_threads; ++i) regularizers[i]=setRegularizerVectors(param,graph_st,tree_st,graph_path_st); int i; if (param.eval) val_loss.resize(M); #pragma omp parallel for private(i) for (i = 0; i< M; ++i) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> alpha0i; alpha0.refCol(i,alpha0i); Vector<T> alphai; alpha.refCol(i,alphai); regularizers[numT]->reset(); regularizers[numT]->prox(alpha0i,alphai,param.lambda); if (param.eval) val_loss[i]=regularizers[numT]->eval(alphai); } for (i = 0; i<num_threads; ++i) { delete(regularizers[i]); regularizers[i]=NULL; } delete[](regularizers); } else { /// regul for matrices if (param.eval) val_loss.resize(1); Regularizer<T, Matrix<T> >* regularizer; regularizer=setRegularizerMatrices(param,alpha0.m(),alpha0.n(),graph_st,tree_st,graph_path_st); regularizer->prox(alpha0,alpha,param.lambda); if (param.eval) val_loss[0]=regularizer->eval(alpha); delete(regularizer); } }; template <typename T> void EvalGraphPath(const Matrix<T>& alpha0, const ParamFISTA<T>& param, Vector<T>& val_loss, const GraphPathStruct<T>* graph_path_st, SpMatrix<T>* paths = NULL) { if (param.verbose) { print_regul(param.regul); if (param.intercept) cout << "with intercept" << endl; flush(cout); } int num_threads=MIN(alpha0.n(),param.num_threads); num_threads=init_omp(num_threads); const int M = alpha0.n(); if (!regul_for_matrices(param.regul)) { Regularizer<T>** regularizers= new Regularizer<T>*[num_threads]; for (int i = 0; i<num_threads; ++i) regularizers[i]=setRegularizerVectors<T>(param,NULL,NULL,graph_path_st); int i; val_loss.resize(M); #pragma omp parallel for private(i) for (i = 0; i< M; ++i) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> alphai; alpha0.refCol(i,alphai); regularizers[numT]->reset(); if (i==0 && paths) { val_loss[i]=regularizers[numT]->eval_paths(alphai,*paths); } else { val_loss[i]=regularizers[numT]->eval(alphai); } } for (i = 0; i<num_threads; ++i) { delete(regularizers[i]); regularizers[i]=NULL; } delete[](regularizers); } else { cerr << "Not implemented" << endl; return; } }; } #endif
sharpen.c
// Sam Siewert, July 16, 2020 // // Based on basic PSF convolution as documented in DSP Engineer's Handbook // // http://www.dspguide.com/pdfbook.htm // #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <time.h> //#define IMG_HEIGHT (240) //#define IMG_WIDTH (320) #define IMG_HEIGHT (960) #define IMG_WIDTH (1280) #define ITERATIONS (90) #define FAST_IO typedef double FLOAT; typedef unsigned int UINT32; typedef unsigned long long int UINT64; typedef unsigned char UINT8; // PPM Edge Enhancement Code // UINT8 header[22]; UINT8 R[IMG_HEIGHT*IMG_WIDTH]; UINT8 G[IMG_HEIGHT*IMG_WIDTH]; UINT8 B[IMG_HEIGHT*IMG_WIDTH]; UINT8 convR[IMG_HEIGHT*IMG_WIDTH]; UINT8 convG[IMG_HEIGHT*IMG_WIDTH]; UINT8 convB[IMG_HEIGHT*IMG_WIDTH]; // PPM image array with channels UINT8 RGB[IMG_HEIGHT*IMG_WIDTH*3]; // controls sharpness // increase from K=4.0 and F=8.0 for sharper edges #define K 4.0 #define F 8.0 //#define F 80.0 FLOAT PSF[9] = {-K/F, -K/F, -K/F, -K/F, K+1.0, -K/F, -K/F, -K/F, -K/F}; int main(int argc, char *argv[]) { int fdin, fdout, bytesRead=0, bytesWritten=0, bytesLeft, i, j, iter, rc, pixel, readcnt=0, writecnt=0; UINT64 microsecs=0, millisecs=0; FLOAT temp, fstart, fnow; struct timespec start, now; int thread_count=4; clock_gettime(CLOCK_MONOTONIC, &start); fstart = (FLOAT)start.tv_sec + (FLOAT)start.tv_nsec / 1000000000.0; if(argc < 3) { printf("Usage: sharpen input_file.ppm output_file.ppm\n"); exit(-1); } else { if((fdin = open(argv[1], O_RDONLY, 0644)) < 0) { printf("Error opening %s\n", argv[1]); } //else // printf("File opened successfully\n"); if((fdout = open(argv[2], (O_RDWR | O_CREAT), 0666)) < 0) { printf("Error opening %s\n", argv[1]); } //else // printf("Output file=%s opened successfully\n", "sharpen.ppm"); } bytesLeft=21; //printf("Reading header\n"); // read in all data do { //printf("bytesRead=%d, bytesLeft=%d\n", bytesRead, bytesLeft); bytesRead=read(fdin, (void *)header, bytesLeft); bytesLeft -= bytesRead; } while(bytesLeft > 0); header[21]='\0'; printf("header = %s\n", header); #ifdef FAST_IO bytesRead=0; bytesLeft=IMG_HEIGHT*IMG_WIDTH*3; readcnt=0; printf("START: read %d, bytesRead=%d, bytesLeft=%d\n", readcnt, bytesRead, bytesLeft); // Read in RGB data in large chunks, requesting all and reading residual do { bytesRead=read(fdin, (void *)&RGB[bytesRead], bytesLeft); bytesLeft -= bytesRead; readcnt++; printf("read %d, bytesRead=%d, bytesLeft=%d\n", readcnt, bytesRead, bytesLeft); } while((bytesLeft > 0) && (readcnt < 3)); printf("END: read %d, bytesRead=%d, bytesLeft=%d\n", readcnt, bytesRead, bytesLeft); // create in memory copy from input by channel for(i=0, pixel=0; i<IMG_HEIGHT*IMG_WIDTH; i++, pixel+=3) { R[i]=RGB[pixel+0]; convR[i]=R[i]; G[i]=RGB[pixel+1]; convG[i]=G[i]; B[i]=RGB[pixel+2]; convB[i]=B[i]; } #else // Read RGB data - Very slow one byte at time! for(i=0; i<IMG_HEIGHT*IMG_WIDTH; i++) { rc=read(fdin, (void *)&R[i], 1); convR[i]=R[i]; rc=read(fdin, (void *)&G[i], 1); convG[i]=G[i]; rc=read(fdin, (void *)&B[i], 1); convB[i]=B[i]; } #endif clock_gettime(CLOCK_MONOTONIC, &now); fnow = (FLOAT)now.tv_sec + (FLOAT)now.tv_nsec / 1000000000.0; printf("\nstart test at %lf\n", fnow-fstart); clock_gettime(CLOCK_MONOTONIC, &start); fstart = (FLOAT)start.tv_sec + (FLOAT)start.tv_nsec / 1000000000.0; #pragma omp parallel for num_threads(thread_count) for(iter=0; iter < ITERATIONS; iter++) { // Skip first and last row, no neighbors to convolve with for(i=1; i<((IMG_HEIGHT)-1); i++) { // Skip first and last column, no neighbors to convolve with for(j=1; j<((IMG_WIDTH)-1); j++) { temp=0; temp += (PSF[0] * (FLOAT)R[((i-1)*IMG_WIDTH)+j-1]); temp += (PSF[1] * (FLOAT)R[((i-1)*IMG_WIDTH)+j]); temp += (PSF[2] * (FLOAT)R[((i-1)*IMG_WIDTH)+j+1]); temp += (PSF[3] * (FLOAT)R[((i)*IMG_WIDTH)+j-1]); temp += (PSF[4] * (FLOAT)R[((i)*IMG_WIDTH)+j]); temp += (PSF[5] * (FLOAT)R[((i)*IMG_WIDTH)+j+1]); temp += (PSF[6] * (FLOAT)R[((i+1)*IMG_WIDTH)+j-1]); temp += (PSF[7] * (FLOAT)R[((i+1)*IMG_WIDTH)+j]); temp += (PSF[8] * (FLOAT)R[((i+1)*IMG_WIDTH)+j+1]); if(temp<0.0) temp=0.0; if(temp>255.0) temp=255.0; convR[(i*IMG_WIDTH)+j]=(UINT8)temp; temp=0; temp += (PSF[0] * (FLOAT)G[((i-1)*IMG_WIDTH)+j-1]); temp += (PSF[1] * (FLOAT)G[((i-1)*IMG_WIDTH)+j]); temp += (PSF[2] * (FLOAT)G[((i-1)*IMG_WIDTH)+j+1]); temp += (PSF[3] * (FLOAT)G[((i)*IMG_WIDTH)+j-1]); temp += (PSF[4] * (FLOAT)G[((i)*IMG_WIDTH)+j]); temp += (PSF[5] * (FLOAT)G[((i)*IMG_WIDTH)+j+1]); temp += (PSF[6] * (FLOAT)G[((i+1)*IMG_WIDTH)+j-1]); temp += (PSF[7] * (FLOAT)G[((i+1)*IMG_WIDTH)+j]); temp += (PSF[8] * (FLOAT)G[((i+1)*IMG_WIDTH)+j+1]); if(temp<0.0) temp=0.0; if(temp>255.0) temp=255.0; convG[(i*IMG_WIDTH)+j]=(UINT8)temp; temp=0; temp += (PSF[0] * (FLOAT)B[((i-1)*IMG_WIDTH)+j-1]); temp += (PSF[1] * (FLOAT)B[((i-1)*IMG_WIDTH)+j]); temp += (PSF[2] * (FLOAT)B[((i-1)*IMG_WIDTH)+j+1]); temp += (PSF[3] * (FLOAT)B[((i)*IMG_WIDTH)+j-1]); temp += (PSF[4] * (FLOAT)B[((i)*IMG_WIDTH)+j]); temp += (PSF[5] * (FLOAT)B[((i)*IMG_WIDTH)+j+1]); temp += (PSF[6] * (FLOAT)B[((i+1)*IMG_WIDTH)+j-1]); temp += (PSF[7] * (FLOAT)B[((i+1)*IMG_WIDTH)+j]); temp += (PSF[8] * (FLOAT)B[((i+1)*IMG_WIDTH)+j+1]); if(temp<0.0) temp=0.0; if(temp>255.0) temp=255.0; convB[(i*IMG_WIDTH)+j]=(UINT8)temp; } } } clock_gettime(CLOCK_MONOTONIC, &now); fnow = (FLOAT)now.tv_sec + (FLOAT)now.tv_nsec / 1000000000.0; printf("stop test at %lf for %d frames, fps=%lf, pps=%lf\n\n", fnow-fstart, ITERATIONS, ITERATIONS/(fnow-fstart), (ITERATIONS*IMG_HEIGHT*IMG_WIDTH)/(fnow-fstart)); rc=write(fdout, (void *)header, 21); #ifdef FAST_IO // create in memory copy from input by channel for(i=0, pixel=0; i<IMG_HEIGHT*IMG_WIDTH; i++, pixel+=3) { RGB[pixel+0]=convR[i]; RGB[pixel+1]=convG[i]; RGB[pixel+2]=convB[i]; } bytesWritten=0; bytesLeft=IMG_HEIGHT*IMG_WIDTH*3; writecnt=0; printf("START: write %d, bytesWritten=%d, bytesLeft=%d\n", writecnt, bytesWritten, bytesLeft); // Write RGB data in large chunks, requesting all at once and writing residual do { bytesWritten=write(fdout, (void *)&RGB[bytesWritten], bytesLeft); bytesLeft -= bytesWritten; writecnt++; printf("write %d, bytesWritten=%d, bytesLeft=%d\n", writecnt, bytesWritten, bytesLeft); } while((bytesLeft > 0) && (writecnt < 3)); printf("END: write %d, bytesWritten=%d, bytesLeft=%d\n", writecnt, bytesWritten, bytesLeft); #else // Write RGB data - very slow 1 byte at a time! for(i=0; i<IMG_HEIGHT*IMG_WIDTH; i++) { rc=write(fdout, (void *)&convR[i], 1); rc=write(fdout, (void *)&convG[i], 1); rc=write(fdout, (void *)&convB[i], 1); } #endif close(fdin); close(fdout); }
transpose.h
// This code is part of the Problem Based Benchmark Suite (PBBS) // Copyright (c) 2011-2016 Guy Blelloch and the PBBS team // // 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. #pragma once #include "get_time.h" #include "sequence_ops.h" #include "utilities.h" namespace pbbs { constexpr const size_t TRANS_THRESHHOLD = PAR_GRANULARITY / 4; inline size_t split(size_t n) { return n / 2; // return ((((size_t) 1) << log2_up(n) != n) ? n/2 : (7*(n+1))/16); } template <class E> struct transpose { E *A, *B; transpose(E *AA, E *BB) : A(AA), B(BB) {} void transR(size_t rStart, size_t rCount, size_t rLength, size_t cStart, size_t cCount, size_t cLength) { if (cCount * rCount < TRANS_THRESHHOLD) { for (size_t i = rStart; i < rStart + rCount; i++) for (size_t j = cStart; j < cStart + cCount; j++) B[j * cLength + i] = A[i * rLength + j]; } else if (cCount > rCount) { size_t l1 = split(cCount); size_t l2 = cCount - l1; auto left = [&]() { transR(rStart, rCount, rLength, cStart, l1, cLength); }; auto right = [&]() { transR(rStart, rCount, rLength, cStart + l1, l2, cLength); }; par_do(left, right); } else { size_t l1 = split(cCount); size_t l2 = rCount - l1; auto left = [&]() { transR(rStart, l1, rLength, cStart, cCount, cLength); }; auto right = [&]() { transR(rStart + l1, l2, rLength, cStart, cCount, cLength); }; par_do(left, right); } } void trans(size_t rCount, size_t cCount) { #if defined(OPENMP) #pragma omp parallel #pragma omp single #endif transR(0, rCount, cCount, 0, cCount, rCount); } }; template <class E, class int_t> struct blockTrans { E *A, *B; int_t *OA, *OB; blockTrans(E *AA, E *BB, int_t *OOA, int_t *OOB) : A(AA), B(BB), OA(OOA), OB(OOB) {} void transR(size_t rStart, size_t rCount, size_t rLength, size_t cStart, size_t cCount, size_t cLength) { if (cCount * rCount < TRANS_THRESHHOLD * 16) { parallel_for(rStart, rStart + rCount, [&](size_t i) { for (size_t j = cStart; j < cStart + cCount; j++) { size_t sa = OA[i * rLength + j]; size_t sb = OB[j * cLength + i]; size_t l = OA[i * rLength + j + 1] - sa; for (size_t k = 0; k < l; k++) move_uninitialized(B[k + sb], A[k + sa]); } }); } else if (cCount > rCount) { size_t l1 = split(cCount); size_t l2 = cCount - l1; auto left = [&]() { transR(rStart, rCount, rLength, cStart, l1, cLength); }; auto right = [&]() { transR(rStart, rCount, rLength, cStart + l1, l2, cLength); }; par_do(left, right); } else { size_t l1 = split(cCount); size_t l2 = rCount - l1; auto left = [&]() { transR(rStart, l1, rLength, cStart, cCount, cLength); }; auto right = [&]() { transR(rStart + l1, l2, rLength, cStart, cCount, cLength); }; par_do(left, right); } } void trans(size_t rCount, size_t cCount) { #if defined(OPENMP) #pragma omp parallel #pragma omp single #endif transR(0, rCount, cCount, 0, cCount, rCount); } }; // Moves values from blocks to buckets // From is sorted by key within each block, in block major // counts is the # of keys in each bucket for each block, in block major // From and To are of lenght n // counts is of length num_blocks * num_buckets // Data is memcpy'd into To avoiding initializers and overloaded = template <typename E, typename s_size_t> size_t *transpose_buckets(E *From, E *To, s_size_t *counts, size_t n, size_t block_size, size_t num_blocks, size_t num_buckets) { timer t("transpose", false); size_t m = num_buckets * num_blocks; sequence<s_size_t> dest_offsets; //(m); auto add = addm<s_size_t>(); // std::cout << "ss 8" << std::endl; // for smaller input do non-cache oblivious version if (n < (1 << 22) || num_buckets <= 512 || num_blocks <= 512) { size_t block_bits = log2_up(num_blocks); size_t block_mask = num_blocks - 1; if ((size_t)1 << block_bits != num_blocks) { std::cout << "in transpose_buckets: num_blocks must be a power or 2" << std::endl; abort(); } // determine the destination offsets auto get = [&](size_t i) { return counts[(i >> block_bits) + num_buckets * (i & block_mask)]; }; // slow down? dest_offsets = sequence<s_size_t>(m, get); size_t sum = scan_inplace(dest_offsets.slice(), add); if (sum != n) abort(); t.next("seq and scan"); // send each key to correct location within its bucket auto f = [&](size_t i) { size_t s_offset = i * block_size; for (size_t j = 0; j < num_buckets; j++) { size_t d_offset = dest_offsets[i + num_blocks * j]; size_t len = counts[i * num_buckets + j]; for (size_t k = 0; k < len; k++) move_uninitialized(To[d_offset++], From[s_offset++]); } }; parallel_for(0, num_blocks, f, 1); t.next("trans"); free_array(counts); } else { // for larger input do cache efficient transpose sequence<s_size_t> source_offsets(counts, m); dest_offsets = sequence<s_size_t>(m); size_t total; transpose<s_size_t>(counts, dest_offsets.begin()) .trans(num_blocks, num_buckets); t.next("trans 1"); // std::cout << "ss 9" << std::endl; // do both scans inplace total = scan_inplace(dest_offsets.slice(), add); if (total != n) abort(); total = scan_inplace(source_offsets.slice(), add); if (total != n) abort(); source_offsets[m] = n; t.next("scans"); blockTrans<E, s_size_t>(From, To, source_offsets.begin(), dest_offsets.begin()) .trans(num_blocks, num_buckets); t.next("trans 2"); // std::cout << "ss 10" << std::endl; } size_t *bucket_offsets = new_array_no_init<size_t>(num_buckets + 1); for (s_size_t i = 0; i < num_buckets; i++) bucket_offsets[i] = dest_offsets[i * num_blocks]; // last element is the total size n bucket_offsets[num_buckets] = n; return bucket_offsets; } } // namespace pbbs
target_teams_distribute_parallel_for_simd_misc_messages.c
// RUN: %clang_cc1 -fsyntax-only -fopenmp -verify %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -verify %s -Wuninitialized // expected-error@+1 {{unexpected OpenMP directive '#pragma omp target teams distribute parallel for simd'}} #pragma omp target teams distribute parallel for simd // expected-error@+1 {{unexpected OpenMP directive '#pragma omp target teams distribute parallel for simd'}} #pragma omp target teams distribute parallel for simd foo void test_no_clause() { int i; #pragma omp target teams distribute parallel for simd for (i = 0; i < 16; ++i) ; // expected-error@+2 {{statement after '#pragma omp target teams distribute parallel for simd' must be a for loop}} #pragma omp target teams distribute parallel for simd ++i; } void test_branch_protected_scope() { int i = 0; L1: ++i; int x[24]; #pragma omp target teams distribute parallel for simd for (i = 0; i < 16; ++i) { if (i == 5) goto L1; // expected-error {{use of undeclared label 'L1'}} else if (i == 6) return; // expected-error {{cannot return from OpenMP region}} else if (i == 7) goto L2; else if (i == 8) { L2: x[i]++; } } if (x[0] == 0) goto L2; // expected-error {{use of undeclared label 'L2'}} else if (x[1] == 1) goto L1; } void test_invalid_clause() { int i; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute parallel for simd' are ignored}} #pragma omp target teams distribute parallel for simd foo bar for (i = 0; i < 16; ++i) ; } void test_non_identifiers() { int i, x; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute parallel for simd' are ignored}} #pragma omp target teams distribute parallel for simd; for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute parallel for simd' are ignored}} #pragma omp target teams distribute parallel for simd private(x); for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute parallel for simd' are ignored}} #pragma omp target teams distribute parallel for simd, private(x); for (i = 0; i < 16; ++i) ; } extern int foo(); void test_collapse() { int i; // expected-error@+1 {{expected '('}} #pragma omp target teams distribute parallel for simd collapse for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd collapse( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd collapse() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd collapse(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd collapse(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp target teams distribute parallel for simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp target teams distribute parallel for simd collapse 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute parallel for simd collapse(4 for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute parallel for simd collapse(4, for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute parallel for simd collapse(4, ) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} // expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute parallel for simd collapse(4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute parallel for simd collapse(4 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute parallel for simd collapse(4, , 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} #pragma omp target teams distribute parallel for simd collapse(4) for (int i1 = 0; i1 < 16; ++i1) for (int i2 = 0; i2 < 16; ++i2) for (int i3 = 0; i3 < 16; ++i3) for (int i4 = 0; i4 < 16; ++i4) foo(); // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute parallel for simd collapse(4, 8) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp target teams distribute parallel for simd collapse(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp target teams distribute parallel for simd collapse(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute parallel for simd collapse(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute parallel for simd collapse(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute parallel for simd collapse(5 - 5) for (i = 0; i < 16; ++i) ; // expected-error@+4 {{OpenMP constructs may not be nested inside a simd region}} #pragma omp target teams distribute parallel for simd collapse(2) firstprivate(i) for (i = 0; i < 16; ++i) for (int j = 0; j < 16; ++j) #pragma omp parallel for reduction(+ : i, j) for (int k = 0; k < 16; ++k) i += j; } void test_private() { int i; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd private( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute parallel for simd private(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute parallel for simd private(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd private() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd private(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target teams distribute parallel for simd private(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target teams distribute parallel for simd private(x) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute parallel for simd private(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute parallel for simd private(x, y, z) for (i = 0; i < 16; ++i) { x = y * i + z; } } void test_lastprivate() { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd lastprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute parallel for simd lastprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute parallel for simd lastprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd lastprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd lastprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target teams distribute parallel for simd lastprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target teams distribute parallel for simd lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute parallel for simd lastprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute parallel for simd lastprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_firstprivate() { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd firstprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute parallel for simd firstprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute parallel for simd firstprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd firstprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd firstprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target teams distribute parallel for simd firstprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; // expected-error@+1 {{lastprivate variable cannot be firstprivate}} expected-note@+1 {{defined as lastprivate}} #pragma omp target teams distribute parallel for simd lastprivate(x) firstprivate(x) for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{lastprivate variable cannot be firstprivate}} expected-note@+1 2 {{defined as lastprivate}} #pragma omp target teams distribute parallel for simd lastprivate(x, y) firstprivate(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 3 {{lastprivate variable cannot be firstprivate}} expected-note@+1 3 {{defined as lastprivate}} #pragma omp target teams distribute parallel for simd lastprivate(x, y, z) firstprivate(x, y, z) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{the value of 'simdlen' parameter must be less than or equal to the value of the 'safelen' parameter}} #pragma omp target teams distribute parallel for simd simdlen(64) safelen(8) for (i = 0; i < 16; ++i) ; } void test_loop_messages() { float a[100], b[100], c[100]; // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp target teams distribute parallel for simd for (float fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp target teams distribute parallel for simd for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } }
electrons.c
/*--------------------------------------------------------------------------------- ELECTRONS.C -Initialize electron and gas entropies -Assign electron and total entropies based on https://academic.oup.com/mnras/article/454/2/1848/2892599 ---------------------------------------------------------------------------------*/ #include "decs.h" #if ELECTRONS // TODO put these in options with a default in decs.h // Defined as in decs.h, CONSTANT not included in ALLMODELS version // KAWAZURA is run by default if ALLMODELS=0 #define KAWAZURA 9 #define WERNER 10 #define ROWAN 11 #define SHARMA 12 #define CONSTANT 5 //tbh, this is never considered void fixup_electrons_1zone(struct FluidState *S, int i, int j); void heat_electrons_1zone(struct GridGeom *G, struct FluidState *Sh, struct FluidState *S, int i, int j); double get_fels(struct GridGeom *G, struct FluidState *S, int i, int j, int model); void init_electrons(struct GridGeom *G, struct FluidState *S) { ZLOOPALL { // Set electron internal energy to constant fraction of internal energy double uel = fel0*S->P[UU][j][i]; // Initialize entropies S->P[KTOT][j][i] = (gam-1.)*S->P[UU][j][i]*pow(S->P[RHO][j][i],-gam); // Initialize model entropy(ies) for (int idx = KEL0; idx < NVAR ; idx++) { S->P[idx][j][i] = (game-1.)*uel*pow(S->P[RHO][j][i],-game); } } // Necessary? Usually called right afterward set_bounds(G, S); } // TODO merge these void heat_electrons(struct GridGeom *G, struct FluidState *Ss, struct FluidState *Sf) { timer_start(TIMER_ELECTRON_HEAT); #pragma omp parallel for collapse(2) ZLOOP { heat_electrons_1zone(G, Ss, Sf, i, j); } timer_stop(TIMER_ELECTRON_HEAT); } inline void heat_electrons_1zone(struct GridGeom *G, struct FluidState *Ss, struct FluidState *Sf, int i, int j) { // Actual entropy at final time double kHarm = (gam-1.)*Sf->P[UU][j][i]/pow(Sf->P[RHO][j][i],gam); // Evolve model entropy(ies) for (int idx = KEL0; idx < NVAR ; idx++) { double fel = get_fels(G, Ss, i, j, idx); Sf->P[idx][j][i] += (game-1.)/(gam-1.)*pow(Ss->P[RHO][j][i],gam-game)*fel*(kHarm - Sf->P[KTOT][j][i]); } // Reset total entropy Sf->P[KTOT][j][i] = kHarm; } // New function for ALLMODELS runs. inline double get_fels(struct GridGeom *G, struct FluidState *S, int i, int j, int model) { get_state(G, S, i, j, CENT); double bsq = bsq_calc(S, i, j); double fel = 0.0; if (model == KAWAZURA) { // Equation (2) in http://www.pnas.org/lookup/doi/10.1073/pnas.1812491116 double Tpr = (gamp-1.)*S->P[UU][j][i]/S->P[RHO][j][i]; double uel = 1./(game-1.)*S->P[model][j][i]*pow(S->P[RHO][j][i],game); double Tel = (game-1.)*uel/S->P[RHO][j][i]; if(Tel <= 0.) Tel = SMALL; if(Tpr <= 0.) Tpr = SMALL; double Trat = fabs(Tpr/Tel); double pres = S->P[RHO][j][i]*Tpr; // Proton pressure double beta = pres/bsq*2; if(beta > 1.e20) beta = 1.e20; double QiQe = 35./(1. + pow(beta/15.,-1.4)*exp(-0.1/Trat)); fel = 1./(1. + QiQe); } else if (model == WERNER) { // Equation (3) in http://academic.oup.com/mnras/article/473/4/4840/4265350 double sigma = bsq/S->P[RHO][j][i]; fel = 0.25*(1+pow(((sigma/5.)/(2+(sigma/5.))), .5)); } else if (model == ROWAN) { // Equation (34) in https://iopscience.iop.org/article/10.3847/1538-4357/aa9380 double pres = (gamp-1.)*S->P[UU][j][i]; // Proton pressure double pg = (gam-1)*S->P[UU][j][i]; double beta = pres/bsq*2; double sigma = bsq/(S->P[RHO][j][i]+S->P[UU][j][i]+pg); double betamax = 0.25/sigma; fel = 0.5*exp(-pow(1-beta/betamax, 3.3)/(1+1.2*pow(sigma, 0.7))); } else if (model == SHARMA) { // Equation for \delta on pg. 719 (Section 4) in https://iopscience.iop.org/article/10.1086/520800 double Tpr = (gamp-1.)*S->P[UU][j][i]/S->P[RHO][j][i]; double uel = 1./(game-1.)*S->P[model][j][i]*pow(S->P[RHO][j][i],game); double Tel = (game-1.)*uel/S->P[RHO][j][i]; if(Tel <= 0.) Tel = SMALL; if(Tpr <= 0.) Tpr = SMALL; double Trat_inv = fabs(Tel/Tpr); //Inverse of the temperature ratio in KAWAZURA double QeQi = 0.33 * pow(Trat_inv, 0.5); fel = 1./(1.+1./QeQi); } #if SUPPRESS_HIGHB_HEAT if(bsq/S->P[RHO][j][i] > 1.) fel = 0; #endif return fel; } void fixup_electrons(struct FluidState *S) { timer_start(TIMER_ELECTRON_FIXUP); #pragma omp parallel for collapse(2) ZLOOP { fixup_electrons_1zone(S, i, j); } timer_stop(TIMER_ELECTRON_FIXUP); } inline void fixup_electrons_1zone(struct FluidState *S, int i, int j) { double kelmax = S->P[KTOT][j][i]*pow(S->P[RHO][j][i],gam-game)/(tptemin*(gam-1.)/(gamp-1.) + (gam-1.)/(game-1.)); double kelmin = S->P[KTOT][j][i]*pow(S->P[RHO][j][i],gam-game)/(tptemax*(gam-1.)/(gamp-1.) + (gam-1.)/(game-1.)); // Replace NANs with cold electrons for (int idx = KEL0; idx < NVAR ; idx++) { if (isnan(S->P[idx][j][i])) S->P[idx][j][i] = kelmin; // Enforce maximum Tp/Te S->P[idx][j][i] = MY_MAX(S->P[idx][j][i], kelmin); // Enforce minimum Tp/Te S->P[idx][j][i] = MY_MIN(S->P[idx][j][i], kelmax); } } #endif // ELECTRONS
Example_host_teams.1.c
/* * @@name: host_teams.2.c * @@type: C * @@compilable: yes * @@linkable: yes * @@expect: success * @@version: omp_5.0 */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> #define N 1000 int main(){ int nteams_required=2, max_thrds, tm_id; float sp_x[N], sp_y[N], sp_a=0.0001e0; double dp_x[N], dp_y[N], dp_a=0.0001e0; // Create 2 teams, each team works in a different precision #pragma omp teams num_teams(nteams_required) \ thread_limit(max_thrds) private(tm_id) { tm_id = omp_get_team_num(); if( omp_get_num_teams() != 2 ) //if only getting 1, quit { printf("error: Insufficient teams on host, 2 required\n"); exit(0); } if(tm_id == 0) // Do Single Precision Work (SAXPY) with this team { #pragma omp parallel { #pragma omp for //init for(int i=0; i<N; i++){sp_x[i] = i*0.0001; sp_y[i]=i; } #pragma omp for simd simdlen(8) for(int i=0; i<N; i++){sp_x[i] = sp_a*sp_x[i] + sp_y[i];} } } if(tm_id == 1) // Do Double Precision Work (DAXPY) with this team { #pragma omp parallel { #pragma omp for //init for(int i=0; i<N; i++){dp_x[i] = i*0.0001; dp_y[i]=i; } #pragma omp for simd simdlen(4) for(int i=0; i<N; i++){dp_x[i] = dp_a*dp_x[i] + dp_y[i];} } } } printf("i=%d sp|dp %f %f \n",N-1, sp_x[N-1], dp_x[N-1]); printf("i=%d sp|dp %f %f \n",N/2, sp_x[N/2], dp_x[N/2]); //OUTPUT1:i=999 sp|dp 999.000000 999.000010 //OUTPUT2:i=500 sp|dp 500.000000 500.000005 return 0; }
debug_test_system.h
// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2012, Knut Reinert, FU Berlin // 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. // // ========================================================================== // Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de> // ========================================================================== // The SeqAn testing infrastructure. Based on ideas from the OpenMS // "ClassTest.h". // ========================================================================== // TODO(holtgrew): This could use some cleanup. // SEQAN_NO_GENERATED_FORWARDS #ifndef SEQAN_CORE_INCLUDE_SEQAN_BASIC_DEBUG_TEST_SYSTEM_H_ #define SEQAN_CORE_INCLUDE_SEQAN_BASIC_DEBUG_TEST_SYSTEM_H_ #include <iostream> // stdout, stderr #include <iomanip> #include <cstring> // strrpos #include <cstdlib> // exit() #include <cstdio> #include <cstdarg> // va_start, va_list, va_end #include <set> #include <vector> #include <string> #ifdef PLATFORM_WINDOWS #include <Windows.h> // DeleteFile() #else // #ifdef PLATFORM_WINDOWS #include <unistd.h> // unlink() #if SEQAN_HAS_EXECINFO #include <execinfo.h> // backtrace(), backtrace_symbols() #endif // #if SEQAN_HAS_EXECINFO #include <cxxabi.h> // __cxa_demangle() #include <signal.h> #endif // #ifdef PLATFORM_WINDOWS /** .Macro.SEQAN_FAIL ..cat:Assertions ..summary:Force abortion of program, regardless of debugging settings. ..signature:SEQAN_FAIL(msg[, args]) ..param.msg:A format string. ..param.args:An optional list of arguments. ..remarks:Use this if something really unexpected happens inside your functions and there is no way to report this through the API. A good example would be logic errors, e.g. invalid values. ..example.text:In the following example, the $SEQAN_FAIL$ is there if a possible value is added to $MyEnum$ but the function $foo$ is not updated accordingly. ..example.code: enum MyEnum { VALUE_ONE, VALUE_TWO }; bool foo(MyEnum x) { switch (x) { case VALUE_ONE: // do something return true; case VALUE_TWO: // do something return true; } SEQAN_FAIL("Logic error. Should never reach here. x == %d.", x); return false; } ..include:seqan/basic.h ..see:Macro.SEQAN_CHECK */ #define SEQAN_FAIL(...) \ do { \ ::seqan::ClassTest::forceFail(__FILE__, __LINE__, \ __VA_ARGS__); \ ::seqan::ClassTest::fail(); \ } while (false) /** .Macro.SEQAN_CHECK ..cat:Assertions ..summary:Force abortion of program if a condition is not met, regardless of debugging settings. ..signature:SEQAN_CHECK(condition, msg[, args]) ..param.msg:A format string. ..param.args:An optional list of arguments. ..remarks:Use this if something really unexpected happens inside your functions and there is no way to report this through the API. A good example would be logic errors, e.g. invalid values. ..example.text:In the following example, the $SEQAN_CHECK$ stops program execution if a value is added to $MyEnum$ but the function $foo$ is not updated accordingly. ..example.code: enum MyEnum { VALUE_ONE, VALUE_TWO }; bool foo(MyEnum x) { SEQAN_CHECK((x == VALUE_ONE || x == VALUE_TWO), "Invalid value for x == %d.", x); switch (x) { case VALUE_ONE: // do something return true; case VALUE_TWO: // do something return true; } return false; // Should never reach here, checked above with SEQAN_CHECK. } ..include:seqan/basic.h ..see:Macro.SEQAN_FAIL */ #define SEQAN_CHECK(_arg1, ...) \ do { \ if (!::seqan::ClassTest::testTrue(__FILE__, __LINE__, \ (_arg1), #_arg1, \ __VA_ARGS__)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // SeqAn's has three global debug/testing levels: testing, debug and // release. Depending on the level, the SEQAN_ASSERT_* and // SEQAN_CHECKPOINT macros will be enabled. // // Note that this is independent of the <cassert> assertions and // NDEBUG being defined. // // The levels are enabled by the values of the macros // SEQAN_ENABLE_TESTING and SEQAN_ENABLE_DEBUG. By setting a macro to // 0, one disables the level and by setting the macro to 1, one // enables a level. Enabling testing also enables debug, overriding a // value of 0 for SEQAN_ENABLE_DEBUG. // // If the level is release (both the macros for debug and testing are // 0), the assertions will be disabled. If the level is debug then // the assertions will be enabled. If the level is testing then the // checkpoint macros will also be enabled. // // The default is to enable debugging but disable testing. // // You can print the current level using the function seqan::printDebugLevel(). /** .Macro.SEQAN_ENABLE_TESTING ..cat:Testing & Debugging ..summary:Indicates whether testing is enabled. ..signature:SEQAN_ENABLE_DEBUG ..remarks:When enabled (set to 1), testing is enabled. This means the macros for the tests (@Macro.SEQAN_BEGIN_TESTSUITE@, @Macro.SEQAN_DEFINE_TEST@, @Macro.SEQAN_CALL_TEST@, and @Macro.SEQAN_END_TESTSUITE@) will be enabled. This makes failing assertions raise exceptions instead of call $abort()$ and enables checkpoints. ..remarks:By default, this is set to 0. ..remarks:If @Macro.SEQAN_ENABLE_CHECKPOINTS@ is not defined before including $<seqan/basic.h>$, then @Macro.SEQAN_ENABLE_CHECKPOINTS@ will be set to the value of @Macro.SEQAN_ENABLE_TESTING@ (after the default initialization to 0). ..remarks:If you want to change this value, you have to define this value before including any SeqAn header. ..remarks:If set to 1 then @Macro.SEQAN_ENABLE_TESTING@ is force-set to 0 as well. ..see:Macro.SEQAN_ENABLE_DEBUG ..see:Macro.SEQAN_ENABLE_CHECKPOINTS */ // Set default for SEQAN_ENABLE_TESTING. #ifndef SEQAN_ENABLE_TESTING #define SEQAN_ENABLE_TESTING 0 #endif // #ifndef SEQAN_ENABLE_TESTING /** .Macro.SEQAN_ENABLE_DEBUG ..cat:Testing & Debugging ..summary:Indicates whether debugging is enabled. ..signature:SEQAN_ENABLE_DEBUG ..remarks:When enabled (set to 1), debugging is enabled. This means the assertion macros are expanded to actual code and not to nothing. ..remarks:By default, this is set to 0. ..remarks:If you want to change this value, you have to define this value before including any SeqAn header. ..remarks:Force-enabled if @Macro.SEQAN_ENABLE_TESTING@ is set to 1. ..see:Macro.SEQAN_ENABLE_TESTING ..see:Macro.SEQAN_ENABLE_CHECKPOINTS */ // Set default for SEQAN_ENABLE_DEBUG. #ifndef SEQAN_ENABLE_DEBUG #define SEQAN_ENABLE_DEBUG 1 #endif // #ifndef SEQAN_ENABLE_DEBUG // Force-enable debugging if testing is enabled. #if SEQAN_ENABLE_TESTING #undef SEQAN_ENABLE_DEBUG #define SEQAN_ENABLE_DEBUG 1 #endif // #if SEQAN_ENABLE_TESTING /** .Macro.SEQAN_ENABLE_CHECKPOINTS ..cat:Testing & Debugging ..summary:Indicates whether checkpoints are enabled. ..signature:SEQAN_ENABLE_CHECKPOINTS ..remarks:When enabled (set to 1), checkpoints are enabled. This means the $SEQAN_CHECKPOINT$ macros are expanded to actual code and not to nothing. ..remarks:By default, this is set to $SEQAN_ENABLE_TESTING$. ..remarks:Checkpoints can come at large increases of running time in your tests. Disable them when your test run too slow. ..remarks:If you want to change this value, you have to define this value before including any SeqAn header. ..example.text:Disable checkpoints in a program. ..example.code: // Disable SeqAn checkpoints in this program. #define SEQAN_ENABLE_CHECKPOINTS 0 // Any SeqAn headers or headers including SeqAn headers have to come AFTER the // definition of SEQAN_ENABLE_CHECKPOINT above. #include <seqan/base.h> int main(int argc, char const ** argv) { // Any call to SeqAn functions will NOT log any checkpoints. return 0; } ..see:Macro.SEQAN_ENABLE_DEBUG ..see:Macro.SEQAN_ENABLE_TESTING */ // Allow disabling checkpoints independent of testing. #ifndef SEQAN_ENABLE_CHECKPOINTS #define SEQAN_ENABLE_CHECKPOINTS 0 // SEQAN_ENABLE_TESTING #endif // #ifndef SEQAN_ENABLE_CHECKPOINTS namespace seqan { // SEQAN_CXX_FLAGS_ contains the compiler flags, SEQAN_CXX_FLAGS is a string // literal with this value. #if !defined(SEQAN_CXX_FLAGS_) #define SEQAN_CXX_FLAGS_ SEQAN_CXX_FLAGS_NOT_SET #endif // !defined(SEQAN_CXX_FLAGS__) #define SEQAN_MKSTRING_(str) # str #define SEQAN_MKSTRING(str) SEQAN_MKSTRING_(str) #define SEQAN_CXX_FLAGS SEQAN_MKSTRING(SEQAN_CXX_FLAGS_) //#undef SEQAN_MKSTRING //#undef SEQAN_MKSTRING_ /** .Function.printDebugLevel ..cat:Testing & Debugging ..summary:Print the current SeqAn debug level and the compiler flags to the given stream. ..signature:printDebugLevel(stream) ..param.stream:The stream to print to, e.g. $std::cout$. ..include:seqan/basic.h */ template <typename TStream> void printDebugLevel(TStream &stream) { stream << "SEQAN_ENABLE_DEBUG == " << SEQAN_ENABLE_DEBUG << std::endl; stream << "SEQAN_ENABLE_TESTING == " << SEQAN_ENABLE_TESTING << std::endl; stream << "SEQAN_ENABLE_CHECKPOINTS == " << SEQAN_ENABLE_CHECKPOINTS << std::endl; stream << "SEQAN_CXX_FLAGS == \"" << SEQAN_CXX_FLAGS << "\"" << std::endl; } #if defined(PLATFORM_WINDOWS) || !SEQAN_HAS_EXECINFO template <typename TSize> void printStackTrace(TSize /*maxFrames*/) { } #else // print a demangled stack backtrace of the caller function template <typename TSize> void printStackTrace(TSize maxFrames) { void *addrlist[256]; char temp[4096]; char addr[20]; char offset[20]; size_t size; int status; char *symname; char *demangled; std::cerr << std::endl << "stack trace:" << std::endl; int addrlist_len = backtrace(addrlist, maxFrames); char** symbollist = backtrace_symbols(addrlist, addrlist_len); for (int i = 1; i < addrlist_len; ++i) { offset[0] = 0; addr[0] = 0; demangled = NULL; // LINUX FORMAT: // ./sam2svg [0x473b8c] // /lib/libc.so.6 [0x7f40d2526f60] // ./sam2svg(_Z2f3v+0x10) [0x47200c] // ./sam2svg(_Z2f2v+0xd) [0x472021] // ./sam2svg(main+0x1367) [0x4735fc] // /lib/libc.so.6(__libc_start_main+0xe6) [0x7f40d25131a6] // if (3 == sscanf(symbollist[i], "%*[^(](%4095[^+]+%[^)]) %s", temp, offset, addr)) { symname = temp; if (NULL != (demangled = abi::__cxa_demangle(temp, NULL, &size, &status))) { symname = demangled; } } // MAC OS X FORMAT: // 1 sam2svg 0x0000000100003a39 _ZN5seqanL28signalHandlerPrintStackTraceEi + 21 // 2 libSystem.B.dylib 0x00007fff87a6d67a _sigtramp + 26 // 3 libSystem.B.dylib 0x00007fff87a76df7 tiny_free_do_recirc_to_depot + 980 // 4 sam2svg 0x00000001000021b9 _Z2f2v + 9 // 5 sam2svg 0x00000001000034b1 main + 4546 // 6 sam2svg 0x0000000100002190 start + 52 else if (3 == sscanf(symbollist[i], "%*d %*s %s %s %*s %s", addr, temp, offset)) { symname = temp; if (NULL != (demangled = abi::__cxa_demangle(temp, NULL, &size, &status))) { symname = demangled; } } // LINUX FORMAT: // ./sam2svg [0x473b8c] // /lib/libc.so.6 [0x7f40d2526f60] else if (2 == sscanf(symbollist[i], "%s %s", temp, addr)) { symname = temp; } // DEFAULT: else { symname = symbollist[i]; } std::cerr << std::setw(3) << i - 1; std::cerr << std::setw(20) << addr; std::cerr << " " << symname; if (offset[0] != 0) std::cerr << " + " << offset; std::cerr << std::endl; free(demangled); } std::cerr << std::endl; // Only the array must be freed according to man page, not the contents. free(symbollist); } static void signalHandlerPrintStackTrace(int signum) { std::cerr << std::endl; printStackTrace(20); signal(signum, SIG_DFL); kill(getpid(), signum); } inline int _deploySignalHandlers() { signal(SIGSEGV, signalHandlerPrintStackTrace); // segfault signal(SIGFPE, signalHandlerPrintStackTrace); // divide by zero // ... return 0; } #if SEQAN_ENABLE_DEBUG // automatically deploy signal handlers that output the stack trace on a trap (in debug mode) template <typename T> struct SignalHandlersDummy_ { static const int i; }; template <typename T> const int SignalHandlersDummy_<T>::i = _deploySignalHandlers(); namespace { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-variable" #endif // ifdef __clang__ volatile int signalHandlersDummy_ = SignalHandlersDummy_<void>::i; #ifdef __clang__ #pragma clang diagnostic pop #endif // ifdef __clang__ } #endif // #if SEQAN_ENABLE_DEBUG #endif // defined(PLATFORM_WINDOWS) || !SEQAN_HAS_EXECINFO // Namespace for the testing infrastructure. // // This namespace contains the variables and functions that are used // in the macros below to perform the tests. namespace ClassTest { // Raised when an assertion fails in test mode. struct AssertionFailedException {}; // Container for static global data for the tests. struct StaticData { // Number of tests that were run. static int &testCount() { static int result = 0; return result; } // Number of errors that occured. static int &errorCount() { static int result = 0; return result; } // Number of skipped tests. static int &skippedCount() { static int result = 0; return result; } // Flag whether there was an error in this test. static bool &thisTestOk() { static bool result = 0; return result; } // Flag whether this test was skipped. static bool &thisTestSkipped() { static bool result = 0; return result; } // Name of the current test. static const char *&currentTestName() { const char *defaultValue = ""; static const char *result = const_cast<char*>(defaultValue); return result; } // Base path to the binary. Extrapolated from __FILE__. static char *&basePath() { const char *defaultValue = "."; static char *result = const_cast<char*>(defaultValue); return result; } // Base path to the directory containing "core" and "extras." // Extrapolated from __FILE__. static char *&pathToRoot() { const char *defaultValue = "."; static char *result = const_cast<char*>(defaultValue); return result; } // Total number of checkpoints in header file. static int &totalCheckPointCount() { static int result = 0; return result; } // Total number of checkpoints found in binary files. static int &foundCheckPointCount() { static int result = 0; return result; } // Names of temporary files as returned by tempFileName. This // global state is used to remove any existing such files // after completing the testsuite. static ::std::vector<std::string> & tempFileNames() { static ::std::vector<std::string> filenames; return filenames; } }; // Open a temporary file, unlink it, return posix handle. Note: This has not been tested yet. // TODO(holtgrew): Not used yet and Windows code does not work. /* inline int openTempFile() { #ifdef PLATFORM_WINDOWS char * fileName = _tempnam(NULL, "SQN"); if (!fileName) { ::std::cerr << "Cannot create a unique temporary filename" << ::std::endl; exit(1); } int result = open(fileName, _O_RDWR | OPEN_TEMPORARY); free(fileName); return result; #else // A Unix... char filenameBuffer[100]; strcpy(filenameBuffer, "/tmp/SEQANXXXXXXXXXX"); int result = mkstemp(filenameBuffer); unlink(filenameBuffer); return result; #endif // ifdef PLATFORM_WINDOWS } */ // Return the path to a temporary file, in a static buffer in this // function. This is not thread safe! inline const char *tempFileName() { //IOREV _duplicate_ overlaps with some stuff in system/file_sync.h, should be moved to io-module static char fileNameBuffer[1000]; #ifdef PLATFORM_WINDOWS_VS static char filePathBuffer[1000]; // Gets the temp path env string (no guarantee it's a valid path). DWORD dwRetVal = 0; dwRetVal = GetTempPath(1000, // length of the buffer filePathBuffer); // buffer for path if (dwRetVal > 1000 || (dwRetVal == 0)) { std::cerr << "GetTempPath failed" << std::endl; exit(1); } UINT uRetVal = 0; uRetVal = GetTempFileName(filePathBuffer, // directory for tmp files TEXT("SEQAN."), // temp file name prefix 0, // create unique name fileNameBuffer); // buffer for name if (uRetVal == 0) { std::cerr << "GetTempFileName failed" << std::endl; exit(1); } StaticData::tempFileNames().push_back(fileNameBuffer); return fileNameBuffer; #else // ifdef PLATFORM_WINDOWS_VS strcpy(fileNameBuffer, "/tmp/SEQAN.XXXXXXXXXXXXXXXXXXXX"); #ifdef PLATFORM_WINDOWS_MINGW // There is no mkstemp in MinGW but it does not complain about tmpnam. tmpnam(fileNameBuffer); #else // ifdef PLATFORM_WINDOWS_MINGW int _tmp = mkstemp(fileNameBuffer); (void) _tmp; unlink(fileNameBuffer); #endif // #ifdef PLATFORM_WINDOWS_MINGW StaticData::tempFileNames().push_back(fileNameBuffer); return fileNameBuffer; #endif // ifdef PLATFORM_WINDOWS_VS } // Initialize the testing infrastructure. // // Used through SEQAN_BEGIN_TESTSUITE(test_name) inline void beginTestSuite(const char *testSuiteName, const char *argv0) { // First things first: Print test suite name and current debug level. std::cout << "TEST SUITE " << testSuiteName << std::endl; printDebugLevel(std::cout); (void)testSuiteName; StaticData::testCount() = 0; StaticData::skippedCount() = 0; StaticData::errorCount() = 0; StaticData::totalCheckPointCount() = 0; StaticData::foundCheckPointCount() = 0; // Get path to argv0. const char *end = argv0; const char *ptr = std::min(strchr(argv0, '\\'), strchr(argv0, '/')); // On Windows, we can have both \ and /. for (; ptr != 0; ptr = std::min(strchr(ptr+1, '\\'), strchr(ptr+1, '/'))) end = ptr; int rpos = end - argv0; if (rpos <= 0) { StaticData::basePath() = new char[2]; strcpy(StaticData::basePath(), "."); } else { int len = rpos; StaticData::basePath() = new char[len]; strncpy(StaticData::basePath(), argv0, len); } // Get path to projects. const char *file = __FILE__; int pos = -1; for (size_t i = 0; i < strlen(file) - strlen("core"); ++i) { if (strncmp(file + i, "core", strlen("core")) == 0) { pos = i; } } for (; pos > 0 && *(file + pos - 1) != '/' && *(file + pos - 1) != '\\'; --pos) continue; if (pos == -1) { std::cerr << "Could not extrapolate path to repository from __FILE__ == \"" << __FILE__ << "\"" << std::endl; exit(1); } StaticData::pathToRoot() = new char[pos]; strncpy(StaticData::pathToRoot(), file, pos); StaticData::pathToRoot()[pos-1] = '\0'; #ifdef PLATFORM_WINDOWS_VS // Set CRT reporting such that everything goes to stderr and there are // no popups causing timeouts. _set_error_mode(_OUT_TO_STDERR); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); #endif // PLATFORM_WINDOWS_VS } // Run test suite finalization. // // Used through SEQAN_END_TESTSUITE // // Prints a bottom banner with the error count and returns the // program's return code. inline int endTestSuite() { delete[] StaticData::basePath(); delete[] StaticData::pathToRoot(); std::cout << "**************************************" << std::endl; std::cout << " Total Check Points : " << StaticData::totalCheckPointCount() << std::endl; std::cout << " Found Check Points : " << StaticData::foundCheckPointCount() << std::endl; std::cout << " Lost Check Points : " << StaticData::totalCheckPointCount() - StaticData::foundCheckPointCount() << std::endl; std::cout << "--------------------------------------" << std::endl; std::cout << " Total Tests: " << StaticData::testCount() << std::endl; std::cout << " Skipped: " << StaticData::skippedCount() << std::endl; std::cout << " Errors: " << StaticData::errorCount() << std::endl; std::cout << "**************************************" << std::endl; // TODO(holtgrew): Re-enable that all check points have to be found for the test to return 1; /* if (StaticData::totalCheckPointCount() != StaticData::foundCheckPointCount()) return 1; */ // Delete all temporary files that still exist. for (unsigned i = 0; i < StaticData::tempFileNames().size(); ++i) { #ifdef PLATFORM_WINDOWS DeleteFile(StaticData::tempFileNames()[i].c_str()); #else // #ifdef PLATFORM_WINDOWS unlink(StaticData::tempFileNames()[i].c_str()); #endif // #ifdef PLATFORM_WINDOWS } if (StaticData::errorCount() != 0) return 1; return 0; } // Run test initialization. inline void beginTest(const char *testName) { StaticData::currentTestName() = testName; StaticData::thisTestOk() = true; StaticData::thisTestSkipped() = false; StaticData::testCount() += 1; } // Run test finalization. inline void endTest() { if (StaticData::thisTestSkipped()) { std::cout << StaticData::currentTestName() << " SKIPPED" << std::endl; } else if (StaticData::thisTestOk()) { std::cout << StaticData::currentTestName() << " OK" << std::endl; } else { std::cerr << StaticData::currentTestName() << " FAILED" << std::endl; } } // Marks the current test as "skipped". inline void skipCurrentTest() { StaticData::thisTestSkipped() = true; StaticData::skippedCount() += 1; } // Called by the macro SEQAN_ASSERT_FAIL. inline void forceFail(const char *file, int line, const char *comment, ...) { StaticData::errorCount() += 1; std::cerr << file << ":" << line << " FAILED! "; if (comment) { std::cerr << " ("; va_list args; va_start(args, comment); // vfprintf(stderr, comment, args); va_end(args); std::cerr << ")"; } std::cerr << std::endl; } // Similar to forceFail above, but accepting a va_list parameter. inline void vforceFail(const char *file, int line, const char *comment, va_list argp) { StaticData::errorCount() += 1; std::cerr << file << ":" << line << " FAILED! "; if (comment) { std::cerr << " ("; // vfprintf(stderr, comment, argp); std::cerr << ")"; } std::cerr << std::endl; } // Same as forceFail above, but with comment set to 0. inline void forceFail(const char *file, int line) { forceFail(file, line, 0); } // Called by the macro SEQAN_ASSERT_EQ. // // Tests that the given two value are equal. Returns true iff the // two values are equal. template <typename T1, typename T2> bool testEqual(char const * file, int line, T1 const & value1, char const * expression1, T2 const & value2, char const * expression2, char const * comment, ...) { if (!(value1 == value2)) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression1 << " == " << expression2 << " was: " << value1 << " != " << value2; if (comment) { std::cerr << " ("; va_list args; va_start(args, comment); // vfprintf(stderr, comment, args); va_end(args); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Similar to testEqual above, but accepts a va_list instead of variadic // parameters. template <typename T1, typename T2> bool vtestEqual(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2, const char *comment, va_list argp) { if (!(value1 == value2)) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression1 << " == " << expression2 << " was: " << value1 << " != " << value2; if (comment) { std::cerr << " ("; // vfprintf(stderr, comment, argp); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Same as testEqual above, but with comment set to 0. template <typename T1, typename T2> bool testEqual(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2) { return testEqual(file, line, value1, expression1, value2, expression2, 0); } // Called by the macro SEQAN_ASSERT_IN_DELTA. // // Tests that the given two value are equal. Returns true iff the // two values are equal. template <typename T1, typename T2, typename T3> bool testInDelta(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2, const T3 &value3, const char *expression3, const char *comment, ...) { if (!(value1 >= value2 - value3 && value1 <= value2 + value3)) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression1 << " in [" << expression2 << " - " << expression3 << ", " << expression2 << " + " << expression3 << "] was: " << value1 << " not in [" << value2 - value3 << ", " << value2 + value3 << "]"; if (comment) { std::cerr << " ("; va_list args; va_start(args, comment); // vfprintf(stderr, comment, args); va_end(args); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Similar to testInDelta above, but accepts a va_list instead of variadic // parameters. template <typename T1, typename T2, typename T3> bool vtestInDelta(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2, const T3 &value3, const char *expression3, const char *comment, va_list argp) { if (!(value1 >= value2 - value3 && value1 <= value2 + value3)) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression1 << " in [" << expression2 << " - " << expression3 << ", " << expression2 << " + " << expression3 << "] was: " << value1 << " not in [" << value2 - value3 << ", " << value2 + value3 << "]"; if (comment) { std::cerr << " ("; // vfprintf(stderr, comment, argp); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Same as testInDelta above, but with comment set to 0. template <typename T1, typename T2, typename T3> bool testInDelta(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2, const T3 &value3, const char *expression3) { return testInDelta(file, line, value1, expression1, value2, expression2, value3, expression3, 0); } // Called by the macro SEQAN_ASSERT_NEQ. // // Tests that the given two value are not equal. Returns true iff // the two values are equal. template <typename T1, typename T2> bool testNotEqual(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2, const char *comment, ...) { if (!(value1 != value2)) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression1 << " != " << expression2 << " was: " << value1 << " == " << value2; if (comment) { std::cerr << " ("; va_list args; va_start(args, comment); // vfprintf(stderr, comment, args); va_end(args); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Similar to testNotEqual above, but accepts a va_list instead of variadic // parameters. template <typename T1, typename T2> bool vtestNotEqual(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2, const char *comment, va_list argp) { if (!(value1 != value2)) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression1 << " != " << expression2 << " was: " << value1 << " == " << value2; if (comment) { std::cerr << " ("; // vfprintf(stderr, comment, argp); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Same as testNotEqual above, but with comment set to 0. template <typename T1, typename T2> bool testNotEqual(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2) { return testNotEqual(file, line, value1, expression1, value2, expression2, 0); } // Called by the macro SEQAN_ASSERT_GEQ. // // Tests that the first value is greater than or equal to the // second one. Returns true iff the test yields true. template <typename T1, typename T2> bool testGeq(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2, const char *comment, ...) { if (!(value1 >= value2)) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression1 << " >= " << expression2 << " was: " << value1 << " < " << value2; if (comment) { std::cerr << " ("; va_list args; va_start(args, comment); // vfprintf(stderr, comment, args); va_end(args); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Similar to testGeq above, but accepts a va_list instead of variadic // parameters. template <typename T1, typename T2> bool vtestGeq(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2, const char *comment, va_list argp) { if (!(value1 >= value2)) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression1 << " >= " << expression2 << " was: " << value1 << " < " << value2; if (comment) { std::cerr << " ("; // vfprintf(stderr, comment, argp); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Same as testGeq above, but with comment set to 0. template <typename T1, typename T2> bool testGeq(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2) { return testGeq(file, line, value1, expression1, value2, expression2, 0); } // Called by the macro SEQAN_ASSERT_GT. // // Tests that the first value is greater than the second one. // Returns true iff the test yields true. template <typename T1, typename T2> bool testGt(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2, const char *comment, ...) { if (!(value1 > value2)) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression1 << " > " << expression2 << " was: " << value1 << " <= " << value2; if (comment) { std::cerr << " ("; va_list args; va_start(args, comment); // vfprintf(stderr, comment, args); va_end(args); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Similar to testGt above, but accepts a va_list instead of variadic // parameters. template <typename T1, typename T2> bool vtestGt(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2, const char *comment, va_list argp) { if (!(value1 > value2)) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression1 << " > " << expression2 << " was: " << value1 << " <= " << value2; if (comment) { std::cerr << " ("; // vfprintf(stderr, comment, argp); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Same as testGt above, but with comment set to 0. template <typename T1, typename T2> bool testGt(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2) { return testGt(file, line, value1, expression1, value2, expression2, 0); } // Called by the macro SEQAN_ASSERT_LEQ. // // Tests that the first value is less than or equal to the second // one. Returns true iff the test yields true. template <typename T1, typename T2> bool testLeq(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2, const char *comment, ...) { if (!(value1 <= value2)) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression1 << " <= " << expression2 << " was: " << value1 << " > " << value2; if (comment) { std::cerr << " ("; va_list args; va_start(args, comment); // vfprintf(stderr, comment, args); va_end(args); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Similar to testLeq above, but accepts a va_list instead of variadic // parameters. template <typename T1, typename T2> bool vtestLeq(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2, const char *comment, va_list argp) { if (!(value1 <= value2)) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression1 << " <= " << expression2 << " was: " << value1 << " > " << value2; if (comment) { std::cerr << " ("; // vfprintf(stderr, comment, argp); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Same as testLeq above, but with comment set to 0. template <typename T1, typename T2> bool testLeq(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2) { return testLeq(file, line, value1, expression1, value2, expression2, 0); } // Called by the macro SEQAN_ASSERT_LT. // // Tests that the first value is greater than the second one. // Returns true iff the test yields true. template <typename T1, typename T2> bool testLt(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2, const char *comment, ...) { if (!(value1 < value2)) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression1 << " < " << expression2 << " was: " << value1 << " >= " << value2; if (comment) { std::cerr << " ("; va_list args; va_start(args, comment); // vfprintf(stderr, comment, args); va_end(args); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Similar to testLt above, but accepts a va_list instead of variadic // parameters. template <typename T1, typename T2> bool vtestLt(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2, const char *comment, va_list argp) { if (!(value1 < value2)) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression1 << " < " << expression2 << " was: " << value1 << " >= " << value2; if (comment) { std::cerr << " ("; // vfprintf(stderr, comment, argp); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Same as testLt above, but comment is 0. template <typename T1, typename T2> bool testLt(const char *file, int line, const T1 &value1, const char *expression1, const T2 &value2, const char *expression2) { return testLt(file, line, value1, expression1, value2, expression2, 0); } // Called by the macro SEQAN_ASSERT. // // Test that the given argument evaluates to true. template <typename T> bool testTrue(const char *file, int line, const T &value_, const char *expression_, const char *comment, ...) { if (!(value_)) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression_ << " should be true but was " << (value_); if (comment) { std::cerr << " ("; va_list args; va_start(args, comment); // vfprintf(stderr, comment, args); va_end(args); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Similar to testTrue above, but accepts a va_list instead of variadic // parameters. template <typename T> bool vtestTrue(const char *file, int line, const T &value_, const char *expression_, const char *comment, va_list argp) { if (!(value_)) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression_ << " should be true but was " << (value_); if (comment) { std::cerr << " ("; // vfprintf(stderr, comment, argp); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Same as testTrue above, but comment will automatically be set to 0. template <typename T> bool testTrue(const char *file, int line, const T &value_, const char *expression_) { return testTrue(file, line, value_, expression_, 0); } // Called by the macro SEQAN_ASSERT. // // Test that the given argument evaluates to false. template <typename T> bool testFalse(const char *file, int line, const T &value_, const char *expression_, const char *comment, ...) { if (value_) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression_ << " should be false but was " << (value_); if (comment) { std::cerr << " ("; va_list args; va_start(args, comment); // vfprintf(stderr, comment, args); va_end(args); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Similar to testFalse above, but accepts a va_list instead of variadic // parameters. template <typename T> bool vtestFalse(const char *file, int line, const T &value_, const char *expression_, const char *comment, va_list argp) { if (value_) { // Increase global error count. StaticData::thisTestOk() = false; StaticData::errorCount() += 1; // Print assertion failure text, with comment if any is given. std::cerr << file << ":" << line << " Assertion failed : " << expression_ << " should be false but was " << (value_); if (comment) { std::cerr << " ("; // vfprintf(stderr, comment, argp); std::cerr << ")"; } std::cerr << std::endl; return false; } return true; } // Same as testFalse above, but comment will automatically be set to 0. template <typename T> bool testFalse(const char *file, int line, const T &value_, const char *expression_) { return testFalse(file, line, value_, expression_, 0); } // Represents a check point in a file. struct CheckPoint { // Path to the file. const char *file; // Line in the file. unsigned int line; // Less-than comparator for check points. bool operator<(const CheckPoint &other) const { int c = strcmp(file, other.file); if (c < 0) return true; if (c == 0 && line < other.line) return true; return false; } }; // Wrapper for a set of check points. // TODO(holtgrew): Simply store the set? struct CheckPointStore { static ::std::set<CheckPoint> &data() { static ::std::set<CheckPoint> result; return result; } }; // Puts the given check point into the CheckPointStore's data. inline bool registerCheckPoint(unsigned int line, const char *file) { const char *file_name = strrchr(file, '/'); const char *file_name_2 = strrchr(file, '\\'); if (file_name_2 > file_name) file_name = file_name_2; if (!file_name) file_name = file; else ++file_name; CheckPoint cp = {file_name, line}; #ifdef _OMP #pragma omp critical #endif // #ifdef _OMP CheckPointStore::data().insert(cp); return true; } // Test whether the given check point exists in the check point // store. inline void testCheckPoint(const char *file, unsigned int line) { StaticData::totalCheckPointCount() += 1; CheckPoint cp = {file, line}; if (CheckPointStore::data().find(cp) == CheckPointStore::data().end()) { std::cerr << file << ":" << line << " -- Check point lost." << std::endl; return; } StaticData::foundCheckPointCount() += 1; } // Verify the check points for the given file. inline void verifyCheckPoints(const char *file) { char const* file_name = strrchr(file, '/'); char const* file_name_2 = strrchr(file, '\\'); if (file_name_2 > file_name) file_name = file_name_2; if (!file_name) file_name = file; else ++file_name; int len = strlen(StaticData::pathToRoot()) + strlen("/") + strlen(file) + 1; char *absolutePath = new char[len]; absolutePath[0] = '\0'; strcat(absolutePath, StaticData::pathToRoot()); strcat(absolutePath, "/"); strcat(absolutePath, file); FILE * fl = ::std::fopen(absolutePath, "r"); delete[] absolutePath; if (!fl) { std::cerr << file << " -- verifyCheckPoints could not find this file." << std::endl; } unsigned int line_number = 1; char buf[1<<16]; while (::std::fgets(buf, sizeof(buf), fl)) { if (::std::strstr(buf, "SEQAN_CHECKPOINT")) { testCheckPoint(file_name, line_number); } ++line_number; } ::std::fclose(fl); } #if SEQAN_ENABLE_TESTING // If in testing mode then raise an AssertionFailedException. inline void fail() { StaticData::thisTestOk() = false; printStackTrace(20); throw AssertionFailedException(); } #else // If not in testing mode then quit with an abort. inline void fail() { printStackTrace(20); // abort(); } #endif // #if SEQAN_ENABLE_TESTING } // namespace ClassTest /** .Macro.SEQAN_DEFINE_TEST ..summary:Expand to test definition. ..cat:Testing & Debugging ..signature:SEQAN_DEFINE_TEST(test_name) ..param.test_name:The name of the test. ..remarks:This macro expands to the definition of a $void$ function with $SEQAN_TEST_ + test_name$ as its name. ..example.code: SEQAN_DEFINE_TEST(test_name) { SEQAN_ASSERT_LT(0, 3); } ..see:Macro.SEQAN_SKIP_TEST ..see:Macro.SEQAN_CALL_TEST ..see:Macro.SEQAN_BEGIN_TESTSUITE ..see:Macro.SEQAN_END_TESTSUITE */ // This macro expands to function header for one test. #define SEQAN_DEFINE_TEST(test_name) \ template <bool speed_up_dummy_to_prevent_compilation_of_unused_tests_> void SEQAN_TEST_ ## test_name () /** .Macro.SEQAN_BEGIN_TESTSUITE ..summary:Expand to a test suite beginning. ..cat:Testing & Debugging ..signature:SEQAN_BEGIN_TESTSUITE(name) ..param.name:The name of the test suite. ..remarks:This macro expands to a $main()$ function and some initialization code that sets up the test system. ..example.code: #include <seqan/basic.h> SEQAN_BEGIN_TESTSUITE(test_foo) { SEQAN_CALL_TEST(test_foo_my_test); } SEQAN_END_TESTSUITE ..see:Macro.SEQAN_SKIP_TEST ..see:Macro.SEQAN_DEFINE_TEST ..see:Macro.SEQAN_CALL_TEST ..see:Macro.SEQAN_END_TESTSUITE */ #if SEQAN_ENABLE_TESTING // This macro expands to startup code for a test file. #define SEQAN_BEGIN_TESTSUITE(suite_name) \ int main(int argc, char **argv) { \ (void) argc; \ ::seqan::ClassTest::beginTestSuite(#suite_name, argv[0]); /** .Macro.SEQAN_END_TESTSUITE ..summary:Expand to a test suite ending. ..cat:Testing & Debugging ..signature:SEQAN_END_TESTSUITE ..remarks:This macro expands to finalization code for a test suite. ..example.code: #include <seqan/basic.h> SEQAN_BEGIN_TESTSUITE(test_foo) { SEQAN_CALL_TEST(test_foo_my_test); } SEQAN_END_TESTSUITE ..see:Macro.SEQAN_SKIP_TEST ..see:Macro.SEQAN_DEFINE_TEST ..see:Macro.SEQAN_CALL_TEST ..see:Macro.SEQAN_BEGIN_TESTSUITE */ // This macro expands to shutdown code for a test file. #define SEQAN_END_TESTSUITE \ return ::seqan::ClassTest::endTestSuite(); \ } /** .Macro.SEQAN_CALL_TEST ..summary:Expand to calling a test. ..cat:Testing & Debugging ..signature:SEQAN_CALL_TEST(test_name) ..param.test_name:The name of the test. ..remarks:This expects the test to be defined with @Macro.SEQAN_DEFINE_TEST@. This macro will expand to code that calls the code inside a try/catch block. Use this macro within a test suite, only. ..example.code: // Within a test suite. SEQAN_CALL_TEST(test_name); ..see:Macro.SEQAN_SKIP_TEST ..see:Macro.SEQAN_DEFINE_TEST ..see:Macro.SEQAN_BEGIN_TESTSUITE ..see:Macro.SEQAN_END_TESTSUITE */ // This macro expands to code to call a given test. #define SEQAN_CALL_TEST(test_name) \ do { \ ::seqan::ClassTest::beginTest(#test_name); \ try { \ SEQAN_TEST_ ## test_name<true>(); \ } catch(::seqan::ClassTest::AssertionFailedException e) { \ /* Swallow exception, go on with next test. */ \ (void) e; /* Get rid of unused variable warning. */ \ } \ ::seqan::ClassTest::endTest(); \ } while (false) /** .Macro.SEQAN_SKIP_TEST ..cat:Testing & Debugging ..summary:Force the test to return without failing and mark it as skipped. ..signature:SEQAN_SKIP_TEST ..example.code: SEQAN_DEFINE_TEST(test_skipped) { SEQAN_SKIP_TEST; } ..see:Macro.SEQAN_DEFINE_TEST ..see:Macro.SEQAN_CALL_TEST ..see:Macro.SEQAN_BEGIN_TESTSUITE ..see:Macro.SEQAN_END_TESTSUITE */ // This macro returns from the current function and logs a "skipped" // event for the current test. #define SEQAN_SKIP_TEST \ do { \ ::seqan::ClassTest::skipCurrentTest(); \ return; \ } while (false) #endif // #if SEQAN_ENABLE_TESTING // variadic macros are not supported by VS 2003 and before #if !defined(_MSC_VER) || (_MSC_VER >= 1400) #if SEQAN_ENABLE_DEBUG /** .Macro.SEQAN_ASSERT ..cat:Assertions ..summary:Test that the given expression can be coerced to $true$. ..signature:SEQAN_ASSERT(expression) ..signature:SEQAN_ASSERT_MSG(expression, message[, parameters]) ..remarks:The main advantage of this macro is that it prints the values of its argument on failures. Note that the $operator<<$ to the type of $std::cerr$ has to be defined for the type of both expression parameters. Otherwise, simply use the equivalent @Macro.SEQAN_ASSERT@ call. ..remarks:See @Macro.SEQAN_CHECK@ and @Macro.SEQAN_FAIL@ for (conditionally) aborting your program regardless of debug settings. ..example.code: SEQAN_ASSERT(0); // will fail SEQAN_ASSERT(1); // will run through SEQAN_ASSERT_MSG(0, "message %d", 2); // Will fail with message. ..see:Macro.SEQAN_ASSERT_NOT ..see:Macro.SEQAN_ASSERT_EQ ..see:Macro.SEQAN_ASSERT_NEQ ..see:Macro.SEQAN_ASSERT_LEQ ..see:Macro.SEQAN_ASSERT_GEQ ..see:Macro.SEQAN_ASSERT_LT ..see:Macro.SEQAN_ASSERT_GT ..see:Macro.SEQAN_ASSERT_IN_DELTA ..see:Macro.SEQAN_CHECK ..see:Macro.SEQAN_FAIL .Macro.SEQAN_ASSERT_NOT ..cat:Assertions ..summary:Test that the given expression can be coerced to $false$. ..signature:SEQAN_ASSERT(expression) ..signature:SEQAN_ASSERT_MSG(expression, message[, parameters]) ..remarks:The main advantage of this macro is that it prints the values of its argument on failures. Note that the $operator<<$ to the type of $std::cerr$ has to be defined for the type of both expression parameters. Otherwise, simply use the equivalent @Macro.SEQAN_ASSERT@ call. ..remarks:See @Macro.SEQAN_CHECK@ and @Macro.SEQAN_FAIL@ for (conditionally) aborting your program regardless of debug settings. ..example.code: SEQAN_ASSERT_NOT(0); // will run through SEQAN_ASSERT_NOT(1); // will fail SEQAN_ASSERT_NOT_MSG(0, "msg %s", "test"); // will fail with message ..see:Macro.SEQAN_ASSERT ..see:Macro.SEQAN_ASSERT_EQ ..see:Macro.SEQAN_ASSERT_NEQ ..see:Macro.SEQAN_ASSERT_LEQ ..see:Macro.SEQAN_ASSERT_GEQ ..see:Macro.SEQAN_ASSERT_LT ..see:Macro.SEQAN_ASSERT_GT ..see:Macro.SEQAN_ASSERT_IN_DELTA ..see:Macro.SEQAN_CHECK ..see:Macro.SEQAN_FAIL .Macro.SEQAN_ASSERT_EQ ..cat:Assertions ..summary:Test that two given expressions are equal, as defined by the matching call to the $operator=(,)$. ..signature:SEQAN_ASSERT_EQ(expression1, expression2) ..signature:SEQAN_ASSERT_EQ_MSG(expression1, expression2, comment[, parameters]) ..remarks:The main advantage of this macro is that it prints the values of its argument on failures. Note that the $operator<<$ to the type of $std::cerr$ has to be defined for the type of both expression parameters. Otherwise, simply use the equivalent @Macro.SEQAN_ASSERT@ call. ..remarks:See @Macro.SEQAN_CHECK@ and @Macro.SEQAN_FAIL@ for (conditionally) aborting your program regardless of debug settings. ..example.code: SEQAN_ASSERT_EQ(0, false); // will run through SEQAN_ASSERT_EQ(1, false); // will fail SEQAN_ASSERT_EQ(1, "foo"); // will not compile SEQAN_ASSERT_EQ_MSG(1, false, "msg"); // will fail with message ..see:Macro.SEQAN_ASSERT ..see:Macro.SEQAN_ASSERT_NOT ..see:Macro.SEQAN_ASSERT_NEQ ..see:Macro.SEQAN_ASSERT_LEQ ..see:Macro.SEQAN_ASSERT_GEQ ..see:Macro.SEQAN_ASSERT_LT ..see:Macro.SEQAN_ASSERT_GT ..see:Macro.SEQAN_ASSERT_IN_DELTA ..see:Macro.SEQAN_CHECK ..see:Macro.SEQAN_FAIL .Macro.SEQAN_ASSERT_NEQ ..cat:Assertions ..summary:Test that two given expressions are not equal, as defined by the matching call to the $operator!=(,)$. ..signature:SEQAN_ASSERT_NEQ(expression) ..signature:SEQAN_ASSERT_NEQ_MSG(expression, message[, parameters]) ..remarks:The main advantage of this macro is that it prints the values of its argument on failures. Note that the $operator<<$ to the type of $std::cerr$ has to be defined for the type of both expression parameters. Otherwise, simply use the equivalent @Macro.SEQAN_ASSERT@ call. ..remarks:See @Macro.SEQAN_CHECK@ and @Macro.SEQAN_FAIL@ for (conditionally) aborting your program regardless of debug settings. ..example.code: SEQAN_ASSERT_NEQ(0, false); // will fail SEQAN_ASSERT_NEQ(1, false); // will run through SEQAN_ASSERT_NEQ(1, "foo"); // will not compile SEQAN_ASSERT_NEQ_MSG(1, false, "msg"); // will fail with message ..see:Macro.SEQAN_ASSERT ..see:Macro.SEQAN_ASSERT_NOT ..see:Macro.SEQAN_ASSERT_EQ ..see:Macro.SEQAN_ASSERT_LEQ ..see:Macro.SEQAN_ASSERT_GEQ ..see:Macro.SEQAN_ASSERT_LT ..see:Macro.SEQAN_ASSERT_GT ..see:Macro.SEQAN_ASSERT_IN_DELTA ..see:Macro.SEQAN_CHECK ..see:Macro.SEQAN_FAIL .Macro.SEQAN_ASSERT_LT ..cat:Assertions ..summary:Test that the two given expressions are in the less-than relation as defined by the matching call to operator<(,). ..signature:SEQAN_ASSERT_LT(expression1, expression2) ..signature:SEQAN_ASSERT_LT(expression1, expression2, comment[, parameters]) ..remarks:The main advantage of this macro is that it prints the values of its argument on failures. Note that the $operator<<$ to the type of $std::cerr$ has to be defined for the type of both expression parameters. Otherwise, simply use the equivalent @Macro.SEQAN_ASSERT@ call. ..remarks:See @Macro.SEQAN_CHECK@ and @Macro.SEQAN_FAIL@ for (conditionally) aborting your program regardless of debug settings. ..example.code: SEQAN_ASSERT_LT(0, 1); // will run through SEQAN_ASSERT_LT(1, 1); // will not run through SEQAN_ASSERT_LT_MSG(1, 1, "msg"); // will fail with message ..see:Macro.SEQAN_ASSERT ..see:Macro.SEQAN_ASSERT_NOT ..see:Macro.SEQAN_ASSERT_EQ ..see:Macro.SEQAN_ASSERT_NEQ ..see:Macro.SEQAN_ASSERT_LEQ ..see:Macro.SEQAN_ASSERT_GEQ ..see:Macro.SEQAN_ASSERT_GT ..see:Macro.SEQAN_ASSERT_IN_DELTA ..see:Macro.SEQAN_CHECK ..see:Macro.SEQAN_FAIL .Macro.SEQAN_ASSERT_LEQ ..cat:Assertions ..summary:Test that the two given expressions are in the less-than-or-equal relation as defined by the matching call to operator<=(,). ..signature:SEQAN_ASSERT_LEQ(expression1, expression2) ..signature:SEQAN_ASSERT_LEQ_MSG(expression1, expression2, comment[, parameters]) ..remarks:The main advantage of this macro is that it prints the values of its argument on failures. Note that the $operator<<$ to the type of $std::cerr$ has to be defined for the type of both expression parameters. Otherwise, simply use the equivalent @Macro.SEQAN_ASSERT@ call. ..remarks:See @Macro.SEQAN_CHECK@ and @Macro.SEQAN_FAIL@ for (conditionally) aborting your program regardless of debug settings. ..example.code: SEQAN_ASSERT_LEQ(1, 1); // will run through SEQAN_ASSERT_LEQ(1, 2); // will not run through SEQAN_ASSERT_LEQ_MSG(1, 2, "msg"); // will fail with message ..see:Macro.SEQAN_ASSERT ..see:Macro.SEQAN_ASSERT_NOT ..see:Macro.SEQAN_ASSERT_EQ ..see:Macro.SEQAN_ASSERT_NEQ ..see:Macro.SEQAN_ASSERT_GEQ ..see:Macro.SEQAN_ASSERT_LT ..see:Macro.SEQAN_ASSERT_GT ..see:Macro.SEQAN_ASSERT_IN_DELTA ..see:Macro.SEQAN_CHECK ..see:Macro.SEQAN_FAIL .Macro.SEQAN_ASSERT_GT ..cat:Assertions ..summary:Test that the two given expressions are in the greather-than relation as defined by the matching call to operator>(,). ..signature:SEQAN_ASSERT_GT(expression1, expression2) ..signature:SEQAN_ASSERT_GT_MSG(expression1, expression2, comment[, parameters]) ..remarks:The main advantage of this macro is that it prints the values of its argument on failures. Note that the $operator<<$ to the type of $std::cerr$ has to be defined for the type of both expression parameters. Otherwise, simply use the equivalent @Macro.SEQAN_ASSERT@ call. ..remarks:See @Macro.SEQAN_CHECK@ and @Macro.SEQAN_FAIL@ for (conditionally) aborting your program regardless of debug settings. ..example.code: SEQAN_ASSERT_GT(2, 1); // will run through SEQAN_ASSERT_GT(1, 1); // will not run through SEQAN_ASSERT_GT_MSG(1, 1, "msg"); // will fail with message ..see:Macro.SEQAN_ASSERT ..see:Macro.SEQAN_ASSERT_NOT ..see:Macro.SEQAN_ASSERT_EQ ..see:Macro.SEQAN_ASSERT_NEQ ..see:Macro.SEQAN_ASSERT_LEQ ..see:Macro.SEQAN_ASSERT_GEQ ..see:Macro.SEQAN_ASSERT_LT ..see:Macro.SEQAN_ASSERT_IN_DELTA ..see:Macro.SEQAN_CHECK ..see:Macro.SEQAN_FAIL .Macro.SEQAN_ASSERT_GEQ ..cat:Assertions ..summary:Test that the two given expressions are in the greater-than-or-equal relation as defined by the matching call to operator>=(,). ..signature:SEQAN_ASSERT_GEQ(expression1, expression2) ..signature:SEQAN_ASSERT_GEQ_MSG(expression1, expression2, comment[, parameters]) ..remarks:The main advantage of this macro is that it prints the values of its argument on failures. Note that the $operator<<$ to the type of $std::cerr$ has to be defined for the type of both expression parameters. Otherwise, simply use the equivalent @Macro.SEQAN_ASSERT@ call. ..remarks:See @Macro.SEQAN_CHECK@ and @Macro.SEQAN_FAIL@ for (conditionally) aborting your program regardless of debug settings. ..example.code: SEQAN_ASSERT_GEQ(1, 1); // will run through SEQAN_ASSERT_GEQ(0, 1); // will not run through SEQAN_ASSERT_GEQ_MSG(0, 1, "msg"); // will fail with message ..see:Macro.SEQAN_ASSERT ..see:Macro.SEQAN_ASSERT_NOT ..see:Macro.SEQAN_ASSERT_EQ ..see:Macro.SEQAN_ASSERT_NEQ ..see:Macro.SEQAN_ASSERT_LEQ ..see:Macro.SEQAN_ASSERT_LT ..see:Macro.SEQAN_ASSERT_GT ..see:Macro.SEQAN_ASSERT_IN_DELTA ..see:Macro.SEQAN_CHECK ..see:Macro.SEQAN_FAIL .Macro.SEQAN_ASSERT_IN_DELTA ..cat:Assertions ..summary:Test that the given expression can be coerced to $true$. ..signature:SEQAN_ASSERT_IN_DELTA(x, y, delta) ..signature:SEQAN_ASSERT_IN_DELTA_MSG(x, y, delta, comment[, parameters]) ..remarks:The main advantage of this macro is that it prints the values of its argument on failures. Note that the $operator<<$ to the type of $std::cerr$ has to be defined for the type of both expression parameters. Otherwise, simply use the equivalent @Macro.SEQAN_ASSERT@ call. ..remarks:See @Macro.SEQAN_CHECK@ and @Macro.SEQAN_FAIL@ for (conditionally) aborting your program regardless of debug settings. ..example.code: SEQAN_ASSERT_IN_DELTA(0, 0, 0.1); // will run through SEQAN_ASSERT_IN_DELTA(1, -2, 1); // will fail SEQAN_ASSERT_IN_DELTA(1, "foo"); // will not compile SEQAN_ASSERT_IN_DELTA_MSG(1, 0, 0.1, "msg"); // will fail with message ..see:Macro.SEQAN_ASSERT ..see:Macro.SEQAN_ASSERT_NOT ..see:Macro.SEQAN_ASSERT_EQ ..see:Macro.SEQAN_ASSERT_NEQ ..see:Macro.SEQAN_ASSERT_LEQ ..see:Macro.SEQAN_ASSERT_GEQ ..see:Macro.SEQAN_ASSERT_LT ..see:Macro.SEQAN_ASSERT_GT ..see:Macro.SEQAN_CHECK ..see:Macro.SEQAN_FAIL */ // Force a test failure. // // Usage: SEQAN_ASSERT_FAIL("Failed at position %d", pos); #define SEQAN_ASSERT_FAIL(...) \ do { \ ::seqan::ClassTest::forceFail(__FILE__, __LINE__, \ __VA_ARGS__); \ ::seqan::ClassTest::fail(); \ } while (false) // Equality assertion without a comment. // // Usage: SEQAN_ASSERT_EQ(4, 4); #define SEQAN_ASSERT_EQ(_arg1, _arg2) \ do { \ if (!::seqan::ClassTest::testEqual(__FILE__, __LINE__, \ (_arg1), #_arg1, \ (_arg2), #_arg2)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // Equality assertion with a comment. // // Usage: SEQAN_ASSERT_EQ(4, 4); #define SEQAN_ASSERT_EQ_MSG(_arg1, _arg2, ...) \ do { \ if (!::seqan::ClassTest::testEqual(__FILE__, __LINE__, \ (_arg1), #_arg1, \ (_arg2), #_arg2, \ __VA_ARGS__)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // In-delta-environment assertion without a comment. // // Usage: SEQAN_ASSERT_IN_DELTA(4.1, 4, 0.1); #define SEQAN_ASSERT_IN_DELTA(_arg1, _arg2, _arg3) \ do { \ if (!::seqan::ClassTest::testInDelta(__FILE__, __LINE__, \ (_arg1), #_arg1, \ (_arg2), #_arg2, \ (_arg3), #_arg3)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // In-delta-environment assertion witha comment. // // Usage: SEQAN_ASSERT_IN_DELTA_MSG(4.1, 4, 0.1, "3.9 <= 4.1 <= 4.1"); #define SEQAN_ASSERT_IN_DELTA_MSG(_arg1, _arg2, _arg3, ...) \ do { \ if (!::seqan::ClassTest::testInDelta(__FILE__, __LINE__, \ (_arg1), #_arg1, \ (_arg2), #_arg2, \ (_arg3), #_arg3, \ __VA_ARGS__)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // Inequality assertion without a comment. // // Usage: SEQAN_ASSERT_NEQ(4, 5); #define SEQAN_ASSERT_NEQ(_arg1, _arg2) \ do { \ if (!::seqan::ClassTest::testNotEqual(__FILE__, __LINE__, \ (_arg1), #_arg1, \ (_arg2), #_arg2)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // Inequality assertion with a comment. // // Usage: SEQAN_ASSERT_NEQ(4, 5); #define SEQAN_ASSERT_NEQ_MSG(_arg1, _arg2, ...) \ do { \ if (!::seqan::ClassTest::testNotEqual(__FILE__, __LINE__, \ (_arg1), #_arg1, \ (_arg2), #_arg2, \ __VA_ARGS__)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // Less-than-or-equal assertion without a comment. #define SEQAN_ASSERT_LEQ(_arg1, _arg2) \ do { \ if (!::seqan::ClassTest::testLeq(__FILE__, __LINE__, \ (_arg1), #_arg1, \ (_arg2), #_arg2)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // Less-than-or-equal assertion with a comment. #define SEQAN_ASSERT_LEQ_MSG(_arg1, _arg2, ...) \ do { \ if (!::seqan::ClassTest::testLeq(__FILE__, __LINE__, \ (_arg1), #_arg1, \ (_arg2), #_arg2, \ __VA_ARGS__)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // Less-than assertion without a comment. #define SEQAN_ASSERT_LT(_arg1, _arg2) \ do { \ if (!::seqan::ClassTest::testLt(__FILE__, __LINE__, \ (_arg1), #_arg1, \ (_arg2), #_arg2)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // Less-than assertion with a comment. #define SEQAN_ASSERT_LT_MSG(_arg1, _arg2, ...) \ do { \ if (!::seqan::ClassTest::testLt(__FILE__, __LINE__, \ (_arg1), #_arg1, \ (_arg2), #_arg2, \ __VA_ARGS__)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // Greater-than-or-equal assertion without a comment. #define SEQAN_ASSERT_GEQ(_arg1, _arg2) \ do { \ if (!::seqan::ClassTest::testGeq(__FILE__, __LINE__, \ (_arg1), #_arg1, \ (_arg2), #_arg2)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // Greater-than-or-equal assertion with a comment. #define SEQAN_ASSERT_GEQ_MSG(_arg1, _arg2, ...) \ do { \ if (!::seqan::ClassTest::testGeq(__FILE__, __LINE__, \ (_arg1), #_arg1, \ (_arg2), #_arg2, \ __VA_ARGS__)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // Greater-than assertion without a comment. #define SEQAN_ASSERT_GT(_arg1, _arg2) \ do { \ if (!::seqan::ClassTest::testGt(__FILE__, __LINE__, \ (_arg1), #_arg1, \ (_arg2), #_arg2)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // Greater-than assertion with a comment. #define SEQAN_ASSERT_GT_MSG(_arg1, _arg2, ...) \ do { \ if (!::seqan::ClassTest::testGt(__FILE__, __LINE__, \ (_arg1), #_arg1, \ (_arg2), #_arg2, \ __VA_ARGS__)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // TODO(holtgrew): Rename to SEQAN_ASSERT once that name is free.; // Trueness assertion with a comment. // // Usage: SEQAN_ASSERT(false); #define SEQAN_ASSERT(_arg1) \ do { \ if (!::seqan::ClassTest::testTrue(__FILE__, __LINE__, \ (_arg1), #_arg1)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // TODO(holtgrew): Rename to SEQAN_ASSERT once that name is free.; // Trueness assertion with a comment. #define SEQAN_ASSERT_MSG(_arg1, ...) \ do { \ if (!::seqan::ClassTest::testTrue(__FILE__, __LINE__, \ (_arg1), #_arg1, \ __VA_ARGS__)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // Falseness assertion without a comment. // // Usage: SEQAN_ASSERT_NOT(false); #define SEQAN_ASSERT_NOT(_arg1) \ do { \ if (!::seqan::ClassTest::testFalse(__FILE__, __LINE__, \ (_arg1), #_arg1)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) // Falseness assertion with a comment. #define SEQAN_ASSERT_NOT_MSG(_arg1, ...) \ do { \ if (!::seqan::ClassTest::testFalse(__FILE__, __LINE__, \ (_arg1), #_arg1, \ __VA_ARGS__)) { \ ::seqan::ClassTest::fail(); \ } \ } while (false) #else // #if SEQAN_ENABLE_DEBUG #define SEQAN_ASSERT_EQ(_arg1, _arg2) do {} while (false) #define SEQAN_ASSERT_EQ_MSG(_arg1, _arg2, ...) do {} while (false) #define SEQAN_ASSERT_NEQ(_arg1, _arg2) do {} while (false) #define SEQAN_ASSERT_NEQ_MSG(_arg1, _arg2, ...) do {} while (false) #define SEQAN_ASSERT_LEQ(_arg1, _arg2) do {} while (false) #define SEQAN_ASSERT_LEQ_MSG(_arg1, _arg2, ...) do {} while (false) #define SEQAN_ASSERT_LT(_arg1, _arg2) do {} while (false) #define SEQAN_ASSERT_LT_MSG(_arg1, _arg2, ...) do {} while (false) #define SEQAN_ASSERT_GEQ(_arg1, _arg2) do {} while (false) #define SEQAN_ASSERT_GEQ_MSG(_arg1, _arg2, ...) do {} while (false) #define SEQAN_ASSERT_GT(_arg1, _arg2) do {} while (false) #define SEQAN_ASSERT_GT_MSG(_arg1, _arg2, ...) do {} while (false) #define SEQAN_ASSERT(_arg1) do {} while (false) #define SEQAN_ASSERT_MSG(_arg1, ...) do {} while (false) #define SEQAN_ASSERT_NOT(_arg1) do {} while (false) #define SEQAN_ASSERT_NOT_MSG(_arg1, ...) do {} while (false) #define SEQAN_ASSERT_FAIL(...) do {} while (false) #endif // #if SEQAN_ENABLE_DEBUG #else // no variadic macros #if SEQAN_ENABLE_DEBUG inline void SEQAN_ASSERT_FAIL(const char *comment, ...) { va_list args; va_start(args, comment); ::seqan::ClassTest::vforceFail("", 0, comment, args); ::seqan::ClassTest::fail(); va_end(args); } template <typename T1, typename T2, typename T3> void SEQAN_ASSERT_IN_DELTA(T1 const &_arg1, T2 const &_arg2, T3 const &_arg3) { if (!::seqan::ClassTest::testInDelta("", 0, _arg1, "", _arg2, "", _arg3, "")) ::seqan::ClassTest::fail(); } template <typename T1, typename T2, typename T3> void SEQAN_ASSERT_IN_DELTA_MSG(T1 const &_arg1, T2 const &_arg2, T3 const &_arg3, const char *comment, ...) { va_list args; va_start(args, comment); if (!::seqan::ClassTest::vtestInDelta("", 0, _arg1, "", _arg2, "", _arg3, "", comment, args)) ::seqan::ClassTest::fail(); va_end(args); } template <typename T1, typename T2> void SEQAN_ASSERT_EQ(T1 const &_arg1, T2 const &_arg2) { if (!::seqan::ClassTest::testEqual("", 0, _arg1, "", _arg2, "")) ::seqan::ClassTest::fail(); } template <typename T1, typename T2> void SEQAN_ASSERT_EQ_MSG(T1 const &_arg1, T2 const &_arg2, const char *comment, ...) { va_list args; va_start(args, comment); if (!::seqan::ClassTest::vtestEqual("", 0, _arg1, "", _arg2, "", comment, args)) ::seqan::ClassTest::fail(); va_end(args); } template <typename T1, typename T2> void SEQAN_ASSERT_NEQ(T1 const &_arg1, T2 const &_arg2) { if (!::seqan::ClassTest::testNotEqual("", _arg1, "", _arg2, "")) ::seqan::ClassTest::fail(); } template <typename T1, typename T2> void SEQAN_ASSERT_NEQ_MSG(T1 const &_arg1, T2 const &_arg2, const char *comment, ...) { va_list args; va_start(args, comment); if (!::seqan::ClassTest::vtestNotEqual("", _arg1, "", _arg2, "", comment, args)) ::seqan::ClassTest::fail(); va_end(args); } template <typename T1, typename T2> void SEQAN_ASSERT_LEQ(T1 const &_arg1, T2 const &_arg2) { if (!::seqan::ClassTest::testLeq("", 0, _arg1, "", _arg2, "")) ::seqan::ClassTest::fail(); } template <typename T1, typename T2> void SEQAN_ASSERT_LEQ_MSG(T1 const &_arg1, T2 const &_arg2, const char *comment, ...) { va_list args; va_start(args, comment); if (!::seqan::ClassTest::vtestLeq("", 0, _arg1, "", _arg2, "", comment, args)) ::seqan::ClassTest::fail(); va_end(args); } template <typename T1, typename T2> void SEQAN_ASSERT_LT(T1 const &_arg1, T2 const &_arg2) { if (!::seqan::ClassTest::testLt("", 0, _arg1, "", _arg2, "")) ::seqan::ClassTest::fail(); } template <typename T1, typename T2> void SEQAN_ASSERT_LT_MSG(T1 const &_arg1, T2 const &_arg2, const char *comment, ...) { va_list args; va_start(args, comment); if (!::seqan::ClassTest::vtestLt("", 0, _arg1, "", _arg2, "", comment, args)) ::seqan::ClassTest::fail(); va_end(args); } template <typename T1, typename T2> void SEQAN_ASSERT_GEQ(T1 const &_arg1, T2 const &_arg2) { if (!::seqan::ClassTest::testGeq("", 0, _arg1, "", _arg2, "")) ::seqan::ClassTest::fail(); } template <typename T1, typename T2> void SEQAN_ASSERT_GEQ_MSG(T1 const &_arg1, T2 const &_arg2, const char *comment, ...) { va_list args; va_start(args, comment); if (!::seqan::ClassTest::vtestGeq("", 0, _arg1, "", _arg2, "", comment, args)) ::seqan::ClassTest::fail(); va_end(args); } template <typename T1, typename T2> void SEQAN_ASSERT_GT(T1 const &_arg1, T2 const &_arg2) { if (!::seqan::ClassTest::testGt("", 0, _arg1, "", _arg2, "")) ::seqan::ClassTest::fail(); } template <typename T1, typename T2> void SEQAN_ASSERT_GT_MSG(T1 const &_arg1, T2 const &_arg2, const char *comment, ...) { va_list args; va_start(args, comment); if (!::seqan::ClassTest::vtestGt("", 0, _arg1, "", _arg2, "", comment, args)) ::seqan::ClassTest::fail(); va_end(args); } template <typename T1> void SEQAN_ASSERT(T1 const &_arg1) { if (!::seqan::ClassTest::testTrue("", 0, _arg1, "")) ::seqan::ClassTest::fail(); } template <typename T1> void SEQAN_ASSERT_MSG(T1 const &_arg1, const char *comment, ...) { va_list args; va_start(args, comment); if (!::seqan::ClassTest::vtestTrue("", 0, _arg1, "", comment, args)) ::seqan::ClassTest::fail(); va_end(args); } template <typename T1> void SEQAN_ASSERT_NOT(T1 const &_arg1) { if (!::seqan::ClassTest::testFalse("", 0, _arg1, "")) ::seqan::ClassTest::fail(); } template <typename T1> void SEQAN_ASSERT_NOT_MSG(T1 const &_arg1, const char *comment, ...) { va_list args; va_start(args, comment); if (!::seqan::ClassTest::vtestFalse("", 0, _arg1, "", comment, args)) ::seqan::ClassTest::fail(); va_end(args); } #else // #if SEQAN_ENABLE_DEBUG inline void SEQAN_ASSERT_FAIL(const char *comment, ...) {} template <typename T1, typename T2, typename T3> void SEQAN_ASSERT_IN_DELTA(T1 const &_arg1, T2 const &_arg2, T3 const &_arg3) {} template <typename T1, typename T2, typename T3> void SEQAN_ASSERT_IN_DELTA_MSG(T1 const &_arg1, T2 const &_arg2, T3 const &_arg3, const char *comment, ...) {} template <typename T1, typename T2> void SEQAN_ASSERT_EQ(T1 const &_arg1, T2 const &_arg2) {} template <typename T1, typename T2> void SEQAN_ASSERT_EQ_MSG(T1 const &_arg1, T2 const &_arg2, const char *comment, ...) {} template <typename T1, typename T2> void SEQAN_ASSERT_NEQ(T1 const &_arg1, T2 const &_arg2) {} template <typename T1, typename T2> void SEQAN_ASSERT_NEQ_MSG(T1 const &_arg1, T2 const &_arg2, const char *comment, ...) {} template <typename T1, typename T2> void SEQAN_ASSERT_LEQ(T1 const &_arg1, T2 const &_arg2) {} template <typename T1, typename T2> void SEQAN_ASSERT_LEQ_MSG(T1 const &_arg1, T2 const &_arg2, const char *comment, ...) {} template <typename T1, typename T2> void SEQAN_ASSERT_LT(T1 const &_arg1, T2 const &_arg2) {} template <typename T1, typename T2> void SEQAN_ASSERT_LT_MSG(T1 const &_arg1, T2 const &_arg2, const char *comment, ...) {} template <typename T1, typename T2> void SEQAN_ASSERT_GEQ(T1 const &_arg1, T2 const &_arg2) {} template <typename T1, typename T2> void SEQAN_ASSERT_GEQ_MSG(T1 const &_arg1, T2 const &_arg2, const char *comment, ...) {} template <typename T1, typename T2> void SEQAN_ASSERT_GT(T1 const &_arg1, T2 const &_arg2) {} template <typename T1, typename T2> void SEQAN_ASSERT_GT_MSG(T1 const &_arg1, T2 const &_arg2, const char *comment, ...) {} template <typename T1> void SEQAN_ASSERT(T1 const &_arg1) {} template <typename T1> void SEQAN_ASSERT_MSG(T1 const &_arg1, const char *comment, ...) {} template <typename T1> void SEQAN_ASSERT_NOT(T1 const &_arg1) {} template <typename T1> void SEQAN_ASSERT_NOT_MSG(T1 const &_arg1, const char *comment, ...) {} #endif // #if SEQAN_ENABLE_DEBUG #endif // no variadic macros // Returns a string (of type char*) with the path to the called binary. // // Use this to locate files relative to the test binary. #define SEQAN_PROGRAM_PATH \ ::seqan::ClassTest::StaticData::basePath() // TODO(holtgrew): Subject to change wiht restructuring. /** .Macro.SEQAN_PATH_TO_ROOT ..cat:Testing & Debugging ..summary:Return path to the checkout root directory (i.e. containing core/extras). ..returns:$char const *$, string with the path to the parent directory of the tests directory. ..signature:SEQAN_PATH_TO_ROOT() ..remarks:The pointed to string is initialized on program startup by the code generated by @Macro.SEQAN_BEGIN_TESTSUITE@. ..example.code: const char *p = SEQAN_PATH_TO_ROOT); char buffer[1000]; strcpy(buffer, p); strcat(buffer, "/tests/files/example.txt"); FILE *f = fopen(buffer, "w"); fprintf(f, "Test Data"); fclose(f); ..see:Macro.SEQAN_TEMP_FILENAME */ // Returns a const char * string with the path to the projects directory. #define SEQAN_PATH_TO_ROOT() \ ::seqan::ClassTest::StaticData::pathToRoot() // Returns the POSIX int file handle to an open file. // TODO(holtgrewe): Uncomment if openTempFile has been implemented. // #define SEQAN_OPEN_TEMP_FILE() (::seqan::ClassTest::openTempFile()) /** .Macro.SEQAN_TEMP_FILENAME ..cat:Testing & Debugging ..summary:Generates the name to a temporary file. ..returns:$char const *$, string with the path to a temporary file. ..signature:SEQAN_TEMP_FILENAME() ..remarks:The pointed to string is stored in a buffer and is overwritten by the next call to this macro. Copy it out if you need it. ..example.code: const char *p = SEQAN_TEMP_FILENAME(); buffer char tempFilename[1000]; strcpy(tempFilename, p); FILE *f = fopen(tempFilename, "w"); fprintf(f, "Test Data"); fclose(f); ..see:Macro.SEQAN_PATH_TO_ROOT */ // Returns a temporary filename. #define SEQAN_TEMP_FILENAME() (::seqan::ClassTest::tempFileName()) /** .Macro.SEQAN_VERIFY_CHECKPOINTS ..cat:Testing & Debugging ..summary:Verify check points for the given file name. ..signature:SEQAN_VERIFY_CHECKPOINTS(path) ..param.path:Path to the file to verify check points for. Relative to parent directory of tests. ..example.code: SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/basic_alphabet.h"); ..see:Macro.SEQAN_CHECKPOINT .Macro.SEQAN_CHECKPOINT ..cat:Testing & Debugging ..summary:Generate a check point. ..signature:SEQAN_CHECKPOINT ..remarks:Whever the code executes the instructions generated by this macro, the check point for this line will be set in global testing state. Use @Macro.SEQAN_VERIFY_CHECKPOINTS@ to verify whether all checkpoints have been reached in a file up to this point. SEQAN_CHECKPOINT; ..see:Macro.SEQAN_VERIFY_CHECKPOINTS */ #if SEQAN_ENABLE_CHECKPOINTS // Create a check point at the point where the macro is placed. // TODO(holtgrew): Should be called SEQAN_CHECK_POINT to be consistent. #define SEQAN_CHECKPOINT \ ::seqan::ClassTest::registerCheckPoint(__LINE__, __FILE__); // Call the check point verification code for the given file. #define SEQAN_VERIFY_CHECKPOINTS(filename) \ ::seqan::ClassTest::verifyCheckPoints(filename) #else // #if SEQAN_ENABLE_CHECKPOINTS #define SEQAN_CHECKPOINT // If checkpoints are to be verified if testing is disabled then print // a warning. //#define SEQAN_VERIFY_CHECKPOINTS(filename) \ // do { \ // fprintf(stderr, ("WARNING: Check point verification is " \ // "disabled. Trying to verify %s from %s:%d.\n"), \ // filename, __FILE__, __LINE__); \ // } while(false) #endif // #if SEQAN_ENABLE_CHECKPOINTS #if !SEQAN_ENABLE_TESTING #define SEQAN_BEGIN_TESTSUITE(suite_name) \ int main(int argc, char **argv) { \ (void) argc; \ (void) argv; \ // fprintf(stderr, "Warning: SEQAN_ENABLE_TESTING is wrong and you used the macro SEQAN_BEGIN_TESTSUITE!\n"); #define SEQAN_END_TESTSUITE return 0; \ } #define SEQAN_CALL_TEST(test_name) do { SEQAN_TEST_ ## test_name(); } while (false) #define SEQAN_SKIP_TEST do {} while (false) #endif // #if !SEQAN_ENABLE_TESTING } // namespace seqan #endif // SEQAN_CORE_INCLUDE_SEQAN_BASIC_DEBUG_TEST_SYSTEM_H_
GB_unop__identity_uint64_fp32.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 Generated/ folder, do not edit it (auto-generated). #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_uint64_fp32 // op(A') function: GB_unop_tran__identity_uint64_fp32 // C type: uint64_t // A type: float // cast: uint64_t cij = GB_cast_to_uint64_t ((double) (aij)) // unaryop: cij = aij #define GB_ATYPE \ float #define GB_CTYPE \ uint64_t // 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) \ uint64_t z = GB_cast_to_uint64_t ((double) (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint64_t z = GB_cast_to_uint64_t ((double) (aij)) ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT64 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_uint64_fp32 ( uint64_t *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *GB_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) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (float), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; uint64_t z = GB_cast_to_uint64_t ((double) (aij)) ; Cx [p] = z ; } #endif } 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] ; uint64_t z = GB_cast_to_uint64_t ((double) (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_uint64_fp32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_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__identity_uint32_uint8.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__identity_uint32_uint8 // op(A') function: GB_tran__identity_uint32_uint8 // C type: uint32_t // A type: uint8_t // cast: uint32_t cij = (uint32_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint8_t #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_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) \ uint32_t z = (uint32_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_IDENTITY || GxB_NO_UINT32 || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_uint32_uint8 ( uint32_t *Cx, // Cx and Ax may be aliased uint8_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__identity_uint32_uint8 ( 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
interaction.c
/* Copyright (C) 2015 Atsushi Togo */ /* All rights reserved. */ /* This file is part of phonopy. */ /* 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 phonopy project 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 HOLDER 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 <stdio.h> #include <stdlib.h> #include <phonoc_array.h> #include <phonoc_const.h> #include <phonon3_h/interaction.h> #include <phonon3_h/real_to_reciprocal.h> #include <phonon3_h/reciprocal_to_normal.h> #include <lapack_wrapper.h> static const int index_exchange[6][3] = {{0, 1, 2}, {2, 0, 1}, {1, 2, 0}, {2, 1, 0}, {0, 2, 1}, {1, 0, 2}}; static void real_to_normal(double *fc3_normal_squared, PHPYCONST int (*g_pos)[4], const int num_g_pos, const double *freqs0, const double *freqs1, const double *freqs2, const lapack_complex_double *eigvecs0, const lapack_complex_double *eigvecs1, const lapack_complex_double *eigvecs2, const double *fc3, const int is_compact_fc3, const double q[9], /* q0, q1, q2 */ const double *shortest_vectors, const int svecs_dims[3], const int *multiplicity, const double *masses, const int *p2s_map, const int *s2p_map, const int *band_indices, const int num_band0, const int num_band, const double cutoff_frequency, const int triplet_index, const int num_triplets, const int openmp_at_bands); static void real_to_normal_sym_q(double *fc3_normal_squared, PHPYCONST int (*g_pos)[4], const int num_g_pos, PHPYCONST double *freqs[3], PHPYCONST lapack_complex_double *eigvecs[3], const double *fc3, const int is_compact_fc3, const double q[9], /* q0, q1, q2 */ const double *shortest_vectors, const int svecs_dims[3], const int *multiplicity, const double *masses, const int *p2s_map, const int *s2p_map, const int *band_indices, const int num_band0, const int num_band, const double cutoff_frequency, const int triplet_index, const int num_triplets, const int openmp_at_bands); /* fc3_normal_squared[num_triplets, num_band0, num_band, num_band] */ void get_interaction(Darray *fc3_normal_squared, const char *g_zero, const Darray *frequencies, const lapack_complex_double *eigenvectors, const Iarray *triplets, const int *grid_address, const int *mesh, const double *fc3, const int is_compact_fc3, const double *shortest_vectors, const int svecs_dims[3], const int *multiplicity, const double *masses, const int *p2s_map, const int *s2p_map, const int *band_indices, const int symmetrize_fc3_q, const double cutoff_frequency) { int i, num_band, num_band0, num_band_prod, openmp_per_triplets; int j, k, l, jkl, num_g_pos; int (*g_pos)[4]; g_pos = NULL; num_band0 = fc3_normal_squared->dims[1]; num_band = frequencies->dims[1]; num_band_prod = num_band0 * num_band * num_band; if (triplets->dims[0] > num_band) { openmp_per_triplets = 1; } else { openmp_per_triplets = 0; } #pragma omp parallel for schedule(guided) private(j, k, l, jkl, num_g_pos, g_pos) if (openmp_per_triplets) for (i = 0; i < triplets->dims[0]; i++) { num_g_pos = 0; jkl = 0; g_pos = (int(*)[4])malloc(sizeof(int[4]) * num_band_prod); for (j = 0; j < num_band0; j++) { for (k = 0; k < num_band; k++) { for (l = 0; l < num_band; l++) { if (!g_zero[jkl + i * num_band_prod]) { g_pos[num_g_pos][0] = j; g_pos[num_g_pos][1] = k; g_pos[num_g_pos][2] = l; g_pos[num_g_pos][3] = jkl; num_g_pos++; } fc3_normal_squared->data[jkl + i * num_band_prod] = 0; jkl++; } } } get_interaction_at_triplet( fc3_normal_squared->data + i * num_band_prod, num_band0, num_band, g_pos, num_g_pos, frequencies->data, eigenvectors, triplets->data + i * 3, grid_address, mesh, fc3, is_compact_fc3, shortest_vectors, svecs_dims, multiplicity, masses, p2s_map, s2p_map, band_indices, symmetrize_fc3_q, cutoff_frequency, i, triplets->dims[0], 1 - openmp_per_triplets); free(g_pos); g_pos = NULL; } } void get_interaction_at_triplet(double *fc3_normal_squared, const int num_band0, const int num_band, PHPYCONST int (*g_pos)[4], const int num_g_pos, const double *frequencies, const lapack_complex_double *eigenvectors, const int *triplet, const int *grid_address, const int *mesh, const double *fc3, const int is_compact_fc3, const double *shortest_vectors, const int svecs_dims[3], const int *multiplicity, const double *masses, const int *p2s_map, const int *s2p_map, const int *band_indices, const int symmetrize_fc3_q, const double cutoff_frequency, const int triplet_index, /* only for print */ const int num_triplets, /* only for print */ const int openmp_at_bands) { int j, k; double *freqs[3]; lapack_complex_double *eigvecs[3]; double q[9]; for (j = 0; j < 3; j++) { for (k = 0; k < 3; k++) { q[j * 3 + k] = ((double)grid_address[triplet[j] * 3 + k]) / mesh[k]; } } if (symmetrize_fc3_q) { for (j = 0; j < 3; j++) { freqs[j] = (double*)malloc(sizeof(double) * num_band); eigvecs[j] = (lapack_complex_double*) malloc(sizeof(lapack_complex_double) * num_band * num_band); for (k = 0; k < num_band; k++) { freqs[j][k] = frequencies[triplet[j] * num_band + k]; } for (k = 0; k < num_band * num_band; k++) { eigvecs[j][k] = eigenvectors[triplet[j] * num_band * num_band + k]; } } real_to_normal_sym_q(fc3_normal_squared, g_pos, num_g_pos, freqs, eigvecs, fc3, is_compact_fc3, q, /* q0, q1, q2 */ shortest_vectors, svecs_dims, multiplicity, masses, p2s_map, s2p_map, band_indices, num_band0, num_band, cutoff_frequency, triplet_index, num_triplets, openmp_at_bands); for (j = 0; j < 3; j++) { free(freqs[j]); freqs[j] = NULL; free(eigvecs[j]); eigvecs[j] = NULL; } } else { real_to_normal(fc3_normal_squared, g_pos, num_g_pos, frequencies + triplet[0] * num_band, frequencies + triplet[1] * num_band, frequencies + triplet[2] * num_band, eigenvectors + triplet[0] * num_band * num_band, eigenvectors + triplet[1] * num_band * num_band, eigenvectors + triplet[2] * num_band * num_band, fc3, is_compact_fc3, q, /* q0, q1, q2 */ shortest_vectors, svecs_dims, multiplicity, masses, p2s_map, s2p_map, band_indices, num_band0, num_band, cutoff_frequency, triplet_index, num_triplets, openmp_at_bands); } } static void real_to_normal(double *fc3_normal_squared, PHPYCONST int (*g_pos)[4], const int num_g_pos, const double *freqs0, const double *freqs1, const double *freqs2, const lapack_complex_double *eigvecs0, const lapack_complex_double *eigvecs1, const lapack_complex_double *eigvecs2, const double *fc3, const int is_compact_fc3, const double q[9], /* q0, q1, q2 */ const double *shortest_vectors, const int svecs_dims[3], const int *multiplicity, const double *masses, const int *p2s_map, const int *s2p_map, const int *band_indices, const int num_band0, const int num_band, const double cutoff_frequency, const int triplet_index, const int num_triplets, const int openmp_at_bands) { int num_patom; lapack_complex_double *fc3_reciprocal; num_patom = num_band / 3; fc3_reciprocal = (lapack_complex_double*)malloc(sizeof(lapack_complex_double) * num_patom * num_patom * num_patom * 27); r2r_real_to_reciprocal(fc3_reciprocal, q, fc3, is_compact_fc3, shortest_vectors, svecs_dims, multiplicity, p2s_map, s2p_map, openmp_at_bands); #ifdef MEASURE_R2N if (openmp_at_bands && num_triplets > 0) { printf("At triplet %d/%d (# of bands=%d):\n", triplet_index, num_triplets, num_band0); } #endif reciprocal_to_normal_squared(fc3_normal_squared, g_pos, num_g_pos, fc3_reciprocal, freqs0, freqs1, freqs2, eigvecs0, eigvecs1, eigvecs2, masses, band_indices, num_band0, num_band, cutoff_frequency, openmp_at_bands); free(fc3_reciprocal); fc3_reciprocal = NULL; } static void real_to_normal_sym_q(double *fc3_normal_squared, PHPYCONST int (*g_pos)[4], const int num_g_pos, PHPYCONST double *freqs[3], PHPYCONST lapack_complex_double *eigvecs[3], const double *fc3, const int is_compact_fc3, const double q[9], /* q0, q1, q2 */ const double *shortest_vectors, const int svecs_dims[3], const int *multiplicity, const double *masses, const int *p2s_map, const int *s2p_map, const int *band_indices, const int num_band0, const int num_band, const double cutoff_frequency, const int triplet_index, const int num_triplets, const int openmp_at_bands) { int i, j, k, l; int band_ex[3]; double q_ex[9]; double *fc3_normal_squared_ex; fc3_normal_squared_ex = (double*)malloc(sizeof(double) * num_band * num_band * num_band); for (i = 0; i < num_band0 * num_band * num_band; i++) { fc3_normal_squared[i] = 0; } for (i = 0; i < 6; i++) { for (j = 0; j < 3; j ++) { for (k = 0; k < 3; k ++) { q_ex[j * 3 + k] = q[index_exchange[i][j] * 3 + k]; } } real_to_normal(fc3_normal_squared_ex, g_pos, num_g_pos, freqs[index_exchange[i][0]], freqs[index_exchange[i][1]], freqs[index_exchange[i][2]], eigvecs[index_exchange[i][0]], eigvecs[index_exchange[i][1]], eigvecs[index_exchange[i][2]], fc3, is_compact_fc3, q_ex, /* q0, q1, q2 */ shortest_vectors, svecs_dims, multiplicity, masses, p2s_map, s2p_map, band_indices, num_band, num_band, cutoff_frequency, triplet_index, num_triplets, openmp_at_bands); for (j = 0; j < num_band0; j++) { for (k = 0; k < num_band; k++) { for (l = 0; l < num_band; l++) { band_ex[0] = band_indices[j]; band_ex[1] = k; band_ex[2] = l; fc3_normal_squared[j * num_band * num_band + k * num_band + l] += fc3_normal_squared_ex[band_ex[index_exchange[i][0]] * num_band * num_band + band_ex[index_exchange[i][1]] * num_band + band_ex[index_exchange[i][2]]] / 6; } } } } free(fc3_normal_squared_ex); }
pr70680-1.c
/* PR middle-end/70680 */ int v; void f1 (void) { int i = 0; #pragma omp task default(shared) if(0) { #pragma omp simd for (i = 0; i < 100; i++) ; v = i; } if (i != 100) __builtin_abort (); } void f2 (void) { int i = 0; #pragma omp task default(shared) if(0) { #pragma omp simd for (i = 0; i < 100; i++) ; } if (i != 100) __builtin_abort (); } void f3 (void) { int i = 0; #pragma omp task default(shared) if(0) { #pragma omp simd linear(i: 1) for (i = 0; i < 100; i++) ; v = i; } if (i != 100) __builtin_abort (); } void f4 (void) { int i = 0; #pragma omp task default(shared) if(0) { #pragma omp simd linear(i: 1) for (i = 0; i < 100; i++) ; } if (i != 100) __builtin_abort (); } int main () { f1 (); if (v++ != 100) __builtin_abort (); f2 (); f3 (); if (v++ != 100) __builtin_abort (); f4 (); return 0; }
eigenvalues.c
#include "eigenvalues.h" #include <omp.h> #include <math.h> #include <assert.h> #include "mkl.h" inline double secularEquation(double lambda, double roh, double* z, double* D, int n, int* G) { double sum = 0; int i; #pragma omp parallel for default(shared) private(i) schedule(static) reduction(+:sum) for (i = 0; i < n; ++i) { if (G[i] == -1) sum += z[i]*z[i] / (D[i]-lambda); } return 1+roh*sum; } void computeEigenvalues(EVRepNode* node, MPIHandle mpiHandle) { // abbreviations int taskid = mpiHandle.taskid; int numtasks = mpiHandle.numtasks; int i; double* D = NULL; double* z = NULL; double* L = NULL; double* C = NULL; double* S = NULL; int* G = NULL; int* P = NULL; double roh; int n; if (taskid == node->taskid) { n = node->n; node->G = malloc(n * sizeof(int)); node->P = malloc(n * sizeof(int)); node->C = malloc(n * sizeof(double)); node->S = malloc(n * sizeof(double)); /* * Store eigenvalues in new array (do not overwrite D), since the elements in D are needed later on to compute the eigenvectors)S */ node->L = malloc(n * sizeof(double)); D = node->D; z = node->z; L = node->L; G = node->G; P = node->P; C = node->C; S = node->S; roh = node->beta * node->theta; node->numGR = 0; // initialize G properly, because later on I perform tests like, G[i] != -2, where G[i] has a random value at this time #pragma omp parallel for default(shared) private(i) schedule(static) for (i = 0; i < n; ++i) G[i] = -1; } // we don't use parallelism yet, so just return if other task if (taskid != node->taskid) { return; } assert(roh != 0); // copy and sort diagonal elements DiagElem* SD = malloc(n * sizeof(DiagElem)); double eps = 1e-6; // scan z for zero element and mark it in G with -2 #pragma omp parallel for default(shared) private(i) schedule(static) for (i = 0; i < n; i++) { if (fabs(z[i]) < eps) { //printf("Deflation happens (z) for index %d\n", i); G[i] = -2; } } #pragma omp parallel for default(shared) private(i) schedule(static) for (i = 0; i < n; ++i) { SD[i].e = D[i]; SD[i].i = i; } qsort(SD, n, sizeof(DiagElem), compareDiagElem); // calculate Givens rotation /* G is a vector that keeps track of Givens rotation for SD * Since SD has been sorted ascendingly, we should always make the off-diagonal * element that corresponds to the smaller diagonal element to be zero*/ int a, b; double c, s ,r, tmpi, tmpj; int nextNonZero; for (i = 0; i < n-1; i++){ if (G[SD[i].i] != -2) { // for those elements correspond to non-zero z nextNonZero = i + 1; while (G[SD[nextNonZero].i] == -2) { if (++nextNonZero == n) break; } if (nextNonZero >= n) { G[SD[i].i] = -1; continue; } if (fabs(SD[nextNonZero].e - SD[i].e) < 1e-5) { a = SD[i].i; b = SD[nextNonZero].i; r = sqrt(z[a] * z[a] + z[b] * z[b]); //printf("Deflation happens (d) for element %g (r=%g)\n", SD[i].i, r); c = z[b] / r; s = z[a] / r; C[node->numGR] = c; S[node->numGR] = s; G[SD[i].i] = SD[nextNonZero].i; z[SD[nextNonZero].i] = r; z[SD[i].i] = 0; P[node->numGR] = SD[i].i; tmpi = c * c * SD[i].e + s * s * SD[nextNonZero].e; tmpj = s * s * SD[i].e + c * c * SD[nextNonZero].e; SD[i].e = tmpi; SD[nextNonZero].e = tmpj; D[a] = tmpi; D[b] = tmpj; node->numGR++; } } } /* Note, if roh > 0, then the last eigenvalue is behind the last d_i * If roh < 0, then the first eigenvalue is before the first d_i */ // use norm of z as an approximation to find the first resp. last eigenvalue double normZ = cblas_dnrm2(n, z, 1); /****************** * Simple Bisection algorithm * ****************/ long maxIter = 10000; /* N ← 1 While N ≤ NMAX # limit iterations to prevent infinite loop c ← (a + b)/2 # new midpoint If f(c) = 0 or (b – a)/2 < TOL then # solution found Output(c) Stop EndIf N ← N + 1 # increment step counter If sign(f(c)) = sign(f(a)) then a ← c else b ← c # new interval EndWhile */ int boundaryHandled = 0; //#pragma omp parallel for default(shared) private(i) schedule(static) for (i = 0; i < n; ++i) { // for each eigenvalue double lambda = 0; double a, b; // interval boundaries double fa, flambda, fb; // function values int ind = SD[i].i; int prevNonZeroIdx; double di = SD[i].e; if (G[ind] != -1) { L[ind] = di; } else { // set initial interval if (roh < 0) { if (!boundaryHandled) { a = di - normZ; int j = 0; while(secularEquation(a, roh, z, D, n, G) < 0) { a -= normZ; assert(++j < 100); } boundaryHandled = 1; } else { prevNonZeroIdx = i - 1; while(G[SD[prevNonZeroIdx].i] != -1) // TODO: Take the first element is zero into consideration prevNonZeroIdx--; a = SD[prevNonZeroIdx].e; } b = di; } else { a = di; prevNonZeroIdx = i + 1; while(prevNonZeroIdx < n && G[SD[prevNonZeroIdx].i] != -1) { // TODO: Take the last element is zero into consideration prevNonZeroIdx++; } if (prevNonZeroIdx >= n) { b = di + normZ; int j = 0; while(secularEquation(b, roh, z, D, n, G) < 0) { b += normZ; assert(++j < 100); } } else { b = SD[prevNonZeroIdx].e; } } int j = 0; while (++j < maxIter) { // new lambda lambda = (a+b) / 2; // compute current function values fa = secularEquation(a, roh, z, D, n, G); flambda = secularEquation(lambda, roh, z, D, n, G); //fb = secularEquation(b, roh, z, D, n, G); // if a function value is inf, then it has probably not the right sign // initial function values are in +/- infinity, depending on the gradiend of the secular equation if (fa == INFINITY || fa == -INFINITY) fa = (roh > 0 ? -INFINITY : INFINITY); //if (fb == INFINITY || fb == -INFINITY) // fb = (roh > 0 ? INFINITY : -INFINITY); // if (isnan(a) || isnan(b) || isnan(lambda)) { // printf("interval: %g, %g, %g, %g, %g, %g %d\n", fa, flambda, fb, a, lambda, b, j); // printVector(z,n); // printf("%g\n",normZ); // MPI_ABORT(MPI_COMM_WORLD, 1); // } if (flambda == 0 || (b-a)/2 < 1e-14) break; // if sign(a) == sign(lambda) if ((fa >= 0 && flambda >= 0) || (fa < 0 && flambda < 0)) a = lambda; else b = lambda; } L[ind] = lambda; //printf("f(%g) = %g\n", lambda, secularEquation(lambda, roh, z, D, n, G)); } } free(SD); // printVector(z,n); // printVector(D,n); //printVector(L,n); } void computeNormalizationFactors(EVRepNode *node) { int* G = node->G; int n = node->n; node->N = malloc(n * sizeof(double)); double* N = node->N; // set normalization vector to 1, to compute unnormalized eigenvectors int i; #pragma omp parallel for default(shared) private(i) schedule(static) for (i = 0; i < n; ++i) { N[i] = 1; } // actual normalization vector double* Ntemp = malloc(n * sizeof(double)); // current ev double* ev = malloc(n * sizeof(double)); for (i = 0; i < n; ++i) { if (G[i] != -1) { Ntemp[i] = 1; } else { getEigenVector(node, ev, i); Ntemp[i] = cblas_dnrm2(n, ev, 1); } } node->N = Ntemp; free(ev); free(N); } void getEigenVector(EVRepNode *node, double* ev, int i) { double* D = node->D; double* z = node->z; double* L = node->L; double* N = node->N; double* C = node->C; double* S = node->S; int* G = node->G; int* P = node->P; int n = node->n; int numGR = node->numGR; // TODO compute i-th eigenvector and store in ev int j; if(G[i] != -1) { #pragma omp parallel for default(shared) private(j) schedule(static) for (j = 0; j < n; j++) { if (j == i){ ev[j] = 1; } else { ev[j] = 0; } } } else { #pragma omp parallel for default(shared) private(j) schedule(static) for (j = 0; j < n; j ++) if (G[j] < -1) { ev[j] = 0; } else { ev[j] = z[j] / ((D[j] - L[i]) * N[i]); // if (isinf(ev[j])) { // printVector(ev,n); // printVector(D,n); // printVector(L,n); // printVector(N,n); // printVector(z,n); // printf("test %d, %.20g %.20g\n", G[j], D[j],L[j]); // break; // } } } /* recover the original rank-one update * apply the inverse of Givens rotation from outside to inside * for example, if the Givens rotation on the original problem is * G3 * G2 * G1 * (D + zz') G1' * G2' * G3' * The order here should be G3^-1, G2^-1 nad G1^-1 */ // don't use openMP fur this loop, the rotations have to be applied in a certain order for (j = numGR - 1; j >= 0 ; j--) { int a, b; double s, c; double tmpi, tmpj; a = P[j]; b = G[a]; c = C[j]; s = S[j]; // TODO: probably it's better to store s as well, since the product c*c halves the precision (e^-10 * e^-10 = e^-20) tmpi = c * ev[a] + s * ev[b]; tmpj = -s * ev[a] + c * ev[b]; ev[a] = tmpi; ev[b] = tmpj; } }
ordering_op-inl.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) 2016 by Contributors * \file ordering_op-inl.h * \brief Function definition of matrix related operators */ #ifndef MXNET_OPERATOR_TENSOR_ORDERING_OP_INL_H_ #define MXNET_OPERATOR_TENSOR_ORDERING_OP_INL_H_ #include <mxnet/operator_util.h> #include <dmlc/optional.h> #include <mshadow/tensor.h> #include <algorithm> #include <vector> #include <type_traits> #include "../mshadow_op.h" #include "../elemwise_op_common.h" #include "./sort_op.h" #include "./indexing_op.h" namespace mshadow { template<typename xpu, int src_dim, typename DType, int dst_dim> inline Tensor<xpu, dst_dim, DType> inplace_reshape(Tensor<xpu, src_dim, DType> src, Shape<dst_dim> target_shape) { CHECK_EQ(src.CheckContiguous(), true); return Tensor<xpu, dst_dim, DType>(src.dptr_, target_shape, src.stream_); } }; namespace mxnet { namespace op { // These enums are only visible within this header namespace topk_enum { enum TopKReturnType {kReturnValue, kReturnIndices, kReturnMask, kReturnBoth}; } // topk_enum struct TopKParam : public dmlc::Parameter<TopKParam> { dmlc::optional<int> axis; int k; int ret_typ; bool is_ascend; DMLC_DECLARE_PARAMETER(TopKParam) { DMLC_DECLARE_FIELD(axis).set_default(dmlc::optional<int>(-1)) .describe("Axis along which to choose the top k indices." " If not given, the flattened array is used. Default is -1."); DMLC_DECLARE_FIELD(k).set_default(1) .describe("Number of top elements to select," " should be always smaller than or equal to the element number in the given axis." " A global sort is performed if set k < 1."); DMLC_DECLARE_FIELD(ret_typ).set_default(topk_enum::kReturnIndices) .add_enum("value", topk_enum::kReturnValue) .add_enum("indices", topk_enum::kReturnIndices) .add_enum("mask", topk_enum::kReturnMask) .add_enum("both", topk_enum::kReturnBoth) .describe("The return type.\n" " \"value\" means to return the top k values," " \"indices\" means to return the indices of the top k values," " \"mask\" means to return a mask array containing 0 and 1. 1 means the top k values." " \"both\" means to return a list of both values and indices of top k elements."); DMLC_DECLARE_FIELD(is_ascend).set_default(false) .describe("Whether to choose k largest or k smallest elements." " Top K largest elements will be chosen if set to false."); } }; struct SortParam : public dmlc::Parameter<SortParam> { dmlc::optional<int> axis; bool is_ascend; DMLC_DECLARE_PARAMETER(SortParam) { DMLC_DECLARE_FIELD(axis).set_default(dmlc::optional<int>(-1)) .describe("Axis along which to choose sort the input tensor." " If not given, the flattened array is used. Default is -1."); DMLC_DECLARE_FIELD(is_ascend).set_default(true) .describe("Whether to sort in ascending or descending order."); } }; struct ArgSortParam : public dmlc::Parameter<ArgSortParam> { dmlc::optional<int> axis; bool is_ascend; DMLC_DECLARE_PARAMETER(ArgSortParam) { DMLC_DECLARE_FIELD(axis).set_default(dmlc::optional<int>(-1)) .describe("Axis along which to sort the input tensor." " If not given, the flattened array is used. Default is -1."); DMLC_DECLARE_FIELD(is_ascend).set_default(true) .describe("Whether to sort in ascending or descending order."); } }; inline void ParseTopKParam(const TShape& src_shape, const TopKParam& param, TShape *target_shape, int *batch_size, int *element_num, int *axis, int *k, bool *do_transpose, bool *is_ascend) { *do_transpose = false; *k = param.k; *is_ascend = param.is_ascend; // get batch_size, axis and element_num if (!static_cast<bool>(param.axis)) { // No axis given *axis = 0; *batch_size = 1; *element_num = src_shape.Size(); } else { *axis = param.axis.value(); if (*axis < 0) { *axis += src_shape.ndim(); } CHECK(*axis >= 0 && *axis < static_cast<int>(src_shape.ndim())) << "Invalid axis! axis should be between 0 and " << src_shape.ndim() << ", found axis=" << *axis; *batch_size = src_shape.Size() / src_shape[*axis]; *element_num = src_shape[*axis]; if (*axis != static_cast<int>(src_shape.ndim()) - 1) { *do_transpose = true; } } // get k if (param.k <= 0) { *k = *element_num; } // get target_shape if (!static_cast<bool>(param.axis)) { if (param.ret_typ != topk_enum::kReturnMask) { *target_shape = mshadow::Shape1(*k); } else { *target_shape = src_shape; } } else { *target_shape = src_shape; if (param.ret_typ != topk_enum::kReturnMask) { (*target_shape)[*axis] = *k; } } CHECK(*k >= 1 && *k <= *element_num) << "k must be smaller than " << *element_num << ", get k = " << *k; } using namespace mshadow; template<typename xpu> void TopKSort(const Tensor<xpu, 1, real_t>& dat, const Tensor<xpu, 1, int>& ind, const Tensor<xpu, 1, char>& work, int K, int N, bool is_ascend, Stream<xpu> *s); template<> MSHADOW_FORCE_INLINE void TopKSort<cpu>(const Tensor<cpu, 1, real_t>& dat, const Tensor<cpu, 1, int>& ind, const Tensor<cpu, 1, char>& work, int K, int N, bool is_ascend, Stream<cpu> *s) { // Use full sort when K is relatively large. const bool full_sort(K*8 > N); // Batch size. const int M(work.size(0)/(sizeof(real_t)*N)); const int omp_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()); #pragma omp parallel for num_threads(omp_threads) for (int i = 0; i < M; ++i) { // Tensor `work` stores the flattened source data, while `dat` stores the sorted result. real_t *vals = reinterpret_cast<real_t*>(work.dptr_); real_t *sorted_vals = dat.dptr_+i*N; int *indices = ind.dptr_+i*N; if (is_ascend) { if (full_sort) { std::sort(indices, indices+N, [&](const int& i1, const int& i2){ return vals[i1] < vals[i2]; }); } else { std::partial_sort(indices, indices+K, indices+N, [&](const int& i1, const int& i2){ return vals[i1] < vals[i2]; }); } } else { if (full_sort) { std::sort(indices, indices+N, [&](const int& i1, const int& i2){ return vals[i1] > vals[i2]; }); } else { std::partial_sort(indices, indices+K, indices+N, [&](const int& i1, const int& i2){ return vals[i1] > vals[i2]; }); } } for (int j = 0; j < K; ++j) { sorted_vals[j] = vals[indices[j]]; } } } #ifdef __CUDACC__ template<typename DType> MSHADOW_XINLINE bool TopKCompare(DType val1, int ind1, DType val2, int ind2, bool is_ascend) { // Negative indices denote undefined values which are considered arbitrary small resp. large. return (ind2 < 0) || (ind1 >= 0 && ((is_ascend && val1 < val2) || (!is_ascend && val1 > val2))); } template<typename DType> MSHADOW_XINLINE void MergeTopK(int K, DType *val1, int *ind1, DType *val2, int *ind2, bool is_ascend) { // In-place merge of two sorted top-K lists into val1/ind1. First determine the intervals // [0,..,i1], [0,..i2] of the two lists that will be part of the merged list. int i1(K-1), i2(K-1); for (int i = 0; i < K; ++i) { if (TopKCompare(val1[i1], ind1[i1], val2[i2], ind2[i2], is_ascend)) { --i2; } else { --i1; } } // Now merge the lists from back to front. for (int i = K; i--;) { if (i2 < 0 || i1 >= 0 && TopKCompare(val2[i2], ind2[i2], val1[i1], ind1[i1], is_ascend)) { val1[i] = val1[i1]; ind1[i] = ind1[i1]; --i1; } else { val1[i] = val2[i2]; ind1[i] = ind2[i2]; --i2; } } } template<typename DType> __global__ void PartialSortSmallK(int K, int N, DType *val, int *ind, bool is_ascend) { // Buffer for pairwise reduction. extern __shared__ int buff[]; // Start of buffer sections associated with this thread. const int offset(threadIdx.x*K); int *ind_buff = &buff[offset]; DType *val_buff = reinterpret_cast<DType*>(&buff[blockDim.x*K])+offset; // Initialize top-K values for this thread. for (int i = 0; i < K; ++i) { ind_buff[i] = -1; } // Range of values this thread cares about. Each thread block processes // a different batch item (i.e. a different set of ind/val where we // have to select the top-K elements). All threads within the same // block work on the same batch item. const int first(blockIdx.x*N+threadIdx.x), last((blockIdx.x+1)*N); // Select top-K from this range and store it sorted in the buffer. // We assume a small K, so linear insertion is o.k. for (int i = first; i < last; i += blockDim.x) { DType cur_val(val[i]); int cur_ind(ind[i]); for (int j = K; j-- && TopKCompare(cur_val, cur_ind, val_buff[j], ind_buff[j], is_ascend); ) { if (j+1 < K) { val_buff[j+1] = val_buff[j]; ind_buff[j+1] = ind_buff[j]; } val_buff[j] = cur_val; ind_buff[j] = cur_ind; } } // Recursive merge of sorted lists for this thread block. Note that blockDim.x is not // necessary a power of two, therefore the additional checks for last_s. for (unsigned int s = (blockDim.x+1)/2, last_s = blockDim.x; last_s > 1; last_s = s, s = (s+1)/2) { __syncthreads(); if (threadIdx.x < s && threadIdx.x+s < last_s) { MergeTopK(K, val_buff, ind_buff, val_buff+s*K, ind_buff+s*K, is_ascend); } } // Final updates on master thread. if (threadIdx.x == 0) { for (int i = 0; i < K; ++i) { ind[blockIdx.x*N+i] = ind_buff[i]; val[blockIdx.x*N+i] = val_buff[i]; } } } template<> MSHADOW_FORCE_INLINE void TopKSort<gpu>(const Tensor<gpu, 1, real_t>& dat, const Tensor<gpu, 1, int>& ind, const Tensor<gpu, 1, char>& work, int K, int N, bool is_ascend, Stream<gpu> *s) { // Use full sort for all but very small K for which we // can do a partial sort entirely within shared memory. const bool full_sort(K > 5); // Batch size. const int M(dat.size(0)/N); if (full_sort) { // Divide workspace into two parts. The first one is needed to store batch ids. const int id_size(sizeof(int)*ind.size(0)); Tensor<gpu, 1, int> batch_id(reinterpret_cast<int*>(work.dptr_), Shape1(ind.size(0)), s); Tensor<gpu, 1, char> sort_work(work.dptr_+id_size, Shape1(work.size(0)-id_size), s); mxnet::op::SortByKey(dat, ind, is_ascend, &sort_work); if (M > 1) { // Back to back sorting. Note that mxnet::op::SortByKey is a stable sort. batch_id = ind / N; mxnet::op::SortByKey(batch_id, dat, true, &sort_work); batch_id = ind / N; mxnet::op::SortByKey(batch_id, ind, true, &sort_work); } } else { const int nthreads(mshadow::cuda::kBaseThreadNum); PartialSortSmallK<<<M, nthreads, nthreads*K*(sizeof(int)+sizeof(real_t)), mshadow::Stream<gpu>::GetStream(s)>>> (K, N, dat.dptr_, ind.dptr_, is_ascend); } } #endif /*! * \brief Implementation of the TopK operation * * * \param ctx the running context * \param resource temporary resource handler * \param src the Source blob * \param ret the destination blobs * \param k the K elements to keep * \param param the topk parameters * \tparam xpu the device type. */ template<typename xpu> void TopKImpl(RunContext ctx, Resource resource, const TBlob& src, const std::vector<TBlob>& ret, const TopKParam& param) { using namespace mshadow; using namespace mshadow::expr; for (auto ret_ele : ret) { CHECK_EQ(ret_ele.type_flag_, src.type_flag_); } // 1. Parse and initialize information Stream<xpu> *s = ctx.get_stream<xpu>(); Tensor<xpu, 1, char> workspace; Tensor<xpu, 1, char> temp_workspace; Tensor<xpu, 1, real_t> sorted_dat; Tensor<xpu, 1, int> indices, sel_indices; Tensor<xpu, 2, real_t> mask_val; int batch_size, element_num; // number of batches + the size of each batch int axis = 0; bool do_transpose = false; bool is_ascend = false; int k = 0; TShape target_shape; ParseTopKParam(src.shape_, param, &target_shape, &batch_size, &element_num, &axis, &k, &do_transpose, &is_ascend); Tensor<xpu, 3, real_t> dat = src.FlatTo3D<xpu, real_t>(axis, axis, s); size_t temp_size = 0; // Temp space needed by the gpu-based full sorts. temp_size = std::max(temp_size, mxnet::op::SortByKeyWorkspaceSize<int, int, xpu>(src.Size())); temp_size = std::max(temp_size, mxnet::op::SortByKeyWorkspaceSize<int, real_t, xpu>(src.Size())); temp_size = std::max(temp_size, mxnet::op::SortByKeyWorkspaceSize<real_t, int, xpu>(src.Size())); // Additional temp space for gpu full sorts for batch ids. temp_size += sizeof(int) * src.Size(); // Temp space for cpu sorts. temp_size = std::max(temp_size, sizeof(real_t) * src.Size()); size_t workspace_size = temp_size + sizeof(real_t) * src.Size() + sizeof(int) * src.Size(); if (param.ret_typ == topk_enum::kReturnMask) { workspace_size += sizeof(int) * batch_size * k + sizeof(real_t) * batch_size * k; } workspace = resource.get_space_typed<xpu, 1, char>(Shape1(workspace_size), s); char* workspace_curr_ptr = workspace.dptr_; sorted_dat = Tensor<xpu, 1, real_t>(reinterpret_cast<real_t*>(workspace_curr_ptr), Shape1(src.Size()), s); // contain sorted dat workspace_curr_ptr += sizeof(real_t) * src.Size(); indices = Tensor<xpu, 1, int>(reinterpret_cast<int*>(workspace_curr_ptr), Shape1(src.Size()), s); // indices in the original matrix workspace_curr_ptr += sizeof(int) * src.Size(); if (param.ret_typ == topk_enum::kReturnMask) { sel_indices = Tensor<xpu, 1, int>(reinterpret_cast<int*>(workspace_curr_ptr), Shape1(batch_size * k), s); workspace_curr_ptr += sizeof(int) * batch_size * k; mask_val = Tensor<xpu, 2, real_t>(reinterpret_cast<real_t*>(workspace_curr_ptr), Shape2(batch_size * k, 1), s); workspace_curr_ptr += sizeof(real_t) * batch_size * k; mask_val = scalar<real_t>(1); CHECK_EQ(sel_indices.CheckContiguous(), true); CHECK_EQ(mask_val.CheckContiguous(), true); } if (std::is_same<xpu, cpu>::value) { Tensor<xpu, 1, real_t> flattened_data; if (do_transpose) { flattened_data = Tensor<xpu, 1, real_t>(reinterpret_cast<real_t*>(workspace_curr_ptr), Shape1(src.Size()), s); workspace_curr_ptr += sizeof(real_t) * src.Size(); flattened_data = reshape(transpose(dat, Shape3(0, 2, 1)), Shape1(src.Size())); CHECK_EQ(flattened_data.CheckContiguous(), true); } else { flattened_data = src.FlatTo1D<xpu, real_t>(s); } // `temp_workspace` stores the flattened data temp_workspace = Tensor<xpu, 1, char>(reinterpret_cast<char*>(flattened_data.dptr_), Shape1(sizeof(real_t)*src.Size()), s); CHECK_EQ(temp_workspace.CheckContiguous(), true); } else { if (do_transpose) { sorted_dat = reshape(transpose(dat, Shape3(0, 2, 1)), Shape1(src.Size())); } else { sorted_dat = reshape(dat, Shape1(src.Size())); } CHECK_EQ(sorted_dat.CheckContiguous(), true); temp_workspace = Tensor<xpu, 1, char>(workspace_curr_ptr, Shape1(temp_size), s); // temp space workspace_curr_ptr += temp_size; } mxnet_op::Kernel<range_fwd, xpu>::Launch(s, batch_size * element_num, 1, 0, 1, kWriteTo, indices.dptr_); CHECK_EQ(indices.CheckContiguous(), true); // 2. Perform inplace batch sort. // After sorting, each batch in `sorted_dat` will be sorted in the corresponding order // up to the k-th element and the `indices` will contain the corresponding index in `sorted_dat` // `temp_workspace` is used to store the flattend source data for CPU device, and it's used as // a temporal buffer for GPU device. TopKSort(sorted_dat, indices, temp_workspace, k, element_num, is_ascend, s); // 3. Assign results to the ret blob // When returning indices, only update(modulo) required elements instead of full elements // to avoid redundant calculation. if (param.ret_typ == topk_enum::kReturnMask) { Tensor<xpu, 2, real_t> ret_mask = ret[0].get_with_shape<xpu, 2, real_t>(Shape2(ret[0].Size(), 1), s); ret_mask = scalar<real_t>(0); sel_indices = reshape(slice<1>( inplace_reshape(indices, Shape2(batch_size, element_num)), 0, k), Shape1(batch_size * k)); if (do_transpose) { TShape src_shape = src.shape_.FlatTo3D(axis); CHECK_EQ(sel_indices.CheckContiguous(), true); sel_indices = transpose_indices(sel_indices, Shape3(src_shape[0], src_shape[2], src_shape[1]), Shape3(0, 2, 1)); } IndexFill(ret_mask, sel_indices, mask_val); } else if (param.ret_typ == topk_enum::kReturnIndices) { if (do_transpose) { Tensor<xpu, 3, real_t> ret_indices = ret[0].FlatTo3D<xpu, real_t>(axis, axis, s); ret_indices = tcast<real_t>(transpose( slice<2>(inplace_reshape(indices, Shape3(ret_indices.shape_[0], ret_indices.shape_[2], element_num)), 0, k), Shape3(0, 2, 1))); ret_indices = F<mshadow_op::mod>(ret_indices, element_num); } else { Tensor<xpu, 2, real_t> ret_indices = ret[0].get_with_shape<xpu, 2, real_t>(Shape2(batch_size, k), s); ret_indices = tcast<real_t>(slice<1>( inplace_reshape(indices, Shape2(batch_size, element_num)), 0, k)); ret_indices = F<mshadow_op::mod>(ret_indices, element_num); } } else { if (do_transpose) { Tensor<xpu, 3, real_t> ret_value = ret[0].FlatTo3D<xpu, real_t>(axis, axis, s); Tensor<xpu, 3, real_t> ret_indices = ret[1].FlatTo3D<xpu, real_t>(axis, axis, s); ret_value = transpose( slice<2>(inplace_reshape(sorted_dat, Shape3(ret_value.shape_[0], ret_value.shape_[2], element_num)), 0, k), Shape3(0, 2, 1)); ret_indices = tcast<real_t>(transpose( slice<2>(inplace_reshape(indices, Shape3(ret_indices.shape_[0], ret_indices.shape_[2], element_num)), 0, k), Shape3(0, 2, 1))); ret_indices = F<mshadow_op::mod>(ret_indices, element_num); } else { Tensor<xpu, 2, real_t> ret_value = ret[0].get_with_shape<xpu, 2, real_t>(Shape2(batch_size, k), s); Tensor<xpu, 2, real_t> ret_indices = ret[1].get_with_shape<xpu, 2, real_t>(Shape2(batch_size, k), s); ret_value = slice<1>(inplace_reshape(sorted_dat, Shape2(batch_size, element_num)), 0, k); ret_indices = tcast<real_t>(slice<1>( inplace_reshape(indices, Shape2(batch_size, element_num)), 0, k)); ret_indices = F<mshadow_op::mod>(ret_indices, element_num); } } } template<typename xpu> void TopK(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); // TODO(sxjscience) We can support inplace in the future CHECK_EQ(req[0], kWriteTo) << "TopK does not support inplace"; TopKImpl<xpu>(ctx.run_ctx, ctx.requested[0], inputs[0], outputs, param); } template<typename xpu> void Sort(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const SortParam& param = nnvm::get<SortParam>(attrs.parsed); CHECK_EQ(req[0], kWriteTo) << "Sort does not support inplace"; TopKParam topk_param; topk_param.axis = param.axis; topk_param.is_ascend = param.is_ascend; topk_param.k = 0; topk_param.ret_typ = topk_enum::kReturnValue; TopKImpl<xpu>(ctx.run_ctx, ctx.requested[0], inputs[0], outputs, topk_param); } template<typename xpu> void ArgSort(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const ArgSortParam& param = nnvm::get<ArgSortParam>(attrs.parsed); CHECK_EQ(req[0], kWriteTo) << "ArgSort does not support inplace"; TopKParam topk_param; topk_param.axis = param.axis; topk_param.is_ascend = param.is_ascend; topk_param.k = 0; topk_param.ret_typ = topk_enum::kReturnIndices; TopKImpl<xpu>(ctx.run_ctx, ctx.requested[0], inputs[0], outputs, topk_param); } template<typename xpu> void TopKBackward_(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { CHECK_NE(req[0], kWriteInplace); using namespace mshadow; using namespace mshadow::expr; Stream<xpu> *s = ctx.run_ctx.get_stream<xpu>(); const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); CHECK(param.ret_typ == topk_enum::kReturnValue || param.ret_typ == topk_enum::kReturnBoth); int batch_size, element_num; // number of batches + the size of each batch int axis = 0; bool do_transpose = false; bool is_ascend = false; int k = 0; TShape target_shape; ParseTopKParam(outputs[0].shape_, param, &target_shape, &batch_size, &element_num, &axis, &k, &do_transpose, &is_ascend); Tensor<xpu, 1, real_t> workspace = ctx.requested[0].get_space_typed<xpu, 1, real_t>(Shape1(batch_size * k * 2 + batch_size), s); Tensor<xpu, 1, real_t> sel_indices = Tensor<xpu, 1, real_t>(workspace.dptr_, Shape1(batch_size * k), s); Tensor<xpu, 1, real_t> batch_shift = Tensor<xpu, 1, real_t>(workspace.dptr_ + batch_size * k, Shape1(batch_size), s); Tensor<xpu, 1, real_t> dummy_index = Tensor<xpu, 1, real_t>(workspace.dptr_ + batch_size * k + batch_size, Shape1(batch_size * k), s); Tensor<xpu, 2, real_t> out_grad = inputs[0].get_with_shape<xpu, 2, real_t>(Shape2(inputs[0].shape_.Size(), 1), s); Tensor<xpu, 2, real_t> in_grad = outputs[0].get_with_shape<xpu, 2, real_t>(Shape2(outputs[0].shape_.Size(), 1), s); mxnet_op::Kernel<range_fwd, xpu>::Launch(s, batch_size, 1, 0.0f, static_cast<real_t>(element_num), kWriteTo, batch_shift.dptr_); if (do_transpose) { Tensor<xpu, 1, real_t> indices = inputs[2].FlatTo1D<xpu, real_t>(s); TShape src_shape = outputs[0].shape_.FlatTo3D(axis); sel_indices = reshape(transpose( broadcast_to(inplace_reshape(batch_shift, Shape3(src_shape[0], src_shape[2], 1)), TShape(Shape3(src_shape[0], src_shape[2], k))), Shape3(0, 2, 1)), Shape1(batch_size * k)); sel_indices += indices; sel_indices = transpose_indices(sel_indices, Shape3(src_shape[0], src_shape[2], src_shape[1]), Shape3(0, 2, 1)); } else { Tensor<xpu, 2, real_t> indices = inputs[2].get_with_shape<xpu, 2, real_t>(Shape2(batch_size, k), s); sel_indices = reshape(indices + broadcast_to(inplace_reshape(batch_shift, Shape2(batch_size, 1)), TShape(Shape2(batch_size, k))), Shape1(batch_size * k)); } CHECK_EQ(sel_indices.CheckContiguous(), true); if (kWriteTo == req[0]) { in_grad = scalar<real_t>(0); IndexFill(in_grad, sel_indices, out_grad); } else if (kAddTo == req[0]) { // TODO(sxjscience) We can use AddTakeGrad in the future. // However, the current implementation of AddTakeGrad is not so efficient. mxnet_op::Kernel<range_fwd, xpu>::Launch(s, sel_indices.shape_.Size(), 1, 0.0f, 1.0f, kWriteTo, dummy_index.dptr_); mxnet::op::AddTakeGradLargeBatch(in_grad, sel_indices, dummy_index, out_grad); } else if (kNullOp == req[0]) { return; } else { LOG(FATAL) << "Not Implemented!"; } } inline uint32_t TopKNumOutputs(const NodeAttrs& attrs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); if (param.ret_typ == topk_enum::kReturnIndices || param.ret_typ == topk_enum::kReturnMask) { return static_cast<uint32_t>(1); } else { return static_cast<uint32_t>(2); } } inline uint32_t TopKNumVisibleOutputs(const NodeAttrs& attrs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); if (param.ret_typ == topk_enum::kReturnBoth) { return static_cast<uint32_t>(2); } else { return static_cast<uint32_t>(1); } } inline bool TopKType(const nnvm::NodeAttrs& attrs, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { return ElemwiseAttr<int, type_is_none, type_assign, true, type_string>( attrs, in_attrs, out_attrs, -1); } inline bool TopKShapeImpl(const TopKParam& param, std::vector<TShape> *in_attrs, std::vector<TShape> *out_attrs) { CHECK_EQ(in_attrs->size(), 1U); if (param.ret_typ == topk_enum::kReturnIndices || param.ret_typ == topk_enum::kReturnMask) { CHECK_EQ(out_attrs->size(), 1U); } else { CHECK_EQ(out_attrs->size(), 2U); } TShape& in_shape = (*in_attrs)[0]; int batch_size, element_num; // number of batches + the size of each batch int axis = 0; bool do_transpose = false; bool is_ascend = false; int k = 0; TShape target_shape; ParseTopKParam(in_shape, param, &target_shape, &batch_size, &element_num, &axis, &k, &do_transpose, &is_ascend); if (param.ret_typ == topk_enum::kReturnIndices || param.ret_typ == topk_enum::kReturnMask) { SHAPE_ASSIGN_CHECK(*out_attrs, 0, target_shape); } else { SHAPE_ASSIGN_CHECK(*out_attrs, 0, target_shape); SHAPE_ASSIGN_CHECK(*out_attrs, 1, target_shape); } return true; } inline bool TopKShape(const nnvm::NodeAttrs& attrs, std::vector<TShape> *in_attrs, std::vector<TShape> *out_attrs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); return TopKShapeImpl(param, in_attrs, out_attrs); } inline bool SortShape(const nnvm::NodeAttrs& attrs, std::vector<TShape> *in_attrs, std::vector<TShape> *out_attrs) { const SortParam& param = nnvm::get<SortParam>(attrs.parsed); TopKParam topk_param; topk_param.axis = param.axis; topk_param.is_ascend = param.is_ascend; topk_param.k = 0; topk_param.ret_typ = topk_enum::kReturnValue; return TopKShapeImpl(topk_param, in_attrs, out_attrs); } inline bool ArgSortShape(const nnvm::NodeAttrs& attrs, std::vector<TShape> *in_attrs, std::vector<TShape> *out_attrs) { const ArgSortParam& param = nnvm::get<ArgSortParam>(attrs.parsed); TopKParam topk_param; topk_param.axis = param.axis; topk_param.is_ascend = param.is_ascend; topk_param.k = 0; topk_param.ret_typ = topk_enum::kReturnIndices; return TopKShapeImpl(topk_param, in_attrs, out_attrs); } } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_TENSOR_ORDERING_OP_INL_H_
GB_binop__bset_int32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary 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_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__bset_int32) // A.*B function (eWiseMult): GB (_AemultB_08__bset_int32) // A.*B function (eWiseMult): GB (_AemultB_02__bset_int32) // A.*B function (eWiseMult): GB (_AemultB_04__bset_int32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bset_int32) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bset_int32) // C+=b function (dense accum): GB (_Cdense_accumb__bset_int32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bset_int32) // C=scalar+B GB (_bind1st__bset_int32) // C=scalar+B' GB (_bind1st_tran__bset_int32) // C=A+scalar GB (_bind2nd__bset_int32) // C=A'+scalar GB (_bind2nd_tran__bset_int32) // C type: int32_t // A type: int32_t // A pattern? 0 // B type: int32_t // B pattern? 0 // BinaryOp: cij = GB_BITSET (aij, bij, int32_t, 32) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ int32_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) \ int32_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) \ int32_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) \ int32_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 = GB_BITSET (x, y, int32_t, 32) ; // 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_BSET || GxB_NO_INT32 || GxB_NO_BSET_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 //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__bset_int32) ( 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__bset_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 { #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__bset_int32) ( 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 int32_t int32_t bwork = (*((int32_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 //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 int32_t *restrict Cx = (int32_t *) 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, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *restrict Cx = (int32_t *) 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__bset_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 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) ; int32_t alpha_scalar ; int32_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int32_t *) alpha_scalar_in)) ; beta_scalar = (*((int32_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__bset_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__bset_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__bset_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__bset_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__bset_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 int32_t *Cx = (int32_t *) 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] = GB_BITSET (x, bij, int32_t, 32) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bset_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 ; int32_t *Cx = (int32_t *) 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] = GB_BITSET (aij, y, int32_t, 32) ; } 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] = GB_BITSET (x, aij, int32_t, 32) ; \ } GrB_Info GB (_bind1st_tran__bset_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] = GB_BITSET (aij, y, int32_t, 32) ; \ } GrB_Info GB (_bind2nd_tran__bset_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